From 460030d6001f83422d3d5638169cb3716baee980 Mon Sep 17 00:00:00 2001 From: ouoertheo Date: Sat, 3 Jun 2023 13:59:26 -0500 Subject: [PATCH 1/3] task class --- public/scripts/extensions/objective/index.js | 187 ++++++++++++------- 1 file changed, 119 insertions(+), 68 deletions(-) diff --git a/public/scripts/extensions/objective/index.js b/public/scripts/extensions/objective/index.js index 74ab41719..8c87f01af 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 @@ -59,13 +59,13 @@ 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( + index, + description, + )) saveState() } @@ -75,7 +75,7 @@ function getTask(index = null, taskDescription = null) { if (index == null && taskDescription == null) { task = currentTask } else if (index != null) { - task = globalObjective[index] + task = globalTasks[index] } else if (taskDescription != null) { task = globalTasks.find(task => { return task.description == description ? true: false @@ -90,27 +90,21 @@ function deleteTask(index){ 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() @@ -121,7 +115,7 @@ async function generateTasks() { // 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 (currentTask == null) { return } checkCounter = $('#objective-check-frequency').val() @@ -166,7 +160,104 @@ function setCurrentTask(index = null) { saveState(); } +class ObjectiveTask { + // Task State + index + description + completed + parent + children + // UI Elements + taskHtml + descriptionSpan + completedCheckbox + deleteTaskButton + addTaskButton + + constructor (index, description, parent=null) { + this.index = index + this.description = description + this.parent = parent + } + + + // 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 = ` +
+ ${this.index} + + ${this.description} +
+
+

+ `; + + // Add the filled out template + $('#objective-tasks').append(template); + + this.completedCheckbox = $(`#objective-task-complete-${this.index}`); + this.descriptionSpan = $(`#objective-task-description-${this.index}`); + this.addButton = $(`#objective-task-add-${this.index}`); + this.deleteButton = $(`#objective-task-delete-${this.index}`); + + // Add event listeners and set properties + $(`#objective-task-complete-${this.index}`).prop('checked', this.completed); + $(`#objective-task-complete-${this.index}`).on('click', this.onCompleteClick); + $(`#objective-task-description-${this.index}`).on('keyup', this.onDescriptionUpdate); + $(`#objective-task-delete-${this.index}`).on('click', this.onDeleteClick); + $(`#objective-task-add-${this.index}`).on('click', this.onAddClick); + } + + onCompleteClick(){ + this.completed = this.completedCheckbox.val() + setCurrentTask(); + } + + onDescriptionUpdate(){ + this.description = this.descriptionSpan.val(); + } + + onDeleteClick(){ + deleteTask(this.index); + } + + onAddClick(){ + addTask("", this.index + 1); + setCurrentTask(); + updateUiTaskList(); + } + + toString() { + return { + "index":this.index, + "description":this.description, + "completed":this.completed, + } + } +} + +class TaskManager { + tasks = {} + + constructor (){ + } + + addTask (description, index, parent) { + if (this.tasks){} + } + + deleteTask (index) +} //###############################// //# UI AND Settings #// @@ -194,9 +285,12 @@ function saveState() { currentChatId = context.chatId } + // Convert globalTasks for saving + const tasks = globalTasks.map(taskString => {return taskString.toString()}) + chat_metadata['objective'] = { objective: globalObjective, - tasks: globalTasks, + tasks: tasks, checkFrequency: $('#objective-check-frequency').val(), chatDepth: $('#objective-chat-depth').val(), hideTasks: $('#objective-hide-tasks').prop('checked'), @@ -219,56 +313,13 @@ function debugObjectiveExtension() { window.debugObjectiveExtension = debugObjectiveExtension - -// Add a single task to the UI and attach event listeners for user edits -function addUiTask(taskIndex, taskComplete, taskDescription) { - const template = ` -
- ${taskIndex} - - ${taskDescription} -
-
-

- `; - - // Add the filled out template - $('#objective-tasks').append(template); - - // Add event listeners and set properties - $(`#objective-task-complete-${taskIndex}`).prop('checked', taskComplete); - $(`#objective-task-complete-${taskIndex}`).on('click', event => { - const index = Number(event.target.id.split('-').pop()); - globalTasks[index].completed = event.target.checked; - setCurrentTask(); - }); - $(`#objective-task-description-${taskIndex}`).on('keyup', event => { - const index = Number(event.target.id.split('-').pop()); - globalTasks[index].description = event.target.textContent; - }); - $(`#objective-task-delete-${taskIndex}`).on('click', event => { - const index = Number(event.target.id.split('-').pop()); - deleteTask(index) - }); - $(`#objective-task-add-${taskIndex}`).on('click', event => { - const index = Number(event.target.id.split('-').pop()) + 1; - addTask("", index) - setCurrentTask() - updateUiTaskList() - }); -} - // Populate UI task list function updateUiTaskList() { $('#objective-tasks').empty() // Show tasks if there are any if (globalTasks.length > 0){ - for (const index in globalTasks) { - addUiTask( - index, - globalTasks[index].completed, - globalTasks[index].description - ) + for (const task of globalTasks) { + task.addUiElement() } } else { // Show button to add tasks if there are none @@ -283,7 +334,7 @@ function updateUiTaskList() { } } -function addManualTaskCheck() { +function addManualTaskCheckUi() { $('#extensionsMenu').prepend(`
@@ -386,7 +437,7 @@ jQuery(() => {
`; - addManualTaskCheck() + addManualTaskCheckUi() $('#extensions_settings').append(settingsHtml); $('#objective-generate').on('click', onGenerateObjectiveClick) $('#objective-chat-depth').on('input', onChatDepthInput) From 8ac368e2ef438559a4cbb6b267a6e46f40c25ef2 Mon Sep 17 00:00:00 2001 From: ouoertheo Date: Sat, 3 Jun 2023 14:41:59 -0500 Subject: [PATCH 2/3] probably not gonna work well --- public/scripts/extensions/objective/index.js | 36 +++++++++++--------- 1 file changed, 20 insertions(+), 16 deletions(-) diff --git a/public/scripts/extensions/objective/index.js b/public/scripts/extensions/objective/index.js index 8c87f01af..f172ccdbe 100644 --- a/public/scripts/extensions/objective/index.js +++ b/public/scripts/extensions/objective/index.js @@ -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) { @@ -126,7 +124,7 @@ async function checkTaskCompleted() { // Check response if task complete if (taskResponse.includes("true")) { console.info(`Character determined task '${JSON.stringify(currentTask)} is completed.`) - completeTask(getTask()) + currentTask.completeTask() } else if (!(taskResponse.includes("false"))) { console.warn(`checkTaskCompleted response did not contain true or false. taskResponse: ${taskResponse}`) } else { @@ -140,17 +138,23 @@ function setCurrentTask(index = null) { const context = getContext(); currentTask = {}; + // Set current task to either the next incomplete task, or the index if valid value is specified if (index === null) { currentTask = globalTasks.find(task => !task.completed) || {}; - } else if (index >= 0 && index < globalTasks.length) { + } else { + if (index >= 0 && index < globalTasks.length){ + toastr.error(`Invalide task index ${index} specified. Must be between 0 and ${globalTasks.length}`) + return + } 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; 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, ''); @@ -212,10 +216,10 @@ class ObjectiveTask { // Add event listeners and set properties $(`#objective-task-complete-${this.index}`).prop('checked', this.completed); - $(`#objective-task-complete-${this.index}`).on('click', this.onCompleteClick); - $(`#objective-task-description-${this.index}`).on('keyup', this.onDescriptionUpdate); - $(`#objective-task-delete-${this.index}`).on('click', this.onDeleteClick); - $(`#objective-task-add-${this.index}`).on('click', this.onAddClick); + $(`#objective-task-complete-${this.index}`).on('click', () => (this.onCompleteClick())); + $(`#objective-task-description-${this.index}`).on('keyup', () => (this.onDescriptionUpdate())); + $(`#objective-task-delete-${this.index}`).on('click', () => (this.onDeleteClick())); + $(`#objective-task-add-${this.index}`).on('click', () => (this.onAddClick())); } onCompleteClick(){ @@ -237,7 +241,7 @@ class ObjectiveTask { updateUiTaskList(); } - toString() { + toSaveState() { return { "index":this.index, "description":this.description, @@ -256,7 +260,7 @@ class TaskManager { if (this.tasks){} } - deleteTask (index) + deleteTask (index) {} } //###############################// @@ -286,7 +290,7 @@ function saveState() { } // Convert globalTasks for saving - const tasks = globalTasks.map(taskString => {return taskString.toString()}) + const tasks = globalTasks.map(task => {return task.toSaveState()}) chat_metadata['objective'] = { objective: globalObjective, @@ -389,7 +393,7 @@ function loadSettings() { // Update globals globalObjective = chat_metadata['objective'].objective - globalTasks = chat_metadata['objective'].tasks + globalTasks = chat_metadata['objective'].tasks.map((task, index) => {return new ObjectiveTask(index, task.description)}) checkCounter = chat_metadata['objective'].checkFrequency // Update UI elements From 9891d0c936f74b0e9b061579c5c0724c851cfb9a Mon Sep 17 00:00:00 2001 From: ouoertheo Date: Mon, 5 Jun 2023 23:52:45 -0500 Subject: [PATCH 3/3] tasks are now a class. fix various bugs --- public/scripts/extensions/objective/index.js | 171 ++++++++++--------- 1 file changed, 94 insertions(+), 77 deletions(-) diff --git a/public/scripts/extensions/objective/index.js b/public/scripts/extensions/objective/index.js index f172ccdbe..6366c1ee0 100644 --- a/public/scripts/extensions/objective/index.js +++ b/public/scripts/extensions/objective/index.js @@ -61,28 +61,27 @@ async function generateQuietPrompt(quiet_prompt) { function addTask(description, index = null) { index = index != null ? index: index = globalTasks.length globalTasks.splice(index, 0, new ObjectiveTask( - index, - description, + {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 = globalTasks[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() @@ -102,18 +101,18 @@ async function generateTasks() { // 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 (currentTask == null) { + if (jQuery.isEmptyObject(currentTask)) { return } checkCounter = $('#objective-check-frequency').val() @@ -123,7 +122,7 @@ async function checkTaskCompleted() { // Check response if task complete if (taskResponse.includes("true")) { - console.info(`Character determined task '${JSON.stringify(currentTask)} is completed.`) + 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}`) @@ -134,23 +133,22 @@ 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 = {}; - // Set current task to either the next incomplete task, or the index if valid value is specified - 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){ - toastr.error(`Invalide task index ${index} specified. Must be between 0 and ${globalTasks.length}`) - return - } + const { _, index } = getTaskById(taskId) currentTask = globalTasks[index]; } // Get the task description and add to extension prompt - const { description } = currentTask.description; + const description = currentTask.description || null; + + // Now update the extension prompt if (description) { const extensionPromptText = extensionPrompt.replace(/{{task}}/gi, description); @@ -164,9 +162,19 @@ 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 { - // Task State - index + id description completed parent @@ -179,10 +187,18 @@ class ObjectiveTask { deleteTaskButton addTaskButton - constructor (index, description, parent=null) { - this.index = index + 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 + } } @@ -197,72 +213,64 @@ class ObjectiveTask { // Add a single task to the UI and attach event listeners for user edits addUiElement() { const template = ` -
- ${this.index} - - ${this.description} -
-
+
+ + ${this.description} +
+

`; // Add the filled out template $('#objective-tasks').append(template); - - this.completedCheckbox = $(`#objective-task-complete-${this.index}`); - this.descriptionSpan = $(`#objective-task-description-${this.index}`); - this.addButton = $(`#objective-task-add-${this.index}`); - this.deleteButton = $(`#objective-task-delete-${this.index}`); + + this.completedCheckbox = $(`#objective-task-complete-${this.id}`); + this.descriptionSpan = $(`#objective-task-description-${this.id}`); + this.addButton = $(`#objective-task-add-${this.id}`); + this.deleteButton = $(`#objective-task-delete-${this.id}`); // Add event listeners and set properties - $(`#objective-task-complete-${this.index}`).prop('checked', this.completed); - $(`#objective-task-complete-${this.index}`).on('click', () => (this.onCompleteClick())); - $(`#objective-task-description-${this.index}`).on('keyup', () => (this.onDescriptionUpdate())); - $(`#objective-task-delete-${this.index}`).on('click', () => (this.onDeleteClick())); - $(`#objective-task-add-${this.index}`).on('click', () => (this.onAddClick())); + $(`#objective-task-complete-${this.id}`).prop('checked', this.completed); + $(`#objective-task-complete-${this.id}`).on('click', () => (this.onCompleteClick())); + $(`#objective-task-description-${this.id}`).on('keyup', () => (this.onDescriptionUpdate())); + $(`#objective-task-description-${this.id}`).on('focusout', () => (this.onDescriptionFocusout())); + $(`#objective-task-delete-${this.id}`).on('click', () => (this.onDeleteClick())); + $(`#objective-task-add-${this.id}`).on('click', () => (this.onAddClick())); } onCompleteClick(){ - this.completed = this.completedCheckbox.val() + this.completed = this.completedCheckbox.prop('checked') setCurrentTask(); } onDescriptionUpdate(){ - this.description = this.descriptionSpan.val(); + this.description = this.descriptionSpan.text(); + } + onDescriptionFocusout(){ + setCurrentTask(); } onDeleteClick(){ - deleteTask(this.index); + deleteTask(this.id); } onAddClick(){ - addTask("", this.index + 1); + const {_, index} = getTaskById(this.id) + addTask("", index + 1); setCurrentTask(); updateUiTaskList(); } toSaveState() { return { - "index":this.index, + "id":this.id, "description":this.description, "completed":this.completed, + "parent": this.parent, } } } -class TaskManager { - tasks = {} - - constructor (){ - } - - addTask (description, index, parent) { - if (this.tasks){} - } - - deleteTask (index) {} -} - //###############################// //# UI AND Settings #// //###############################// @@ -306,11 +314,11 @@ function saveState() { // Dump core state function debugObjectiveExtension() { console.log(JSON.stringify({ - "currentTask": currentTask, + "currentTask": currentTask.toSaveState(), "currentChatId": currentChatId, "checkCounter": checkCounter, "globalObjective": globalObjective, - "globalTasks": globalTasks, + "globalTasks": globalTasks.map(v => {return v.toSaveState()}), "extension_settings": chat_metadata['objective'], }, null, 2)) } @@ -338,14 +346,6 @@ function updateUiTaskList() { } } -function addManualTaskCheckUi() { - $('#extensionsMenu').prepend(` -
-
- Manual Task Check -
`) - $('#objective-task-manual-check-menu-item').attr('title', 'Trigger AI check of completed tasks').on('click', checkTaskCompleted) -} // Trigger creation of new tasks with given objective. async function onGenerateObjectiveClick() { @@ -393,7 +393,14 @@ function loadSettings() { // Update globals globalObjective = chat_metadata['objective'].objective - globalTasks = chat_metadata['objective'].tasks.map((task, index) => {return new ObjectiveTask(index, task.description)}) + globalTasks = chat_metadata['objective'].tasks.map(task => { + return new ObjectiveTask({ + id: task.id, + description: task.description, + completed: task.completed, + parent: task.parent, + }) + }); checkCounter = chat_metadata['objective'].checkFrequency // Update UI elements @@ -407,6 +414,15 @@ function loadSettings() { setCurrentTask() } +function addManualTaskCheckUi() { + $('#extensionsMenu').prepend(` +
+
+ Manual Task Check +
`) + $('#objective-task-manual-check-menu-item').attr('title', 'Trigger AI check of completed tasks').on('click', checkTaskCompleted) +} + jQuery(() => { const settingsHtml = `
@@ -429,7 +445,8 @@ jQuery(() => {
-
+
+