diff --git a/public/scripts/extensions/objective/index.js b/public/scripts/extensions/objective/index.js index 052f40416..d2d675e71 100644 --- a/public/scripts/extensions/objective/index.js +++ b/public/scripts/extensions/objective/index.js @@ -12,7 +12,7 @@ const MODULE_NAME = "Objective" let globalObjective = "" let globalTasks = [] let currentChatId = "" -let currentTask = {} +let currentTask = null let checkCounter = 0 @@ -38,9 +38,7 @@ const objectivePrompts = { ` } -const injectPrompts = { - "task": "Your current task is [{{task}}]. Balance existing roleplay with completing this task." -} +const extensionPrompt = "Your current task is [{{task}}]. Balance existing roleplay with completing this task." // Background prompt generation async function generateQuietPrompt(quiet_prompt) { @@ -59,69 +57,63 @@ async function generateQuietPrompt(quiet_prompt) { //# Task Management #// //###############################// -// Accepts optional position. Defaults to adding to end of list. -function addTask(description, position = null) { - position = position != null ? position : position = globalTasks.length - globalTasks.splice(position, 0, { - "description": description, - "completed": false - }) +// Accepts optional index. Defaults to adding to end of list. +function addTask(description, index = null) { + index = index != null ? index: index = globalTasks.length + globalTasks.splice(index, 0, new ObjectiveTask( + {description: description} + )) saveState() } -// Get a task either by index or task description. Return current task if none specified -function getTask(index = null, taskDescription = null) { - let task = {} - if (index == null && taskDescription == null) { - task = currentTask - } else if (index != null) { - task = globalObjective[index] - } else if (taskDescription != null) { - task = globalTasks.find(task => { - return task.description == description ? true : false - }) +// Return the task and index or throw an error +function getTaskById(taskId){ + if (taskId == null) { + throw `Null task id` + } + const index = globalTasks.findIndex((task) => task.id === taskId); + if (index !== -1) { + return { task: globalTasks[index], index: index }; + } else { + throw `Cannot find task with ${taskId}` + } - return task } -function deleteTask(index) { +function deleteTask(taskId){ + const { task, index } = getTaskById(taskId) + globalTasks.splice(index, 1) setCurrentTask() updateUiTaskList() } -// Complete the current task, setting next task to next incomplete task -function completeTask(task) { - task.completed = true - console.info(`Task successfully completed: ${JSON.stringify(task)}`) - setCurrentTask() - updateUiTaskList() -} - // Call Quiet Generate to create task list using character context, then convert to tasks. Should not be called much. async function generateTasks() { const prompt = substituteParams(objectivePrompts["createTask"].replace(/{{objective}}/gi, globalObjective)); console.log(`Generating tasks for objective with prompt`) toastr.info('Generating tasks for objective', 'Please wait...'); const taskResponse = await generateQuietPrompt(prompt) + + // Clear all existing global tasks when generating globalTasks = [] const numberedListPattern = /^\d+\./ - // Add numbered tasks, store them without the numbers. + // Create tasks from generated task list for (const task of taskResponse.split('\n').map(x => x.trim())) { if (task.match(numberedListPattern) != null) { - addTask(task.replace(numberedListPattern, '').trim()) + addTask(task.replace(numberedListPattern,"").trim()) } } updateUiTaskList() - console.info(`Response for Objective: '${globalObjective}' was \n'${taskResponse}', \nwhich created tasks \n${JSON.stringify(globalTasks, null, 2)} `) + console.info(`Response for Objective: '${globalObjective}' was \n'${taskResponse}', \nwhich created tasks \n${JSON.stringify(globalTasks.map(v => {return v.toSaveState()}), null, 2)} `) toastr.success(`Generated ${globalTasks.length} tasks`, 'Done!'); } // Call Quiet Generate to check if a task is completed async function checkTaskCompleted() { // Make sure there are tasks - if (Object.keys(currentTask).length == 0) { + if (jQuery.isEmptyObject(currentTask)) { return } checkCounter = $('#objective-check-frequency').val() @@ -131,8 +123,8 @@ async function checkTaskCompleted() { // Check response if task complete if (taskResponse.includes("true")) { - console.info(`Character determined task '${JSON.stringify(currentTask)} is completed.`) - completeTask(getTask()) + console.info(`Character determined task '${JSON.stringify(currentTask.toSaveState())} is completed.`) + currentTask.completeTask() } else if (!(taskResponse.includes("false"))) { console.warn(`checkTaskCompleted response did not contain true or false. taskResponse: ${taskResponse}`) } else { @@ -142,21 +134,26 @@ async function checkTaskCompleted() { // Set a task in extensionPrompt context. Defaults to first incomplete -function setCurrentTask(index = null) { +function setCurrentTask(taskId = null) { const context = getContext(); currentTask = {}; - if (index === null) { + // Set current task to either the next incomplete task, or the index + if (taskId === null) { currentTask = globalTasks.find(task => !task.completed) || {}; - } else if (index >= 0 && index < globalTasks.length) { + } else { + const { _, index } = getTaskById(taskId) currentTask = globalTasks[index]; } - const { description } = currentTask; - const injectPromptsTask = injectPrompts["task"].replace(/{{task}}/gi, description); + // Get the task description and add to extension prompt + const description = currentTask.description || null; + + // Now update the extension prompt if (description) { - context.setExtensionPrompt(MODULE_NAME, injectPromptsTask, 1, $('#objective-chat-depth').val()); + const extensionPromptText = extensionPrompt.replace(/{{task}}/gi, description); + context.setExtensionPrompt(MODULE_NAME, extensionPromptText, 1, $('#objective-chat-depth').val()); console.info(`Current task in context.extensionPrompts.Objective is ${JSON.stringify(context.extensionPrompts.Objective)}`); } else { context.setExtensionPrompt(MODULE_NAME, ''); @@ -166,7 +163,114 @@ function setCurrentTask(index = null) { saveState(); } +let taskIdCounter = 0 +function getNextTaskId(){ + // Make sure id does not exist + while (globalTasks.find(task => task.id == taskIdCounter) != undefined) { + taskIdCounter += 1 + } + const nextId = taskIdCounter + console.log(`TaskID assigned: ${nextId}`) + taskIdCounter += 1 + return nextId +} +class ObjectiveTask { + id + description + completed + parent + children + // UI Elements + taskHtml + descriptionSpan + completedCheckbox + deleteTaskButton + addTaskButton + + constructor ({id=undefined, description, completed=false, parent=null}) { + this.description = description + this.parent = parent + this.children = [] + this.completed = completed + + // Generate a new ID if none specified + if (id==undefined){ + this.id = getNextTaskId() + } else { + this.id=id + } + } + + + // Complete the current task, setting next task to next incomplete task + completeTask() { + this.completed = true + console.info(`Task successfully completed: ${JSON.stringify(this.description)}`) + setCurrentTask() + updateUiTaskList() + } + + // Add a single task to the UI and attach event listeners for user edits + addUiElement() { + const template = ` +