From 20527d8acf39f727220e5dd66021c1ba804ba056 Mon Sep 17 00:00:00 2001 From: Bertan Ari Date: Tue, 10 Nov 2026 20:47:19 -0800 Subject: [PATCH] feat: complete sessions and resume the deepest active task --- .changeset/session-history-completion.md | 5 + packages/types/src/history.ts | 1 + packages/types/src/vscode-extension-host.ts | 5 + .../removeClineFromStack-delegation.spec.ts | 286 +------------ src/core/task-persistence/TaskHistoryStore.ts | 22 + .../__tests__/TaskHistoryStore.spec.ts | 33 ++ .../__tests__/sessionHistory.spec.ts | 54 +++ src/core/task-persistence/sessionHistory.ts | 51 +++ src/core/webview/ClineProvider.ts | 144 +++++-- .../ClineProvider.session-history.spec.ts | 376 ++++++++++++++++++ .../webview/__tests__/ClineProvider.spec.ts | 2 + .../webviewMessageHandler.checkpoint.spec.ts | 1 + .../webviewMessageHandler.edit.spec.ts | 34 ++ src/core/webview/webviewMessageHandler.ts | 44 +- src/i18n/locales/ca/common.json | 9 + src/i18n/locales/de/common.json | 9 + src/i18n/locales/en/common.json | 9 + src/i18n/locales/es/common.json | 9 + src/i18n/locales/fr/common.json | 9 + src/i18n/locales/hi/common.json | 9 + src/i18n/locales/id/common.json | 9 + src/i18n/locales/it/common.json | 9 + src/i18n/locales/ja/common.json | 9 + src/i18n/locales/ko/common.json | 9 + src/i18n/locales/nl/common.json | 9 + src/i18n/locales/pl/common.json | 9 + src/i18n/locales/pt-BR/common.json | 9 + src/i18n/locales/ru/common.json | 9 + src/i18n/locales/tr/common.json | 9 + src/i18n/locales/vi/common.json | 9 + src/i18n/locales/zh-CN/common.json | 9 + src/i18n/locales/zh-TW/common.json | 9 + webview-ui/src/components/chat/ChatView.tsx | 54 ++- webview-ui/src/components/chat/TaskHeader.tsx | 8 + .../chat/__tests__/ChatView.spec.tsx | 187 +++++++++ .../chat/__tests__/TaskHeader.spec.tsx | 37 +- .../src/components/history/HistoryView.tsx | 11 + .../history/SessionCompletionButton.tsx | 54 +++ .../src/components/history/TaskItem.tsx | 28 +- .../history/__tests__/HistoryView.spec.tsx | 17 + .../history/__tests__/TaskItem.spec.tsx | 43 ++ .../history/__tests__/useTaskSearch.spec.tsx | 36 ++ .../src/components/history/useTaskSearch.ts | 37 +- webview-ui/src/i18n/locales/ca/history.json | 7 + webview-ui/src/i18n/locales/de/history.json | 7 + webview-ui/src/i18n/locales/en/history.json | 7 + webview-ui/src/i18n/locales/es/history.json | 7 + webview-ui/src/i18n/locales/fr/history.json | 7 + webview-ui/src/i18n/locales/hi/history.json | 7 + webview-ui/src/i18n/locales/id/history.json | 7 + webview-ui/src/i18n/locales/it/history.json | 7 + webview-ui/src/i18n/locales/ja/history.json | 7 + webview-ui/src/i18n/locales/ko/history.json | 7 + webview-ui/src/i18n/locales/nl/history.json | 7 + webview-ui/src/i18n/locales/pl/history.json | 7 + .../src/i18n/locales/pt-BR/history.json | 7 + webview-ui/src/i18n/locales/ru/history.json | 7 + webview-ui/src/i18n/locales/tr/history.json | 7 + webview-ui/src/i18n/locales/vi/history.json | 7 + .../src/i18n/locales/zh-CN/history.json | 7 + .../src/i18n/locales/zh-TW/history.json | 7 + 61 files changed, 1520 insertions(+), 338 deletions(-) create mode 100644 .changeset/session-history-completion.md create mode 100644 src/core/task-persistence/__tests__/sessionHistory.spec.ts create mode 100644 src/core/task-persistence/sessionHistory.ts create mode 100644 src/core/webview/__tests__/ClineProvider.session-history.spec.ts create mode 100644 webview-ui/src/components/history/SessionCompletionButton.tsx diff --git a/.changeset/session-history-completion.md b/.changeset/session-history-completion.md new file mode 100644 index 00000000000..662f5d1db55 --- /dev/null +++ b/.changeset/session-history-completion.md @@ -0,0 +1,5 @@ +--- +"roo-cline": minor +--- + +Mark sessions completed from their root task. Completed sessions are kept and can be reopened, but hidden from history unless Show completed is on. Resume continues the deepest unfinished task on the active delegation path instead of the parent, or opens the root with a warning if task relationships are damaged. diff --git a/packages/types/src/history.ts b/packages/types/src/history.ts index a60d1a75b65..4704a2b8d90 100644 --- a/packages/types/src/history.ts +++ b/packages/types/src/history.ts @@ -21,6 +21,7 @@ export const historyItemSchema = z.object({ mode: z.string().optional(), apiConfigName: z.string().optional(), // Provider profile name for sticky profile feature status: z.enum(["active", "completed", "delegated"]).optional(), + sessionCompletedAt: z.number().optional(), delegatedToId: z.string().optional(), // Last child this parent delegated to childIds: z.array(z.string()).optional(), // All children spawned by this task awaitingChildId: z.string().optional(), // Child currently awaited (set when delegated) diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 606cba77c5c..a9347f14e73 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -57,6 +57,7 @@ export interface ExtensionMessage { | "fileSearchResults" | "toggleApiConfigPin" | "acceptInput" + | "resumeSessionInputUsed" | "setHistoryPreviewCollapsed" | "commandExecutionStatus" | "mcpExecutionStatus" @@ -400,6 +401,9 @@ export interface WebviewMessage { | "selectImages" | "exportCurrentTask" | "showTaskWithId" + | "markSessionCompleted" + | "reopenSession" + | "resumeSession" | "deleteTaskWithId" | "exportTaskWithId" | "importSettings" @@ -541,6 +545,7 @@ export interface WebviewMessage { askResponse?: ClineAskResponse apiConfiguration?: ProviderSettings images?: string[] + input?: string bool?: boolean value?: number stepIndex?: number diff --git a/src/__tests__/removeClineFromStack-delegation.spec.ts b/src/__tests__/removeClineFromStack-delegation.spec.ts index a72f580d6fe..8c11ee3c8f2 100644 --- a/src/__tests__/removeClineFromStack-delegation.spec.ts +++ b/src/__tests__/removeClineFromStack-delegation.spec.ts @@ -1,281 +1,33 @@ -// npx vitest run __tests__/removeClineFromStack-delegation.spec.ts - -import { describe, it, expect, vi } from "vitest" import { ClineProvider } from "../core/webview/ClineProvider" -describe("ClineProvider.removeClineFromStack() delegation awareness", () => { - /** - * Helper to build a minimal mock provider with a single task on the stack. - * The task's parentTaskId and taskId are configurable. - */ - function buildMockProvider(opts: { - childTaskId: string - parentTaskId?: string - parentHistoryItem?: Record - getTaskWithIdError?: Error - }) { - const childTask = { - taskId: opts.childTaskId, - instanceId: "inst-1", - parentTaskId: opts.parentTaskId, - emit: vi.fn(), - abortTask: vi.fn().mockResolvedValue(undefined), - } - - const updateTaskHistory = vi.fn().mockResolvedValue([]) - const getTaskWithId = opts.getTaskWithIdError - ? vi.fn().mockRejectedValue(opts.getTaskWithIdError) - : vi.fn().mockImplementation(async (id: string) => { - if (id === opts.parentTaskId && opts.parentHistoryItem) { - return { historyItem: { ...opts.parentHistoryItem } } - } - throw new Error("Task not found") - }) - +describe("ClineProvider.removeClineFromStack", () => { + it.each([undefined, "parent-1"])("SH-07: never repairs metadata (parent %s)", async (parentTaskId) => { + const cleanup = vi.fn() + const task = { taskId: "child", parentTaskId, emit: vi.fn(), abortTask: vi.fn() } const provider = { - clineStack: [childTask] as any[], - taskEventListeners: new Map(), - log: vi.fn(), - getTaskWithId, - updateTaskHistory, - } - - return { provider, childTask, updateTaskHistory, getTaskWithId } - } - - it("repairs parent metadata (delegated → active) when a delegated child is removed", async () => { - const { provider, updateTaskHistory, getTaskWithId } = buildMockProvider({ - childTaskId: "child-1", - parentTaskId: "parent-1", - parentHistoryItem: { - id: "parent-1", - task: "Parent task", - ts: 1000, - number: 1, - tokensIn: 0, - tokensOut: 0, - totalCost: 0, - status: "delegated", - awaitingChildId: "child-1", - delegatedToId: "child-1", - childIds: ["child-1"], - }, - }) - - await (ClineProvider.prototype as any).removeClineFromStack.call(provider) - - // Stack should be empty after pop - expect(provider.clineStack).toHaveLength(0) - - // Parent lookup should have been called - expect(getTaskWithId).toHaveBeenCalledWith("parent-1") - - // Parent metadata should be repaired - expect(updateTaskHistory).toHaveBeenCalledTimes(1) - const updatedParent = updateTaskHistory.mock.calls[0][0] - expect(updatedParent).toEqual( - expect.objectContaining({ - id: "parent-1", - status: "active", - awaitingChildId: undefined, - }), - ) - - // Log the repair - expect(provider.log).toHaveBeenCalledWith(expect.stringContaining("Repaired parent parent-1 metadata")) - }) - - it("does NOT modify parent metadata when the task has no parentTaskId (non-delegated)", async () => { - const { provider, updateTaskHistory, getTaskWithId } = buildMockProvider({ - childTaskId: "standalone-1", - // No parentTaskId — this is a top-level task - }) - - await (ClineProvider.prototype as any).removeClineFromStack.call(provider) - - // Stack should be empty - expect(provider.clineStack).toHaveLength(0) - - // No parent lookup or update should happen - expect(getTaskWithId).not.toHaveBeenCalled() - expect(updateTaskHistory).not.toHaveBeenCalled() - }) - - it("does NOT modify parent metadata when awaitingChildId does not match the popped child", async () => { - const { provider, updateTaskHistory, getTaskWithId } = buildMockProvider({ - childTaskId: "child-1", - parentTaskId: "parent-1", - parentHistoryItem: { - id: "parent-1", - task: "Parent task", - ts: 1000, - number: 1, - tokensIn: 0, - tokensOut: 0, - totalCost: 0, - status: "delegated", - awaitingChildId: "child-OTHER", // different child - delegatedToId: "child-OTHER", - childIds: ["child-OTHER"], - }, - }) - - await (ClineProvider.prototype as any).removeClineFromStack.call(provider) - - // Parent was looked up but should NOT be updated - expect(getTaskWithId).toHaveBeenCalledWith("parent-1") - expect(updateTaskHistory).not.toHaveBeenCalled() - }) - - it("does NOT modify parent metadata when parent status is not 'delegated'", async () => { - const { provider, updateTaskHistory, getTaskWithId } = buildMockProvider({ - childTaskId: "child-1", - parentTaskId: "parent-1", - parentHistoryItem: { - id: "parent-1", - task: "Parent task", - ts: 1000, - number: 1, - tokensIn: 0, - tokensOut: 0, - totalCost: 0, - status: "completed", // already completed - awaitingChildId: "child-1", - childIds: ["child-1"], - }, - }) - - await (ClineProvider.prototype as any).removeClineFromStack.call(provider) - - expect(getTaskWithId).toHaveBeenCalledWith("parent-1") - expect(updateTaskHistory).not.toHaveBeenCalled() - }) - - it("catches and logs errors during parent metadata repair without blocking the pop", async () => { - const { provider, childTask, updateTaskHistory, getTaskWithId } = buildMockProvider({ - childTaskId: "child-1", - parentTaskId: "parent-1", - getTaskWithIdError: new Error("Storage unavailable"), - }) - - // Should NOT throw - await (ClineProvider.prototype as any).removeClineFromStack.call(provider) - - // Stack should still be empty (pop was not blocked) - expect(provider.clineStack).toHaveLength(0) - - // The abort should still have been called - expect(childTask.abortTask).toHaveBeenCalledWith(true) - - // Error should be logged as non-fatal - expect(provider.log).toHaveBeenCalledWith( - expect.stringContaining("Failed to repair parent metadata for parent-1 (non-fatal)"), - ) - - // No update should have been attempted - expect(updateTaskHistory).not.toHaveBeenCalled() - }) - - it("handles empty stack gracefully", async () => { - const provider = { - clineStack: [] as any[], - taskEventListeners: new Map(), - log: vi.fn(), + clineStack: [task], + taskEventListeners: new Map([[task, [cleanup]]]), getTaskWithId: vi.fn(), updateTaskHistory: vi.fn(), + log: vi.fn(), } - - // Should not throw - await (ClineProvider.prototype as any).removeClineFromStack.call(provider) - - expect(provider.clineStack).toHaveLength(0) + await ClineProvider.prototype.removeClineFromStack.call(provider as any) + expect(provider.clineStack).toEqual([]) + expect(task.abortTask).toHaveBeenCalledWith(true) + expect(cleanup).toHaveBeenCalledOnce() expect(provider.getTaskWithId).not.toHaveBeenCalled() expect(provider.updateTaskHistory).not.toHaveBeenCalled() }) - it("skips delegation repair when skipDelegationRepair option is true", async () => { - const { provider, updateTaskHistory, getTaskWithId } = buildMockProvider({ - childTaskId: "child-1", - parentTaskId: "parent-1", - parentHistoryItem: { - id: "parent-1", - task: "Parent task", - ts: 1000, - number: 1, - tokensIn: 0, - tokensOut: 0, - totalCost: 0, - status: "delegated", - awaitingChildId: "child-1", - delegatedToId: "child-1", - childIds: ["child-1"], - }, - }) - - // Call with skipDelegationRepair: true (as delegateParentAndOpenChild would) - await (ClineProvider.prototype as any).removeClineFromStack.call(provider, { skipDelegationRepair: true }) - - // Stack should be empty after pop - expect(provider.clineStack).toHaveLength(0) - - // Parent lookup should NOT have been called — repair was skipped entirely - expect(getTaskWithId).not.toHaveBeenCalled() - expect(updateTaskHistory).not.toHaveBeenCalled() + it("still cleans up when abort fails", async () => { + const task = { taskId: "child", emit: vi.fn(), abortTask: vi.fn().mockRejectedValue(new Error("abort")) } + const provider = { clineStack: [task], taskEventListeners: new Map(), log: vi.fn() } + await ClineProvider.prototype.removeClineFromStack.call(provider as any) + expect(provider.clineStack).toEqual([]) + expect(provider.log).toHaveBeenCalledOnce() }) - it("does NOT reset grandparent during A→B→C nested delegation transition", async () => { - // Scenario: A delegated to B, B is now delegating to C. - // delegateParentAndOpenChild() pops B via removeClineFromStack({ skipDelegationRepair: true }). - // Grandparent A should remain "delegated" — its metadata must not be repaired. - const grandparentHistory = { - id: "task-A", - task: "Grandparent task", - ts: 1000, - number: 1, - tokensIn: 0, - tokensOut: 0, - totalCost: 0, - status: "delegated", - awaitingChildId: "task-B", - delegatedToId: "task-B", - childIds: ["task-B"], - } - - const taskB = { - taskId: "task-B", - instanceId: "inst-B", - parentTaskId: "task-A", - emit: vi.fn(), - abortTask: vi.fn().mockResolvedValue(undefined), - } - - const getTaskWithId = vi.fn().mockImplementation(async (id: string) => { - if (id === "task-A") { - return { historyItem: { ...grandparentHistory } } - } - throw new Error("Task not found") - }) - const updateTaskHistory = vi.fn().mockResolvedValue([]) - - const provider = { - clineStack: [taskB] as any[], - taskEventListeners: new Map(), - log: vi.fn(), - getTaskWithId, - updateTaskHistory, - } - - // Simulate what delegateParentAndOpenChild does: pop B with skipDelegationRepair - await (ClineProvider.prototype as any).removeClineFromStack.call(provider, { skipDelegationRepair: true }) - - // B was popped - expect(provider.clineStack).toHaveLength(0) - - // Grandparent A should NOT have been looked up or modified - expect(getTaskWithId).not.toHaveBeenCalled() - expect(updateTaskHistory).not.toHaveBeenCalled() - - // Grandparent A's metadata remains intact (delegated, awaitingChildId: task-B) - // The caller (delegateParentAndOpenChild) will update A to point to C separately. + it("handles an empty stack", async () => { + await ClineProvider.prototype.removeClineFromStack.call({ clineStack: [] } as any) }) }) diff --git a/src/core/task-persistence/TaskHistoryStore.ts b/src/core/task-persistence/TaskHistoryStore.ts index 4157d8b9fbb..734824c4764 100644 --- a/src/core/task-persistence/TaskHistoryStore.ts +++ b/src/core/task-persistence/TaskHistoryStore.ts @@ -184,6 +184,28 @@ export class TaskHistoryStore { }) } + async updateIfPresent( + taskId: string, + update: (item: HistoryItem) => Partial> | undefined, + ): Promise { + return this.withLock(async () => { + const existing = this.cache.get(taskId) + if (!existing) { + return undefined + } + const changes = update(existing) + if (!changes) { + return undefined + } + const merged = { ...existing, ...changes, id: taskId } + await this.writeTaskFile(merged) + this.cache.set(taskId, merged) + this.scheduleIndexWrite() + await this.onWrite?.(this.getAll()) + return merged + }) + } + /** * Delete a single task's history item. */ diff --git a/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts b/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts index 8adc486160a..0444d29183e 100644 --- a/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts +++ b/src/core/task-persistence/__tests__/TaskHistoryStore.spec.ts @@ -49,6 +49,39 @@ describe("TaskHistoryStore", () => { await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {}) }) + describe("updateIfPresent()", () => { + it("SH-11: checks existence inside the lock after a queued deletion", async () => { + await store.upsert(makeHistoryItem({ id: "parent", status: "delegated", awaitingChildId: "child" })) + let releaseWrite!: () => void + const blockedWrite = new Promise((resolve) => { + releaseWrite = resolve + }) + const { safeWriteJson } = await import("../../../utils/safeWriteJson") + vi.mocked(safeWriteJson).mockImplementationOnce(async () => blockedWrite) + const blocker = store.upsert(makeHistoryItem({ id: "blocker" })) + const deletion = store.delete("parent") + const update = vi.fn(() => ({ status: "active" as const, awaitingChildId: undefined })) + const repair = store.updateIfPresent("parent", update) + releaseWrite() + await Promise.all([blocker, deletion, repair]) + expect(await repair).toBeUndefined() + expect(update).not.toHaveBeenCalled() + expect(store.get("parent")).toBeUndefined() + await expect(fs.access(path.join(tmpDir, "tasks", "parent", GlobalFileNames.historyItem))).rejects.toThrow() + }) + + it("rechecks relationships under lock and preserves unrelated fields", async () => { + await store.upsert(makeHistoryItem({ id: "parent", sessionCompletedAt: 123, status: "delegated" })) + await store.updateIfPresent("parent", () => ({ status: "active", awaitingChildId: undefined })) + expect(store.get("parent")).toMatchObject({ status: "active", sessionCompletedAt: 123 }) + const update = await store.updateIfPresent("parent", (entry) => + entry.status === "delegated" ? { status: "completed" } : undefined, + ) + expect(update).toBeUndefined() + expect(store.get("parent")!.status).toBe("active") + }) + }) + describe("initialize()", () => { it("initializes from empty state (no index, no task dirs)", async () => { await store.initialize() diff --git a/src/core/task-persistence/__tests__/sessionHistory.spec.ts b/src/core/task-persistence/__tests__/sessionHistory.spec.ts new file mode 100644 index 00000000000..9924e0441a4 --- /dev/null +++ b/src/core/task-persistence/__tests__/sessionHistory.spec.ts @@ -0,0 +1,54 @@ +import type { HistoryItem } from "@roo-code/types" +import { historyItemSchema } from "@roo-code/types" +import { resolveResumeTarget, resolveSessionRoot } from "../sessionHistory" + +function item(id: string, changes: Partial = {}): HistoryItem { + return { id, number: 1, ts: 1, task: id, tokensIn: 0, tokensOut: 0, totalCost: 0, ...changes } +} + +const chain = [ + item("A", { status: "delegated", awaitingChildId: "B" }), + item("B", { parentTaskId: "A", status: "delegated", awaitingChildId: "C" }), + item("C", { parentTaskId: "B", status: "active", mode: "architect" }), + item("old", { parentTaskId: "C", status: "completed", ts: 9999 }), +] +const history = (items: HistoryItem[]) => new Map(items.map((entry) => [entry.id, entry])) + +describe("session history resolution", () => { + it("accepts old records and completion timestamps", () => { + expect(historyItemSchema.parse(item("A")).sessionCompletedAt).toBeUndefined() + expect(historyItemSchema.parse(item("A", { sessionCompletedAt: 123 })).sessionCompletedAt).toBe(123) + }) + + it.each(["A", "B", "C", "old"])("SH-03: resolves %s to the active leaf", (startId) => { + expect(resolveResumeTarget(startId, history(chain))).toEqual({ taskId: "C" }) + }) + + it("returns the parent after its child returned, ignoring historical children", () => { + const returned = chain.map((entry) => + entry.id === "B" ? { ...entry, status: "active" as const, awaitingChildId: undefined } : entry, + ) + expect(resolveResumeTarget("old", history(returned))).toEqual({ taskId: "B" }) + }) + + it.each([ + ["missingAwaitingChild", [item("A", { status: "delegated" })]], + ["missingChild", [item("A", { status: "delegated", awaitingChildId: "lost" })]], + ["inconsistentChild", [chain[0], item("B", { parentTaskId: "other" })]], + ["inconsistentChild", [chain[0], item("B", { parentTaskId: "A", status: "completed" })]], + ["cycle", [chain[0], item("B", { parentTaskId: "A", status: "delegated", awaitingChildId: "A" })]], + ["cycle", [item("A", { parentTaskId: "B" }), item("B", { parentTaskId: "A" })]], + ] as const)("SH-04: falls back for %s", (fallbackReason, entries) => { + expect(resolveResumeTarget("A", history([...entries]))).toEqual({ taskId: "A", fallbackReason }) + }) + + it("promotes a task with a missing parent and handles standalone sessions", () => { + const entries = history([item("A", { parentTaskId: "missing" })]) + expect(resolveSessionRoot("A", entries)).toEqual({ taskId: "A" }) + expect(resolveResumeTarget("A", entries)).toEqual({ taskId: "A" }) + }) + + it("rejects a missing start without inventing a root", () => { + expect(() => resolveResumeTarget("missing", history(chain))).toThrow("Task not found") + }) +}) diff --git a/src/core/task-persistence/sessionHistory.ts b/src/core/task-persistence/sessionHistory.ts new file mode 100644 index 00000000000..cbd2c0e3481 --- /dev/null +++ b/src/core/task-persistence/sessionHistory.ts @@ -0,0 +1,51 @@ +import type { HistoryItem } from "@roo-code/types" + +export type SessionFallbackReason = "cycle" | "missingChild" | "missingAwaitingChild" | "inconsistentChild" +export type SessionResolution = { taskId: string; fallbackReason?: SessionFallbackReason } + +export function resolveSessionRoot(startId: string, historyById: ReadonlyMap): SessionResolution { + let current = historyById.get(startId) + if (!current) { + throw new Error("Task not found") + } + const visited = new Set() + while (current.parentTaskId) { + visited.add(current.id) + if (visited.has(current.parentTaskId)) { + return { taskId: startId, fallbackReason: "cycle" } + } + const parent = historyById.get(current.parentTaskId) + if (!parent) { + break + } + current = parent + } + return { taskId: current.id } +} + +export function resolveResumeTarget(startId: string, historyById: ReadonlyMap): SessionResolution { + const root = resolveSessionRoot(startId, historyById) + if (root.fallbackReason) { + return root + } + let current = historyById.get(root.taskId)! + const visited = new Set() + while (current.status === "delegated") { + visited.add(current.id) + if (!current.awaitingChildId) { + return { ...root, fallbackReason: "missingAwaitingChild" } + } + if (visited.has(current.awaitingChildId)) { + return { ...root, fallbackReason: "cycle" } + } + const child = historyById.get(current.awaitingChildId) + if (!child) { + return { ...root, fallbackReason: "missingChild" } + } + if (child.parentTaskId !== current.id || child.status === "completed") { + return { ...root, fallbackReason: "inconsistentChild" } + } + current = child + } + return { taskId: current.id } +} diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 38a09baa018..83689fbec36 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -88,6 +88,7 @@ import { webviewMessageHandler } from "./webviewMessageHandler" import type { ClineMessage, TodoItem } from "@roo-code/types" import { readApiMessages, saveApiMessages, saveTaskMessages, TaskHistoryStore } from "../task-persistence" import { readTaskMessages } from "../task-persistence/taskMessages" +import { resolveSessionRoot, resolveResumeTarget } from "../task-persistence/sessionHistory" import { getNonce } from "./getNonce" import { getUri } from "./getUri" import { REQUESTY_BASE_URL } from "../../shared/utils/requesty" @@ -372,9 +373,7 @@ export class ClineProvider } } - // Removes and destroys the top Cline instance (the current finished task), - // activating the previous one (resuming the parent task). - async removeClineFromStack(options?: { skipDelegationRepair?: boolean }) { + async removeClineFromStack() { if (this.clineStack.length === 0) { return } @@ -383,11 +382,6 @@ export class ClineProvider let task = this.clineStack.pop() if (task) { - // Capture delegation metadata before abort/dispose, since abortTask(true) - // is async and the task reference is cleared afterwards. - const childTaskId = task.taskId - const parentTaskId = task.parentTaskId - task.emit(RooCodeEventName.TaskUnfocused) try { @@ -411,37 +405,6 @@ export class ClineProvider // Make sure no reference kept, once promises end it will be // garbage collected. task = undefined - - // Delegation-aware parent metadata repair: - // If the popped task was a delegated child, repair the parent's metadata - // so it transitions from "delegated" back to "active" and becomes resumable - // from the task history list. - // Skip when called from delegateParentAndOpenChild() during nested delegation - // transitions (A→B→C), where the caller intentionally replaces the active - // child and will update the parent to point at the new child. - if (parentTaskId && childTaskId && !options?.skipDelegationRepair) { - try { - const { historyItem: parentHistory } = await this.getTaskWithId(parentTaskId) - - if (parentHistory.status === "delegated" && parentHistory.awaitingChildId === childTaskId) { - await this.updateTaskHistory({ - ...parentHistory, - status: "active", - awaitingChildId: undefined, - }) - this.log( - `[ClineProvider#removeClineFromStack] Repaired parent ${parentTaskId} metadata: delegated → active (child ${childTaskId} removed)`, - ) - } - } catch (err) { - // Non-fatal: log but do not block the pop operation. - this.log( - `[ClineProvider#removeClineFromStack] Failed to repair parent metadata for ${parentTaskId} (non-fatal): ${ - err instanceof Error ? err.message : String(err) - }`, - ) - } - } } } @@ -1824,6 +1787,75 @@ export class ClineProvider return { historyItem, aggregatedCosts } } + private async getSessionHistory(id: string) { + await this.taskHistoryStore.initialized + const historyById = new Map(this.taskHistoryStore.getAll().map((item) => [item.id, item])) + const root = resolveSessionRoot(id, historyById) + return { historyById, root: historyById.get(root.taskId)! } + } + + async guardSessionEdit(id: string): Promise { + const { root, historyById } = await this.getSessionHistory(id) + if (root.sessionCompletedAt !== undefined) { + vscode.window.showInformationMessage(t("common:session_history.reopen_first")) + } else if (historyById.get(id)?.status === "delegated") { + await this.resumeSession(id) + } else { + return true + } + vscode.window.showInformationMessage(t("common:session_history.edit_not_sent")) + return false + } + + async markSessionCompleted(id: string) { + const { root } = await this.getSessionHistory(id) + await this.taskHistoryStore.updateIfPresent(root.id, () => ({ sessionCompletedAt: Date.now() })) + this.recentTasksCache = undefined + await this.postStateToWebview() + } + + async reopenSession(id: string) { + const { root } = await this.getSessionHistory(id) + await this.taskHistoryStore.updateIfPresent(root.id, () => ({ sessionCompletedAt: undefined })) + this.recentTasksCache = undefined + await this.postStateToWebview() + } + + async resumeSession(id: string, input?: string, images?: string[]) { + const { root, historyById } = await this.getSessionHistory(id) + if (root.sessionCompletedAt !== undefined) { + vscode.window.showInformationMessage(t("common:session_history.reopen_first")) + return + } + const target = resolveResumeTarget(id, historyById) + if (target.fallbackReason) { + // Closing saves the instance's old status, so repair only after it has closed. + if (this.getCurrentTask()?.taskId === root.id) { + await this.removeClineFromStack() + } + await this.taskHistoryStore.updateIfPresent(root.id, () => ({ + status: "active", + awaitingChildId: undefined, + })) + this.recentTasksCache = undefined + await this.showTaskWithId(root.id) + vscode.window.showWarningMessage( + t("common:session_history.resume_fallback", { + reason: t(`common:session_history.${target.fallbackReason}`), + }), + ) + return + } + const current = this.getCurrentTask() + if (current?.taskId === target.taskId && current.taskAsk?.ask === "resume_task") { + const hasInput = Boolean(input || images?.length) + await current.handleWebviewAskResponse(hasInput ? "messageResponse" : "yesButtonClicked", input, images) + await this.postMessageToWebview({ type: "resumeSessionInputUsed", text: target.taskId }) + return + } + await this.showTaskWithId(target.taskId) + } + async showTaskWithId(id: string) { if (id !== this.getCurrentTask()?.taskId) { // Non-current task. @@ -1884,6 +1916,7 @@ export class ClineProvider // Collect all task IDs to delete (parent + all subtasks) const allIdsToDelete: string[] = [id] + const deletedIds = new Set(allIdsToDelete) if (cascadeSubtasks) { // Recursively collect all child IDs @@ -1892,8 +1925,11 @@ export class ClineProvider const { historyItem: item } = await this.getTaskWithId(taskId) if (item.childIds && item.childIds.length > 0) { for (const childId of item.childIds) { - allIdsToDelete.push(childId) - await collectChildIds(childId) + if (!deletedIds.has(childId)) { + deletedIds.add(childId) + allIdsToDelete.push(childId) + await collectChildIds(childId) + } } } } catch (error) { @@ -1914,6 +1950,30 @@ export class ClineProvider } } + for (const deletedId of deletedIds) { + const deletedItem = this.taskHistoryStore.get(deletedId) + const parentId = deletedItem?.parentTaskId + if (!parentId || deletedIds.has(parentId)) { + continue + } + try { + const parent = this.taskHistoryStore.get(parentId) + if (parent?.status !== "delegated" || parent.awaitingChildId !== deletedId) { + continue + } + if (this.getCurrentTask()?.taskId === parentId) { + await this.removeClineFromStack() + } + await this.taskHistoryStore.updateIfPresent(parentId, (storedParent) => + storedParent.status === "delegated" && storedParent.awaitingChildId === deletedId + ? { status: "active", awaitingChildId: undefined } + : undefined, + ) + } catch (error) { + this.log(`[deleteTaskWithId] Failed to repair parent ${parentId}: ${String(error)}`) + } + } + // Delete all tasks from state in one batch await this.taskHistoryStore.deleteMany(allIdsToDelete) this.recentTasksCache = undefined @@ -3001,7 +3061,7 @@ export class ClineProvider // This ensures we never have >1 tasks open at any time during delegation. // Await abort completion to ensure clean disposal and prevent unhandled rejections. try { - await this.removeClineFromStack({ skipDelegationRepair: true }) + await this.removeClineFromStack() } catch (error) { this.log( `[delegateParentAndOpenChild] Error during parent disposal (non-fatal): ${ diff --git a/src/core/webview/__tests__/ClineProvider.session-history.spec.ts b/src/core/webview/__tests__/ClineProvider.session-history.spec.ts new file mode 100644 index 00000000000..02679814cfc --- /dev/null +++ b/src/core/webview/__tests__/ClineProvider.session-history.spec.ts @@ -0,0 +1,376 @@ +import * as fs from "fs/promises" +import * as os from "os" +import * as path from "path" +import * as vscode from "vscode" +import type { HistoryItem } from "@roo-code/types" +import { ClineProvider } from "../ClineProvider" +import { Task } from "../../task/Task" +import * as TaskModule from "../../task/Task" +import { TaskHistoryStore } from "../../task-persistence/TaskHistoryStore" +import { readTaskMessages } from "../../task-persistence/taskMessages" +import { resolveResumeTarget } from "../../task-persistence/sessionHistory" +import { ShadowCheckpointService } from "../../../services/checkpoints/ShadowCheckpointService" +import { webviewMessageHandler } from "../webviewMessageHandler" + +vi.mock("../../../i18n", () => ({ t: (key: string) => key })) +vi.mock("vscode", async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + window: { + ...actual.window, + showInformationMessage: vi.fn(), + showWarningMessage: vi.fn(), + showErrorMessage: vi.fn(), + }, + } +}) + +function item(id: string, changes: Partial = {}): HistoryItem { + return { id, number: 1, ts: 1, task: id, tokensIn: 0, tokensOut: 0, totalCost: 0, ...changes } +} + +const chain = [ + item("A", { status: "delegated", awaitingChildId: "B", childIds: ["B"] }), + item("B", { parentTaskId: "A", status: "delegated", awaitingChildId: "C", childIds: ["C"] }), + item("C", { parentTaskId: "B", status: "active", mode: "architect" }), +] + +describe("session history backend", () => { + let storagePath: string + let store: TaskHistoryStore + let provider: ClineProvider + let opened: HistoryItem[] + + function makeTask(historyItem: HistoryItem): Task { + const task = Object.assign(Object.create(Task.prototype), { + taskId: historyItem.id, + instanceId: `instance-${historyItem.id}`, + parentTaskId: historyItem.parentTaskId, + rootTaskId: historyItem.rootTaskId, + taskNumber: historyItem.number, + globalStoragePath: storagePath, + workspacePath: storagePath, + _taskApiConfigName: "saved-profile", + _taskMode: historyItem.mode || "code", + initialStatus: historyItem.status, + providerRef: new WeakRef(provider), + toolUsage: {}, + clineMessages: [{ ts: 1, type: "say", say: "text", text: historyItem.task }], + emit: vi.fn(), + debouncedEmitTokenUsage: vi.fn(), + handleWebviewAskResponse: vi.fn(), + }) as Task + task.abortTask = vi.fn(async () => { + expect(await (task as any).saveClineMessages()).toBe(true) + }) + return task + } + + function setCurrent(id?: string) { + ;(provider as any).clineStack = id ? [makeTask(store.get(id)!)] : [] + return provider.getCurrentTask() + } + + beforeEach(async () => { + vi.clearAllMocks() + vi.spyOn(ShadowCheckpointService, "deleteTask").mockResolvedValue(undefined) + storagePath = await fs.mkdtemp(path.join(os.tmpdir(), "roo-session-history-")) + store = new TaskHistoryStore(storagePath) + // No watchers are needed; retain the real store lock and disk writes. + ;(store as any).resolveInitialized() + provider = Object.assign(Object.create(ClineProvider.prototype), { + taskHistoryStore: store, + taskHistoryStoreInitialized: true, + clineStack: [], + taskEventListeners: new Map(), + contextProxy: { globalStorageUri: { fsPath: storagePath } }, + log: vi.fn(), + postStateToWebview: vi.fn(), + postMessageToWebview: vi.fn(), + getState: vi.fn().mockResolvedValue({ maxImageFileSize: 5, maxTotalImageSize: 20 }), + }) + opened = [] + provider.createTaskWithHistoryItem = vi.fn(async (historyItem) => { + await provider.removeClineFromStack() + opened.push(historyItem) + const task = makeTask(historyItem) + ;(provider as any).clineStack.push(task) + return task + }) + for (const entry of chain) { + await store.upsert(entry) + } + }) + + afterEach(async () => { + await store.flushIndex() + store.dispose() + await store.flushIndex() + await fs.rm(storagePath, { recursive: true, force: true }) + vi.restoreAllMocks() + }) + + it("SH-01/02: mark/reopen changes only the root completion field and survives real task saves", async () => { + const task = setCurrent("A")! + const original = structuredClone(store.getAll()) + await provider.markSessionCompleted("C") + expect(store.get("A")).toEqual({ + ...original.find((entry) => entry.id === "A"), + sessionCompletedAt: expect.any(Number), + }) + expect(store.get("B")).toEqual(original.find((entry) => entry.id === "B")) + expect(task.abortTask).not.toHaveBeenCalled() + const timestamp = store.get("A")!.sessionCompletedAt + const persisted = new TaskHistoryStore(storagePath) + await persisted.invalidate("A") + expect(persisted.get("A")!.sessionCompletedAt).toBe(timestamp) + persisted.dispose() + await persisted.flushIndex() + expect(await (task as any).saveClineMessages()).toBe(true) + expect(store.get("A")!.sessionCompletedAt).toBe(timestamp) + await provider.reopenSession("B") + expect(store.get("A")!.sessionCompletedAt).toBeUndefined() + expect(store.get("A")!.awaitingChildId).toBe("B") + expect(task.abortTask).not.toHaveBeenCalled() + expect(opened).toEqual([]) + const reloaded = new TaskHistoryStore(storagePath) + await reloaded.invalidate("A") + expect(reloaded.get("A")!.sessionCompletedAt).toBeUndefined() + reloaded.dispose() + await reloaded.flushIndex() + }) + + it("SH-05: inspecting A preserves the continuation and restores C's saved mode and relationships", async () => { + setCurrent("C") + await provider.showTaskWithId("A") + expect(store.get("B")!.awaitingChildId).toBe("C") + await provider.resumeSession("A", "unsent") + expect(opened.map((entry) => entry.id)).toEqual(["A", "C"]) + expect(opened[1]).toMatchObject({ mode: "architect", parentTaskId: "B" }) + expect(provider.postMessageToWebview).not.toHaveBeenCalledWith( + expect.objectContaining({ type: "resumeSessionInputUsed" }), + ) + }) + + it("SH-06: creating a new top-level task preserves the saved nested continuation", async () => { + const previous = setCurrent("C")! + const created = makeTask(item("new-task", { status: "active" })) + created.start = vi.fn() + const constructor = vi.spyOn(TaskModule, "Task").mockImplementation(function () { + return created + }) + provider.setValues = vi.fn() + provider.getState = vi + .fn() + .mockResolvedValue({ apiConfiguration: {}, organizationAllowList: { allowAll: true } }) + provider.addClineToStack = vi.fn(async (task) => { + ;(provider as any).clineStack.push(task) + }) + expect(await provider.createTask("new work")).toBe(created) + expect(constructor).toHaveBeenCalledWith(expect.objectContaining({ task: "new work", parentTask: undefined })) + expect(previous.abortTask).toHaveBeenCalledOnce() + expect(created.start).toHaveBeenCalledOnce() + expect(provider.getCurrentTask()).toBe(created) + expect(store.get("A")).toMatchObject({ status: "delegated", awaitingChildId: "B" }) + expect(store.get("B")).toMatchObject({ status: "delegated", awaitingChildId: "C" }) + constructor.mockRestore() + await provider.resumeSession("A") + expect(opened.at(-1)?.id).toBe("C") + }) + + it.each(["leave", "clear", "reload", "dispose"])("SH-06: %s preserves nested continuation", async (operation) => { + setCurrent("C") + if (operation === "clear") { + await provider.clearTask() + } else if (operation === "dispose") { + Object.assign(provider, { + pendingOperations: new Map(), + webviewDisposables: [], + disposables: [], + removeAllListeners: vi.fn(), + }) + await provider.dispose() + } else { + await provider.removeClineFromStack() + } + if (operation === "reload") { + await store.flushIndex() + const reloaded = new TaskHistoryStore(storagePath) + for (const entry of chain) { + await reloaded.invalidate(entry.id) + } + expect(resolveResumeTarget("A", new Map(reloaded.getAll().map((entry) => [entry.id, entry])))).toEqual({ + taskId: "C", + }) + reloaded.dispose() + await reloaded.flushIndex() + } + await provider.resumeSession("A") + expect(opened.at(-1)?.id).toBe("C") + }) + + it.each(["C", "B", undefined])( + "SH-08/10: deletion repairs B when current is %s without reopening it", + async (currentId) => { + const task = setCurrent(currentId) + await provider.deleteTaskWithId("C") + expect(store.get("B")).toMatchObject({ status: "active", awaitingChildId: undefined }) + expect(store.get("C")).toBeUndefined() + expect(opened).toEqual([]) + if (currentId === "B") { + expect(task!.abortTask).toHaveBeenCalledOnce() + expect(provider.getCurrentTask()).toBeUndefined() + const saved = await readTaskMessages({ taskId: "B", globalStoragePath: storagePath }) + expect(saved).toEqual(task!.clineMessages) + await provider.showTaskWithId("B") + expect(await (provider.getCurrentTask() as any).saveClineMessages()).toBe(true) + expect(store.get("B")!.status).toBe("active") + } + }, + ) + + it("SH-09: cascade-deleting B with C current repairs A", async () => { + setCurrent("C") + await provider.deleteTaskWithId("B") + expect(store.get("A")).toMatchObject({ status: "active", awaitingChildId: undefined }) + expect(store.get("B")).toBeUndefined() + expect(store.get("C")).toBeUndefined() + }) + + it("SH-11: parallel deletion cannot resurrect a deleted parent", async () => { + await Promise.all([provider.deleteTaskWithId("B"), provider.deleteTaskWithId("C")]) + expect(store.get("B")).toBeUndefined() + expect(store.get("C")).toBeUndefined() + }) + + it.each([ + { status: "active" as const, awaitingChildId: "C" }, + { status: "delegated" as const, awaitingChildId: "other" }, + ])("SH-12: deletion leaves unrelated parent metadata alone (%s)", async (changes) => { + await store.upsert({ ...store.get("B")!, ...changes }) + const original = store.get("B") + await provider.deleteTaskWithId("C") + expect(store.get("B")).toEqual(original) + }) + + it("SH-12: repair errors are logged without preventing deletion", async () => { + vi.spyOn(store, "updateIfPresent").mockRejectedValueOnce(new Error("storage unavailable")) + await provider.deleteTaskWithId("C") + expect(provider.log).toHaveBeenCalledWith(expect.stringContaining("Failed to repair parent B")) + expect(store.get("C")).toBeUndefined() + }) + + it.each([ + ["typed", "continue here", undefined, "messageResponse"], + ["images only", undefined, ["image"], "messageResponse"], + ["button", undefined, undefined, "yesButtonClicked"], + ] as const)( + "SH-15: %s answers only the current target resume ask then confirms", + async (_name, input, images, response) => { + const task = setCurrent("C")! + task.resumableAsk = { ts: 2, type: "ask", ask: "resume_task" } + await provider.resumeSession("A", input, images ? [...images] : undefined) + expect(task.handleWebviewAskResponse).toHaveBeenCalledWith(response, input, images) + expect(provider.postMessageToWebview).toHaveBeenCalledWith({ type: "resumeSessionInputUsed", text: "C" }) + expect(vi.mocked(task.handleWebviewAskResponse).mock.invocationCallOrder[0]).toBeLessThan( + vi.mocked(provider.postMessageToWebview).mock.invocationCallOrder[0], + ) + }, + ) + + it.each(["A", "C"])("SH-16: fallback with %s open survives real close and subsequent saves", async (currentId) => { + await store.delete("B") + const old = setCurrent(currentId)! + await provider.resumeSession("A", "not used") + expect(old.abortTask).toHaveBeenCalledOnce() + expect(store.get("A")).toMatchObject({ status: "active", awaitingChildId: undefined }) + expect(await (provider.getCurrentTask() as any).saveClineMessages()).toBe(true) + expect(store.get("A")!.status).toBe("active") + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith("common:session_history.resume_fallback") + expect(provider.postMessageToWebview).not.toHaveBeenCalledWith( + expect.objectContaining({ type: "resumeSessionInputUsed" }), + ) + vi.mocked(vscode.window.showWarningMessage).mockClear() + await provider.resumeSession("A") + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled() + }) + + it.each(["tool", undefined, "resume_completed_task"] as const)( + "SH-17: does not answer a current %s ask", + async (ask) => { + const task = setCurrent("C")! + task.interactiveAsk = ask ? { ts: 2, type: "ask", ask } : undefined + await provider.resumeSession("A", "not used") + expect(task.handleWebviewAskResponse).not.toHaveBeenCalled() + expect(provider.postMessageToWebview).not.toHaveBeenCalledWith( + expect.objectContaining({ type: "resumeSessionInputUsed" }), + ) + }, + ) + + it("completed session declines Resume and editing without changing state", async () => { + await provider.markSessionCompleted("A") + const task = setCurrent("C")! + task.resumableAsk = { ts: 2, type: "ask", ask: "resume_task" } + const original = structuredClone(store.getAll()) + await provider.resumeSession("C", "not used") + expect(await provider.guardSessionEdit("C")).toBe(false) + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith("common:session_history.reopen_first") + expect(store.getAll()).toEqual(original) + expect(task.handleWebviewAskResponse).not.toHaveBeenCalled() + expect(task.abortTask).not.toHaveBeenCalled() + expect(opened).toEqual([]) + }) + + it("SH-18/19: delegated edit opens C with a notice, but finished child editing is allowed", async () => { + setCurrent("B") + expect(await provider.guardSessionEdit("B")).toBe(false) + expect(opened.at(-1)?.id).toBe("C") + expect(vscode.window.showInformationMessage).toHaveBeenCalledWith("common:session_history.edit_not_sent") + await store.upsert({ ...store.get("C")!, status: "completed" }) + expect(await provider.guardSessionEdit("C")).toBe(true) + }) + + it("routes session actions and keeps the task id separate from input", async () => { + const resume = vi.spyOn(provider, "resumeSession").mockResolvedValue(undefined) + await webviewMessageHandler(provider, { type: "markSessionCompleted", text: "B" }) + expect(store.get("A")!.sessionCompletedAt).toEqual(expect.any(Number)) + await webviewMessageHandler(provider, { type: "reopenSession", text: "C" }) + expect(store.get("A")!.sessionCompletedAt).toBeUndefined() + await webviewMessageHandler(provider, { type: "resumeSession", text: "A", input: "actual input" }) + expect(resume).toHaveBeenCalledWith("A", "actual input", expect.any(Array)) + }) + + it.each(["markSessionCompleted", "reopenSession", "resumeSession"] as const)( + "F1: %s on a just-deleted task does not reject from the message handler", + async (type) => { + await expect(webviewMessageHandler(provider, { type, text: "deleted-task" })).resolves.toBeUndefined() + expect(vscode.window.showErrorMessage).toHaveBeenCalledWith("common:errors.share_task_not_found") + expect(provider.log).toHaveBeenCalledWith(expect.stringContaining(`Failed to handle ${type}`)) + }, + ) + + it("F2/R15: fallback whose root repair finds nothing still opens the root with a message", async () => { + await store.delete("B") + vi.spyOn(store, "updateIfPresent").mockResolvedValueOnce(undefined) + await provider.resumeSession("A") + expect(opened.map((entry) => entry.id)).toEqual(["A"]) + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith("common:session_history.resume_fallback") + }) + + it("N1: edit confirm on a current task without a history record does not reject", async () => { + ;(provider as any).clineStack = [makeTask(item("unsaved-task"))] + await expect( + webviewMessageHandler(provider, { type: "editMessageConfirm", messageTs: 1, text: "edited" }), + ).resolves.toBeUndefined() + }) + + it("getTaskWithId rejects absent metadata but tolerates missing conversation files", async () => { + await expect(provider.getTaskWithId("missing")).rejects.toThrow("Task not found") + await expect(provider.getTaskWithId("C")).resolves.toMatchObject({ + historyItem: store.get("C"), + apiConversationHistory: [], + }) + }) +}) diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index a08e60136b6..2ee4922e9aa 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -1306,6 +1306,7 @@ describe("ClineProvider", () => { describe("editMessage", () => { beforeEach(async () => { + provider.guardSessionEdit = vi.fn().mockResolvedValue(true) await provider.resolveWebviewView(mockWebviewView) }) @@ -2642,6 +2643,7 @@ describe("ClineProvider - Comprehensive Edit/Delete Edge Cases", () => { vi.mocked(filesystem.readFile).mockResolvedValue("[]") provider = new ClineProvider(mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext)) + provider.guardSessionEdit = vi.fn().mockResolvedValue(true) defaultTaskOptions = { provider, diff --git a/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts index b2d3b92b140..8ecda9cf7b3 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.checkpoint.spec.ts @@ -54,6 +54,7 @@ function createFixture() { Object.defineProperty(task, "messageManager", { value: new MessageManager(task) }) const providerDouble = { getCurrentTask: vi.fn(() => task as Task | undefined), + guardSessionEdit: vi.fn(async () => true), cancelTask: vi.fn(async (_options: unknown) => { taskDouble.abort = true taskDouble.abandoned = true diff --git a/src/core/webview/__tests__/webviewMessageHandler.edit.spec.ts b/src/core/webview/__tests__/webviewMessageHandler.edit.spec.ts index 2f11281d2be..9ff303478b5 100644 --- a/src/core/webview/__tests__/webviewMessageHandler.edit.spec.ts +++ b/src/core/webview/__tests__/webviewMessageHandler.edit.spec.ts @@ -58,13 +58,16 @@ describe("webviewMessageHandler - Edit Message with Timestamp Fallback", () => { overwriteClineMessages: vi.fn(), overwriteApiConversationHistory: vi.fn(), handleWebviewAskResponse: vi.fn(), + submitUserMessage: vi.fn(), } mockCurrentTask.messageManager = new MessageManager(mockCurrentTask) // Create mock provider mockClineProvider = { getCurrentTask: vi.fn().mockReturnValue(mockCurrentTask), + guardSessionEdit: vi.fn().mockResolvedValue(true), postMessageToWebview: vi.fn(), + postStateToWebview: vi.fn(), contextProxy: { getValue: vi.fn(), setValue: vi.fn(), @@ -78,6 +81,37 @@ describe("webviewMessageHandler - Edit Message with Timestamp Fallback", () => { } as unknown as ClineProvider }) + it("SH-19: an allowed edit rewinds and submits the edited content", async () => { + mockCurrentTask.clineMessages = [{ ts: 1, type: "say", say: "user_feedback", text: "original" }] + await webviewMessageHandler(mockClineProvider, { + type: "editMessageConfirm", + messageTs: 1, + text: "edited", + restoreCheckpoint: false, + }) + expect(mockCurrentTask.submitUserMessage).toHaveBeenCalledWith("edited", []) + }) + + it.each([false, true])( + "SH-18: blocked edit never rewinds or restores (checkpoint %s)", + async (restoreCheckpoint) => { + vi.mocked(mockClineProvider.guardSessionEdit).mockResolvedValue(false) + mockCurrentTask.clineMessages = [{ ts: 1, type: "say", say: "user_feedback", text: "original" }] + mockCurrentTask.submitUserMessage = vi.fn() + await webviewMessageHandler(mockClineProvider, { + type: "editMessageConfirm", + messageTs: 1, + text: "edited", + restoreCheckpoint, + }) + expect(mockClineProvider.guardSessionEdit).toHaveBeenCalledWith("test-task-id") + expect(mockCurrentTask.overwriteClineMessages).not.toHaveBeenCalled() + expect(mockCurrentTask.submitUserMessage).not.toHaveBeenCalled() + const { handleCheckpointRestoreOperation } = await import("../checkpointRestoreHandler") + expect(handleCheckpointRestoreOperation).not.toHaveBeenCalled() + }, + ) + it("should not modify API history when apiConversationHistoryIndex is -1", async () => { // Setup: User message followed by attempt_completion const userMessageTs = 1000 diff --git a/src/core/webview/webviewMessageHandler.ts b/src/core/webview/webviewMessageHandler.ts index 6f23d274e14..f7a77947fa8 100644 --- a/src/core/webview/webviewMessageHandler.ts +++ b/src/core/webview/webviewMessageHandler.ts @@ -398,17 +398,21 @@ export const webviewMessageHandler = async (provider: ClineProvider, message: We return } - // Use findMessageIndices to find messages based on timestamp - const { messageIndex, apiConversationHistoryIndex } = findMessageIndices(messageTs, currentCline) + try { + if (!(await provider.guardSessionEdit(currentCline.taskId))) { + return + } - if (messageIndex === -1) { - const errorMessage = t("common:errors.message.message_not_found", { messageTs }) - console.error("[handleEditMessageConfirm]", errorMessage) - await vscode.window.showErrorMessage(errorMessage) - return - } + // Use findMessageIndices to find messages based on timestamp + const { messageIndex, apiConversationHistoryIndex } = findMessageIndices(messageTs, currentCline) + + if (messageIndex === -1) { + const errorMessage = t("common:errors.message.message_not_found", { messageTs }) + console.error("[handleEditMessageConfirm]", errorMessage) + await vscode.window.showErrorMessage(errorMessage) + return + } - try { const targetMessage = currentCline.clineMessages[messageIndex] // If checkpoint restoration is requested, find and restore to the last checkpoint before this message @@ -736,6 +740,28 @@ export const webviewMessageHandler = async (provider: ClineProvider, message: We provider.exportTaskWithId(currentTaskId) } break + case "markSessionCompleted": + case "reopenSession": + case "resumeSession": { + try { + if (message.type === "resumeSession") { + const resolved = await resolveIncomingImages({ text: message.input, images: message.images }) + await provider.resumeSession(message.text!, resolved.text, resolved.images) + } else { + await provider[message.type](message.text!) + } + } catch (error) { + provider.log(`Failed to handle ${message.type} for task ${message.text}: ${String(error)}`) + vscode.window.showErrorMessage( + error instanceof Error && error.message === "Task not found" + ? t("common:errors.share_task_not_found") + : error instanceof Error + ? error.message + : String(error), + ) + } + break + } case "showTaskWithId": provider.showTaskWithId(message.text!) break diff --git a/src/i18n/locales/ca/common.json b/src/i18n/locales/ca/common.json index 39d523cccfd..e4eceadd64d 100644 --- a/src/i18n/locales/ca/common.json +++ b/src/i18n/locales/ca/common.json @@ -23,6 +23,15 @@ "delete_config_profile": "Estàs segur que vols eliminar aquest perfil de configuració?", "delete_custom_mode_with_rules": "Esteu segur que voleu suprimir aquest mode {scope}?\n\nAixò també suprimirà la carpeta de regles associada a:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Aquesta sessió està completada. Torna-la a obrir abans de reprendre la feina.", + "edit_not_sent": "El missatge editat no s'ha enviat.", + "resume_fallback": "No s'ha pogut restaurar la continuació prevista: {{reason}}. S'ha obert la tasca arrel de la sessió. Prem Reprèn allà per continuar.", + "cycle": "Les relacions entre tasques contenen un cicle", + "missingChild": "Falta la tasca filla esperada", + "missingAwaitingChild": "Una tasca delegada no identifica la tasca filla que espera", + "inconsistentChild": "La tasca filla esperada té relacions entre tasques incoherents o ja està completada" + }, "errors": { "invalid_data_uri": "Format d'URI de dades no vàlid", "error_copying_image": "Error copiant la imatge: {{errorMessage}}", diff --git a/src/i18n/locales/de/common.json b/src/i18n/locales/de/common.json index b507fdbecc1..ebf97d00b08 100644 --- a/src/i18n/locales/de/common.json +++ b/src/i18n/locales/de/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Möchtest du dieses Konfigurationsprofil wirklich löschen?", "delete_custom_mode_with_rules": "Bist du sicher, dass du diesen {scope}-Modus löschen möchtest?\n\nDadurch wird auch der zugehörige Regelordner unter folgender Adresse gelöscht:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Diese Sitzung ist abgeschlossen. Öffne sie erneut, bevor du weiterarbeitest.", + "edit_not_sent": "Die bearbeitete Nachricht wurde nicht gesendet.", + "resume_fallback": "Die vorgesehene Fortsetzung konnte nicht wiederhergestellt werden: {{reason}}. Die Hauptaufgabe der Sitzung wurde geöffnet. Klicke dort auf Fortsetzen, um weiterzuarbeiten.", + "cycle": "Die Aufgabenbeziehungen enthalten einen Zyklus", + "missingChild": "Die erwartete Unteraufgabe fehlt", + "missingAwaitingChild": "Eine delegierte Aufgabe gibt ihre erwartete Unteraufgabe nicht an", + "inconsistentChild": "Die erwartete Unteraufgabe hat widersprüchliche Aufgabenbeziehungen oder ist bereits abgeschlossen" + }, "errors": { "invalid_data_uri": "Ungültiges Daten-URI-Format", "error_copying_image": "Fehler beim Kopieren des Bildes: {{errorMessage}}", diff --git a/src/i18n/locales/en/common.json b/src/i18n/locales/en/common.json index eb623128025..f8b30304a34 100644 --- a/src/i18n/locales/en/common.json +++ b/src/i18n/locales/en/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Are you sure you want to delete this configuration profile?", "delete_custom_mode_with_rules": "Are you sure you want to delete this {scope} mode?\n\nThis will also delete the associated rules folder at:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "This session is completed. Reopen it before resuming work.", + "edit_not_sent": "The edited message was not sent.", + "resume_fallback": "The intended continuation could not be restored: {{reason}}. The session's root task was opened. Press Resume there to continue.", + "cycle": "The task relationships contain a cycle", + "missingChild": "The awaited child task is missing", + "missingAwaitingChild": "A delegated task does not identify its awaited child", + "inconsistentChild": "The awaited child has inconsistent task relationships or is already completed" + }, "errors": { "invalid_data_uri": "Invalid data URI format", "error_copying_image": "Error copying image: {{errorMessage}}", diff --git a/src/i18n/locales/es/common.json b/src/i18n/locales/es/common.json index 9b5835044aa..29058e990f4 100644 --- a/src/i18n/locales/es/common.json +++ b/src/i18n/locales/es/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "¿Estás seguro de que deseas eliminar este perfil de configuración?", "delete_custom_mode_with_rules": "¿Estás seguro de que quieres eliminar este modo {scope}?\n\nEsto también eliminará la carpeta de reglas asociada en:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Esta sesión está completada. Vuelve a abrirla antes de reanudar el trabajo.", + "edit_not_sent": "El mensaje editado no se envió.", + "resume_fallback": "No se pudo restaurar la continuación prevista: {{reason}}. Se abrió la tarea raíz de la sesión. Pulsa Reanudar allí para continuar.", + "cycle": "Las relaciones entre tareas contienen un ciclo", + "missingChild": "Falta la tarea hija esperada", + "missingAwaitingChild": "Una tarea delegada no identifica la tarea hija que espera", + "inconsistentChild": "La tarea hija esperada tiene relaciones entre tareas incoherentes o ya está completada" + }, "errors": { "invalid_data_uri": "Formato de URI de datos no válido", "error_copying_image": "Error copiando la imagen: {{errorMessage}}", diff --git a/src/i18n/locales/fr/common.json b/src/i18n/locales/fr/common.json index 40e52c56ca7..90dfe9dc2eb 100644 --- a/src/i18n/locales/fr/common.json +++ b/src/i18n/locales/fr/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Êtes-vous sûr de vouloir supprimer ce profil de configuration ?", "delete_custom_mode_with_rules": "Êtes-vous sûr de vouloir supprimer ce mode {scope} ?\n\nCela supprimera également le dossier de règles associé à l'adresse :\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Cette session est terminée. Rouvre-la avant de reprendre le travail.", + "edit_not_sent": "Le message modifié n'a pas été envoyé.", + "resume_fallback": "La suite prévue n'a pas pu être restaurée : {{reason}}. La tâche racine de la session a été ouverte. Appuie sur Reprendre à cet endroit pour continuer.", + "cycle": "Les relations entre les tâches contiennent un cycle", + "missingChild": "La tâche enfant attendue est introuvable", + "missingAwaitingChild": "Une tâche déléguée n'identifie pas la tâche enfant qu'elle attend", + "inconsistentChild": "La tâche enfant attendue a des relations incohérentes ou est déjà terminée" + }, "errors": { "invalid_data_uri": "Format d'URI de données invalide", "error_copying_image": "Erreur lors de la copie de l'image : {{errorMessage}}", diff --git a/src/i18n/locales/hi/common.json b/src/i18n/locales/hi/common.json index 9ca5924802b..1ebb001941b 100644 --- a/src/i18n/locales/hi/common.json +++ b/src/i18n/locales/hi/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "क्या आप वाकई इस कॉन्फ़िगरेशन प्रोफ़ाइल को हटाना चाहते हैं?", "delete_custom_mode_with_rules": "क्या आप वाकई इस {scope} मोड को हटाना चाहते हैं?\n\nयह संबंधित नियम फ़ोल्डर को भी यहाँ हटा देगा:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "यह सत्र पूरा हो चुका है। काम फिर से शुरू करने से पहले इसे दोबारा खोलो।", + "edit_not_sent": "संपादित संदेश भेजा नहीं गया।", + "resume_fallback": "काम को तय जगह से फिर शुरू करने की स्थिति बहाल नहीं हो सकी: {{reason}}। सत्र का मूल कार्य खोला गया है। आगे बढ़ने के लिए वहाँ फिर शुरू करो दबाओ।", + "cycle": "कार्यों के संबंधों में एक चक्र है", + "missingChild": "जिस उपकार्य का इंतज़ार है, वह मौजूद नहीं है", + "missingAwaitingChild": "एक सौंपे गए कार्य में उस उपकार्य की पहचान नहीं है जिसका उसे इंतज़ार है", + "inconsistentChild": "जिस उपकार्य का इंतज़ार है, उसके कार्य संबंध असंगत हैं या वह पहले ही पूरा हो चुका है" + }, "errors": { "invalid_data_uri": "अमान्य डेटा URI फॉर्मेट", "error_copying_image": "छवि कॉपी करने में त्रुटि: {{errorMessage}}", diff --git a/src/i18n/locales/id/common.json b/src/i18n/locales/id/common.json index 59853406f47..f2484ccecea 100644 --- a/src/i18n/locales/id/common.json +++ b/src/i18n/locales/id/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Apakah kamu yakin ingin menghapus profil konfigurasi ini?", "delete_custom_mode_with_rules": "Anda yakin ingin menghapus mode {scope} ini?\n\nIni juga akan menghapus folder aturan terkait di:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Sesi ini sudah selesai. Buka kembali sebelum melanjutkan pekerjaan.", + "edit_not_sent": "Pesan yang diedit tidak terkirim.", + "resume_fallback": "Kelanjutan yang dimaksud tidak dapat dipulihkan: {{reason}}. Tugas utama sesi telah dibuka. Tekan Lanjutkan di sana untuk melanjutkan.", + "cycle": "Hubungan antartugas membentuk siklus", + "missingChild": "Subtugas yang ditunggu tidak ditemukan", + "missingAwaitingChild": "Tugas yang didelegasikan tidak mencantumkan subtugas yang ditunggu", + "inconsistentChild": "Subtugas yang ditunggu memiliki hubungan tugas yang tidak konsisten atau sudah selesai" + }, "errors": { "invalid_data_uri": "Format data URI tidak valid", "error_copying_image": "Error menyalin gambar: {{errorMessage}}", diff --git a/src/i18n/locales/it/common.json b/src/i18n/locales/it/common.json index 27f1f545e86..d9876da6b0c 100644 --- a/src/i18n/locales/it/common.json +++ b/src/i18n/locales/it/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Sei sicuro di voler eliminare questo profilo di configurazione?", "delete_custom_mode_with_rules": "Sei sicuro di voler eliminare questa modalità {scope}?\n\nQuesto eliminerà anche la cartella delle regole associata in:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Questa sessione è completata. Riaprila prima di riprendere il lavoro.", + "edit_not_sent": "Il messaggio modificato non è stato inviato.", + "resume_fallback": "Non è stato possibile ripristinare la continuazione prevista: {{reason}}. È stata aperta l'attività radice della sessione. Premi Riprendi lì per continuare.", + "cycle": "Le relazioni tra le attività contengono un ciclo", + "missingChild": "La sottoattività attesa non è presente", + "missingAwaitingChild": "Un'attività delegata non identifica la sottoattività che sta aspettando", + "inconsistentChild": "La sottoattività attesa ha relazioni incoerenti o è già completata" + }, "errors": { "invalid_data_uri": "Formato URI dati non valido", "error_copying_image": "Errore durante la copia dell'immagine: {{errorMessage}}", diff --git a/src/i18n/locales/ja/common.json b/src/i18n/locales/ja/common.json index 315e7e51b8d..15710d121fb 100644 --- a/src/i18n/locales/ja/common.json +++ b/src/i18n/locales/ja/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "この設定プロファイルを削除してもよろしいですか?", "delete_custom_mode_with_rules": "この{scope}モードを削除してもよろしいですか?\n\nこれにより、関連するルールフォルダも次の場所で削除されます:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "このセッションは完了済み。作業を再開する前に、もう一度開いてね。", + "edit_not_sent": "編集したメッセージは送信されなかった。", + "resume_fallback": "予定していた続きの状態を復元できなかった:{{reason}}。セッションのルートタスクを開いたので、そこで「再開」を押して続けてね。", + "cycle": "タスク間の関係が循環している", + "missingChild": "待機中の子タスクが見つからない", + "missingAwaitingChild": "委任されたタスクに、待機中の子タスクが指定されていない", + "inconsistentChild": "待機中の子タスクの関係に矛盾があるか、すでに完了している" + }, "errors": { "invalid_data_uri": "データURIフォーマットが無効です", "error_copying_image": "画像のコピー中にエラーが発生しました:{{errorMessage}}", diff --git a/src/i18n/locales/ko/common.json b/src/i18n/locales/ko/common.json index 4b55a80e4a0..2fae8f1dc10 100644 --- a/src/i18n/locales/ko/common.json +++ b/src/i18n/locales/ko/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "이 구성 프로필을 삭제하시겠습니까?", "delete_custom_mode_with_rules": "이 {scope} 모드를 삭제하시겠습니까?\n\n이렇게 하면 연결된 규칙 폴더도 다음 위치에서 삭제됩니다:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "이 세션은 완료됐어. 작업을 재개하기 전에 다시 열어 줘.", + "edit_not_sent": "수정한 메시지가 전송되지 않았어.", + "resume_fallback": "이어서 진행할 상태를 복원하지 못했어: {{reason}}. 세션의 루트 작업을 열었어. 거기서 재개를 눌러 계속해 줘.", + "cycle": "작업 간 관계에 순환이 있어", + "missingChild": "기다리는 하위 작업이 없어", + "missingAwaitingChild": "위임된 작업에 기다리는 하위 작업이 지정되어 있지 않아", + "inconsistentChild": "기다리는 하위 작업의 관계가 일관되지 않거나 이미 완료됐어" + }, "errors": { "invalid_data_uri": "잘못된 데이터 URI 형식", "error_copying_image": "이미지 복사 중 오류 발생: {{errorMessage}}", diff --git a/src/i18n/locales/nl/common.json b/src/i18n/locales/nl/common.json index 1bf940c55bd..ced95a732f9 100644 --- a/src/i18n/locales/nl/common.json +++ b/src/i18n/locales/nl/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Weet je zeker dat je dit configuratieprofiel wilt verwijderen?", "delete_custom_mode_with_rules": "Weet je zeker dat je deze {scope}-modus wilt verwijderen?\n\nDit verwijdert ook de bijbehorende regelsmap op:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Deze sessie is voltooid. Heropen de sessie voordat je verder werkt.", + "edit_not_sent": "Het bewerkte bericht is niet verzonden.", + "resume_fallback": "De bedoelde voortzetting kon niet worden hersteld: {{reason}}. De hoofdtaak van de sessie is geopend. Druk daar op Hervatten om verder te gaan.", + "cycle": "De taakrelaties bevatten een cyclus", + "missingChild": "De verwachte subtaak ontbreekt", + "missingAwaitingChild": "Een gedelegeerde taak geeft niet aan op welke subtaak deze wacht", + "inconsistentChild": "De verwachte subtaak heeft inconsistente taakrelaties of is al voltooid" + }, "errors": { "invalid_data_uri": "Ongeldig data-URI-formaat", "error_copying_image": "Fout bij kopiëren van afbeelding: {{errorMessage}}", diff --git a/src/i18n/locales/pl/common.json b/src/i18n/locales/pl/common.json index 621f09b33bf..63233b41c95 100644 --- a/src/i18n/locales/pl/common.json +++ b/src/i18n/locales/pl/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Czy na pewno chcesz usunąć ten profil konfiguracyjny?", "delete_custom_mode_with_rules": "Czy na pewno chcesz usunąć ten tryb {scope}?\n\nSpowoduje to również usunięcie powiązanego folderu reguł pod adresem:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Ta sesja jest zakończona. Otwórz ją ponownie, zanim wznowisz pracę.", + "edit_not_sent": "Edytowana wiadomość nie została wysłana.", + "resume_fallback": "Nie udało się przywrócić planowanej kontynuacji: {{reason}}. Otwarto główne zadanie sesji. Naciśnij tam Wznów, aby kontynuować.", + "cycle": "Relacje między zadaniami zawierają cykl", + "missingChild": "Brakuje oczekiwanego podzadania", + "missingAwaitingChild": "Delegowane zadanie nie wskazuje podzadania, na które czeka", + "inconsistentChild": "Oczekiwane podzadanie ma niespójne relacje między zadaniami lub jest już zakończone" + }, "errors": { "invalid_data_uri": "Nieprawidłowy format URI danych", "error_copying_image": "Błąd kopiowania obrazu: {{errorMessage}}", diff --git a/src/i18n/locales/pt-BR/common.json b/src/i18n/locales/pt-BR/common.json index 3151f8b394e..d27999c8aca 100644 --- a/src/i18n/locales/pt-BR/common.json +++ b/src/i18n/locales/pt-BR/common.json @@ -23,6 +23,15 @@ "delete_config_profile": "Tem certeza de que deseja excluir este perfil de configuração?", "delete_custom_mode_with_rules": "Tem certeza de que deseja excluir este modo {scope}?\n\nIsso também excluirá a pasta de regras associada em:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Esta sessão está concluída. Reabra antes de retomar o trabalho.", + "edit_not_sent": "A mensagem editada não foi enviada.", + "resume_fallback": "Não foi possível restaurar a continuação prevista: {{reason}}. A tarefa raiz da sessão foi aberta. Pressione Retomar lá para continuar.", + "cycle": "As relações entre tarefas contêm um ciclo", + "missingChild": "A subtarefa aguardada não foi encontrada", + "missingAwaitingChild": "Uma tarefa delegada não identifica a subtarefa que está aguardando", + "inconsistentChild": "A subtarefa aguardada tem relações inconsistentes ou já está concluída" + }, "errors": { "invalid_data_uri": "Formato de URI de dados inválido", "error_copying_image": "Erro ao copiar imagem: {{errorMessage}}", diff --git a/src/i18n/locales/ru/common.json b/src/i18n/locales/ru/common.json index 7fa16c8b227..a5eb59687f9 100644 --- a/src/i18n/locales/ru/common.json +++ b/src/i18n/locales/ru/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Вы уверены, что хотите удалить этот профиль конфигурации?", "delete_custom_mode_with_rules": "Вы уверены, что хотите удалить этот режим {scope}?\n\nЭто также приведет к удалению соответствующей папки правил по адресу:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Эта сессия завершена. Открой её снова, прежде чем продолжить работу.", + "edit_not_sent": "Изменённое сообщение не отправлено.", + "resume_fallback": "Не удалось восстановить намеченное продолжение: {{reason}}. Открыта корневая задача сессии. Нажми там «Продолжить», чтобы возобновить работу.", + "cycle": "Связи между задачами образуют цикл", + "missingChild": "Ожидаемая подзадача отсутствует", + "missingAwaitingChild": "В делегированной задаче не указана ожидаемая подзадача", + "inconsistentChild": "У ожидаемой подзадачи противоречивые связи между задачами или она уже завершена" + }, "errors": { "invalid_data_uri": "Неверный формат URI данных", "error_copying_image": "Ошибка копирования изображения: {{errorMessage}}", diff --git a/src/i18n/locales/tr/common.json b/src/i18n/locales/tr/common.json index 5b657e4f12a..cb733bcd3f0 100644 --- a/src/i18n/locales/tr/common.json +++ b/src/i18n/locales/tr/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Bu yapılandırma profilini silmek istediğinizden emin misiniz?", "delete_custom_mode_with_rules": "Bu {scope} modunu silmek istediğinizden emin misiniz?\n\nBu işlem, ilişkili kurallar klasörünü de şu konumdan silecektir:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Bu oturum tamamlandı. Çalışmaya devam etmeden önce yeniden aç.", + "edit_not_sent": "Düzenlenen mesaj gönderilmedi.", + "resume_fallback": "Planlanan devam durumu geri yüklenemedi: {{reason}}. Oturumun kök görevi açıldı. Devam etmek için orada Sürdür'e bas.", + "cycle": "Görev ilişkileri bir döngü içeriyor", + "missingChild": "Beklenen alt görev bulunamadı", + "missingAwaitingChild": "Devredilen bir görev, beklediği alt görevi belirtmiyor", + "inconsistentChild": "Beklenen alt görevin görev ilişkileri tutarsız veya görev zaten tamamlanmış" + }, "errors": { "invalid_data_uri": "Geçersiz veri URI formatı", "error_copying_image": "Resim kopyalanırken hata oluştu: {{errorMessage}}", diff --git a/src/i18n/locales/vi/common.json b/src/i18n/locales/vi/common.json index 44a29eee42e..4ed54d86d30 100644 --- a/src/i18n/locales/vi/common.json +++ b/src/i18n/locales/vi/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "Bạn có chắc chắn muốn xóa hồ sơ cấu hình này không?", "delete_custom_mode_with_rules": "Bạn có chắc chắn muốn xóa chế độ {scope} này không?\n\nThao tác này cũng sẽ xóa thư mục quy tắc liên quan tại:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "Phiên này đã hoàn tất. Mở lại trước khi tiếp tục làm việc.", + "edit_not_sent": "Tin nhắn đã chỉnh sửa chưa được gửi.", + "resume_fallback": "Không thể khôi phục trạng thái tiếp tục dự kiến: {{reason}}. Tác vụ gốc của phiên đã được mở. Nhấn Tiếp tục ở đó để làm tiếp.", + "cycle": "Quan hệ giữa các tác vụ tạo thành vòng lặp", + "missingChild": "Không tìm thấy tác vụ con đang chờ", + "missingAwaitingChild": "Một tác vụ được ủy quyền không chỉ rõ tác vụ con mà nó đang chờ", + "inconsistentChild": "Tác vụ con đang chờ có quan hệ tác vụ không nhất quán hoặc đã hoàn tất" + }, "errors": { "invalid_data_uri": "Định dạng URI dữ liệu không hợp lệ", "error_copying_image": "Lỗi khi sao chép hình ảnh: {{errorMessage}}", diff --git a/src/i18n/locales/zh-CN/common.json b/src/i18n/locales/zh-CN/common.json index 761fe0f644b..4962b0920a5 100644 --- a/src/i18n/locales/zh-CN/common.json +++ b/src/i18n/locales/zh-CN/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "您确定要删除此配置文件吗?", "delete_custom_mode_with_rules": "您确定要删除此 {scope} 模式吗?\n\n这也将删除位于以下位置的关联规则文件夹:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "此会话已完成。继续工作前,先重新打开会话。", + "edit_not_sent": "编辑后的消息未发送。", + "resume_fallback": "无法恢复预期的继续位置:{{reason}}。已打开会话的根任务。点击该处的“继续”以恢复工作。", + "cycle": "任务关系中存在循环", + "missingChild": "等待的子任务不存在", + "missingAwaitingChild": "委派的任务未指定正在等待的子任务", + "inconsistentChild": "等待的子任务关系不一致,或子任务已完成" + }, "errors": { "invalid_mcp_config": "项目MCP配置格式无效", "invalid_mcp_settings_format": "MCP设置JSON格式无效。请确保您的设置遵循正确的JSON格式。", diff --git a/src/i18n/locales/zh-TW/common.json b/src/i18n/locales/zh-TW/common.json index b024defe85c..858656ef7a5 100644 --- a/src/i18n/locales/zh-TW/common.json +++ b/src/i18n/locales/zh-TW/common.json @@ -19,6 +19,15 @@ "delete_config_profile": "您確定要刪除此設定檔案嗎?", "delete_custom_mode_with_rules": "您確定要刪除此 {scope} 模式嗎?\n\n這也將刪除位於以下位置的關聯規則資料夾:\n{rulesFolderPath}" }, + "session_history": { + "reopen_first": "此工作階段已完成。繼續工作前,先重新開啟工作階段。", + "edit_not_sent": "編輯後的訊息未傳送。", + "resume_fallback": "無法還原預期的接續位置:{{reason}}。已開啟工作階段的根工作。按一下該處的「繼續」以恢復工作。", + "cycle": "工作關係中存在循環", + "missingChild": "等待的子工作不存在", + "missingAwaitingChild": "委派的工作未指定正在等待的子工作", + "inconsistentChild": "等待的子工作關係不一致,或子工作已完成" + }, "errors": { "invalid_data_uri": "資料 URI 格式無效", "error_copying_image": "複製圖片時發生錯誤:{{errorMessage}}", diff --git a/webview-ui/src/components/chat/ChatView.tsx b/webview-ui/src/components/chat/ChatView.tsx index b799a58bb8b..8eea40aaaf7 100644 --- a/webview-ui/src/components/chat/ChatView.tsx +++ b/webview-ui/src/components/chat/ChatView.tsx @@ -133,6 +133,7 @@ const ChatViewComponent: React.ForwardRefRenderFunction() const sendingDisabled = baseSendingDisabled || manualCondenseTaskId !== undefined const [selectedImages, setSelectedImages] = useState([]) + const pendingResumeTaskIdRef = useRef() // We need to hold on to the ask because useEffect > lastMessage will always // let us know when an ask comes in and handle it, but by the time @@ -567,6 +568,7 @@ const ChatViewComponent: React.ForwardRefRenderFunction { + pendingResumeTaskIdRef.current = undefined // Clear any pending auto-approval timeout if (autoApproveTimeoutRef.current) { clearTimeout(autoApproveTimeoutRef.current) @@ -586,6 +588,22 @@ const ChatViewComponent: React.ForwardRefRenderFunction { + if (!currentTaskItem) { + return + } + pendingResumeTaskIdRef.current = currentTaskItem.id + vscode.postMessage({ + type: "resumeSession", + text: currentTaskItem.id, + ...(input ? { input } : {}), + ...(images?.length ? { images } : {}), + }) + }, + [currentTaskItem], + ) + /** * Handles sending messages to the extension * @param text - The message text to send @@ -603,6 +621,11 @@ const ChatViewComponent: React.ForwardRefRenderFunction 0)) { - vscode.postMessage({ - type: "askResponse", - askResponse: "yesButtonClicked", - text: trimmedInput, - images: images, - }) - // Clear input state after sending - setInputValue("") - setSelectedImages([]) - } else { - vscode.postMessage({ type: "askResponse", askResponse: "yesButtonClicked" }) - } + resumeSession(trimmedInput, images) + return } break case "completion_result": @@ -791,7 +802,7 @@ const ChatViewComponent: React.ForwardRefRenderFunction
e.stopPropagation()}> + {!isSubtask && currentTaskItem && !currentTaskItem.parentTaskId && ( + + )} + + + + {t("history:markSessionCompleted")} + {t("history:completeSessionMessage")} + + + + + + + + + + + +
+ ) +} diff --git a/webview-ui/src/components/history/TaskItem.tsx b/webview-ui/src/components/history/TaskItem.tsx index eba5e59ac94..8d03dec5a93 100644 --- a/webview-ui/src/components/history/TaskItem.tsx +++ b/webview-ui/src/components/history/TaskItem.tsx @@ -7,7 +7,9 @@ import { cn } from "@/lib/utils" import { Checkbox } from "@/components/ui/checkbox" import TaskItemFooter from "./TaskItemFooter" -import { StandardTooltip } from "../ui" +import { StandardTooltip, Button } from "../ui" +import { useAppTranslation } from "@/i18n/TranslationContext" +import { SessionCompletionButton } from "./SessionCompletionButton" interface TaskItemProps { item: DisplayHistoryItem @@ -32,6 +34,9 @@ const TaskItem = ({ onDelete, className, }: TaskItemProps) => { + const { t } = useAppTranslation() + const isRoot = !item.parentTaskId + const completed = item.sessionCompletedAt !== undefined const handleClick = () => { if (isSelectionMode && onToggleSelection) { onToggleSelection(item.id, !isSelected) @@ -109,6 +114,27 @@ const TaskItem = ({ )} + {isRoot && ( +
event.stopPropagation()}> + {completed && ( + + {t("history:sessionCompleted")} + + )} + {!isSelectionMode && ( + <> + + + + )} +
+ )} + { }) }) + it("offers a local Show completed toggle that starts off", () => { + render() + const toggle = screen.getByRole("checkbox", { name: "history:showCompleted" }) + expect(toggle).not.toBeChecked() + fireEvent.click(toggle) + expect(toggle).toBeChecked() + fireEvent.click(toggle) + expect(toggle).not.toBeChecked() + }) + it("renders the history interface", () => { const onDone = vi.fn() render() @@ -63,3 +73,10 @@ describe("HistoryView", () => { expect(onDone).toHaveBeenCalled() }) }) + +// Share the renderer's React instance across Vite and native dependencies. +vi.mock("react", async () => { + const { createRequire } = await import("node:module") + const react = createRequire(import.meta.url)("react") + return { ...react, default: react } +}) diff --git a/webview-ui/src/components/history/__tests__/TaskItem.spec.tsx b/webview-ui/src/components/history/__tests__/TaskItem.spec.tsx index df8fc742d3c..d5a3ef6c096 100644 --- a/webview-ui/src/components/history/__tests__/TaskItem.spec.tsx +++ b/webview-ui/src/components/history/__tests__/TaskItem.spec.tsx @@ -1,6 +1,7 @@ import { render, screen, fireEvent } from "@/utils/test-utils" import TaskItem from "../TaskItem" +import { vscode } from "@/utils/vscode" vi.mock("@src/utils/vscode") vi.mock("@src/i18n/TranslationContext", () => ({ @@ -31,6 +32,41 @@ describe("TaskItem", () => { vi.clearAllMocks() }) + it("keeps row inspection separate from Resume and confirmed completion", () => { + render() + fireEvent.click(screen.getByTestId("task-content")) + expect(vscode.postMessage).toHaveBeenLastCalledWith({ type: "showTaskWithId", text: "1" }) + vi.mocked(vscode.postMessage).mockClear() + fireEvent.click(screen.getByRole("button", { name: "history:resumeSession" })) + expect(vscode.postMessage).toHaveBeenCalledTimes(1) + expect(vscode.postMessage).toHaveBeenCalledWith({ type: "resumeSession", text: "1" }) + vi.mocked(vscode.postMessage).mockClear() + fireEvent.click(screen.getByRole("button", { name: "history:markSessionCompleted" })) + expect(screen.getByText("history:completeSessionMessage")).toBeInTheDocument() + expect(vscode.postMessage).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole("button", { name: "history:cancel" })) + expect(vscode.postMessage).not.toHaveBeenCalled() + fireEvent.click(screen.getByRole("button", { name: "history:markSessionCompleted" })) + fireEvent.click(screen.getByRole("button", { name: "history:confirmSessionCompleted" })) + expect(vscode.postMessage).toHaveBeenCalledTimes(1) + expect(vscode.postMessage).toHaveBeenCalledWith({ type: "markSessionCompleted", text: "1" }) + }) + + it("identifies completed sessions and reopens without resuming or inspecting", () => { + render() + expect(screen.getByText("history:sessionCompleted")).toBeInTheDocument() + expect(screen.queryByRole("button", { name: "history:markSessionCompleted" })).not.toBeInTheDocument() + fireEvent.click(screen.getByRole("button", { name: "history:reopenSession" })) + expect(vscode.postMessage).toHaveBeenCalledTimes(1) + expect(vscode.postMessage).toHaveBeenCalledWith({ type: "reopenSession", text: "1" }) + }) + + it("does not offer session actions on child search results", () => { + render() + expect(screen.queryByRole("button", { name: "history:resumeSession" })).not.toBeInTheDocument() + expect(screen.queryByRole("button", { name: "history:markSessionCompleted" })).not.toBeInTheDocument() + }) + it("renders task information", () => { render( { expect(taskItem).toHaveClass("hover:text-vscode-foreground") }) }) + +// Share the renderer's React instance across Vite and native dependencies. +vi.mock("react", async () => { + const { createRequire } = await import("node:module") + const react = createRequire(import.meta.url)("react") + return { ...react, default: react } +}) diff --git a/webview-ui/src/components/history/__tests__/useTaskSearch.spec.tsx b/webview-ui/src/components/history/__tests__/useTaskSearch.spec.tsx index bea79814fa1..e72aa8f5da7 100644 --- a/webview-ui/src/components/history/__tests__/useTaskSearch.spec.tsx +++ b/webview-ui/src/components/history/__tests__/useTaskSearch.spec.tsx @@ -60,6 +60,35 @@ describe("useTaskSearch", () => { } as any) }) + it("hides completed roots and every descendant before workspace and search filtering", () => { + mockUseExtensionState.mockReturnValue({ + cwd: "/workspace/project1", + taskHistory: [ + { ...mockTaskHistory[2], id: "root", sessionCompletedAt: 0 }, + { ...mockTaskHistory[0], id: "child", parentTaskId: "root" }, + { ...mockTaskHistory[0], id: "grandchild", parentTaskId: "child" }, + { ...mockTaskHistory[1], status: "completed", parentTaskId: "missing" }, + ], + }) + const { result, unmount } = renderHook(() => useTaskSearch()) + expect(result.current.showCompleted).toBe(false) + expect(result.current.tasks.map((task) => task.id)).toEqual(["task-2"]) + act(() => result.current.setSearchQuery("React")) + expect(result.current.tasks).toHaveLength(0) + act(() => result.current.setShowCompleted(true)) + expect(result.current.tasks.map((task) => task.id).sort()).toEqual(["child", "grandchild"]) + act(() => { + result.current.setSearchQuery("") + result.current.setShowAllWorkspaces(true) + }) + expect(result.current.tasks).toHaveLength(4) + act(() => result.current.setShowCompleted(false)) + expect(result.current.tasks.map((task) => task.id)).toEqual(["task-2"]) + unmount() + const remounted = renderHook(() => useTaskSearch()) + expect(remounted.result.current.showCompleted).toBe(false) + }) + it("returns all tasks by default", () => { const { result } = renderHook(() => useTaskSearch()) @@ -285,3 +314,10 @@ describe("useTaskSearch", () => { expect(result.current.sortOption).toBe("mostRelevant") }) }) + +// Share the renderer's React instance across Vite and native dependencies. +vi.mock("react", async () => { + const { createRequire } = await import("node:module") + const react = createRequire(import.meta.url)("react") + return { ...react, default: react } +}) diff --git a/webview-ui/src/components/history/useTaskSearch.ts b/webview-ui/src/components/history/useTaskSearch.ts index 3969985b98a..fe077669928 100644 --- a/webview-ui/src/components/history/useTaskSearch.ts +++ b/webview-ui/src/components/history/useTaskSearch.ts @@ -13,6 +13,37 @@ export const useTaskSearch = () => { const [lastNonRelevantSort, setLastNonRelevantSort] = useState("newest") const [showAllWorkspaces, setShowAllWorkspaces] = useState(false) + const [showCompleted, setShowCompleted] = useState(false) + + const hiddenTaskIds = useMemo(() => { + const hiddenIds = new Set() + if (showCompleted) { + return hiddenIds + } + const taskIds = new Set(taskHistory.map((item) => item.id)) + const children = new Map() + const pendingIds: string[] = [] + for (const item of taskHistory) { + if (item.parentTaskId && taskIds.has(item.parentTaskId)) { + const siblings = children.get(item.parentTaskId) ?? [] + siblings.push(item.id) + children.set(item.parentTaskId, siblings) + } else if (item.sessionCompletedAt !== undefined) { + pendingIds.push(item.id) + } + } + while (pendingIds.length > 0) { + const taskId = pendingIds.pop()! + if (!hiddenIds.has(taskId)) { + hiddenIds.add(taskId) + for (const childId of children.get(taskId) ?? []) { + pendingIds.push(childId) + } + } + } + return hiddenIds + }, [taskHistory, showCompleted]) + useEffect(() => { if (searchQuery && sortOption !== "mostRelevant" && !lastNonRelevantSort) { setLastNonRelevantSort(sortOption) @@ -24,12 +55,12 @@ export const useTaskSearch = () => { }, [searchQuery, sortOption, lastNonRelevantSort]) const presentableTasks = useMemo(() => { - let tasks = taskHistory.filter((item) => item.ts && item.task) + let tasks = taskHistory.filter((item) => item.ts && item.task && !hiddenTaskIds.has(item.id)) if (!showAllWorkspaces) { tasks = tasks.filter((item) => item.workspace === cwd) } return tasks - }, [taskHistory, showAllWorkspaces, cwd]) + }, [taskHistory, showAllWorkspaces, cwd, hiddenTaskIds]) const fzf = useMemo(() => { return new Fzf(presentableTasks, { @@ -86,6 +117,8 @@ export const useTaskSearch = () => { setSortOption, lastNonRelevantSort, setLastNonRelevantSort, + showCompleted, + setShowCompleted, showAllWorkspaces, setShowAllWorkspaces, } diff --git a/webview-ui/src/i18n/locales/ca/history.json b/webview-ui/src/i18n/locales/ca/history.json index ab1bba7582e..b4fa411ad9a 100644 --- a/webview-ui/src/i18n/locales/ca/history.json +++ b/webview-ui/src/i18n/locales/ca/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Mostra les completades", + "sessionCompleted": "Completada", + "markSessionCompleted": "Completa i conserva la sessió", + "confirmSessionCompleted": "Completa i conserva", + "completeSessionMessage": "Vols conservar aquesta sessió i els seus missatges, però amagar-la de l'historial per defecte? No s'elimina res i qualsevol feina en curs continuarà. Fes servir Mostra les completades per trobar-la i tornar-la a obrir més endavant.", + "reopenSession": "Torna a obrir la sessió", + "resumeSession": "Reprèn", "recentTasks": "Tasques", "viewAll": "Veure tot", "tokens": "Tokens: ↑{{in}} ↓{{out}}", diff --git a/webview-ui/src/i18n/locales/de/history.json b/webview-ui/src/i18n/locales/de/history.json index 46064d6e2ea..b801fdcf833 100644 --- a/webview-ui/src/i18n/locales/de/history.json +++ b/webview-ui/src/i18n/locales/de/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Abgeschlossene anzeigen", + "sessionCompleted": "Abgeschlossen", + "markSessionCompleted": "Sitzung abschließen und behalten", + "confirmSessionCompleted": "Abschließen und behalten", + "completeSessionMessage": "Diese Sitzung samt Nachrichten behalten, aber standardmäßig im Verlauf ausblenden? Nichts wird gelöscht und laufende Arbeiten werden fortgesetzt. Mit Abgeschlossene anzeigen kannst du sie später finden und erneut öffnen.", + "reopenSession": "Sitzung erneut öffnen", + "resumeSession": "Fortsetzen", "recentTasks": "Aufgaben", "viewAll": "Alle anzeigen", "tokens": "Tokens: ↑{{in}} ↓{{out}}", diff --git a/webview-ui/src/i18n/locales/en/history.json b/webview-ui/src/i18n/locales/en/history.json index 85174890e14..0542c6252a0 100644 --- a/webview-ui/src/i18n/locales/en/history.json +++ b/webview-ui/src/i18n/locales/en/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Show completed", + "sessionCompleted": "Completed", + "markSessionCompleted": "Complete and keep session", + "confirmSessionCompleted": "Complete and keep", + "completeSessionMessage": "Keep this session and its messages, but hide it from history by default? Nothing is deleted, and any running work will continue. Use Show completed to find and reopen it later.", + "reopenSession": "Reopen session", + "resumeSession": "Resume", "recentTasks": "Recent Tasks", "history": "History", "exitSelectionMode": "Exit Selection Mode", diff --git a/webview-ui/src/i18n/locales/es/history.json b/webview-ui/src/i18n/locales/es/history.json index 820f003d402..ad8c8ac0042 100644 --- a/webview-ui/src/i18n/locales/es/history.json +++ b/webview-ui/src/i18n/locales/es/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Mostrar completadas", + "sessionCompleted": "Completada", + "markSessionCompleted": "Completar y conservar sesión", + "confirmSessionCompleted": "Completar y conservar", + "completeSessionMessage": "¿Quieres conservar esta sesión y sus mensajes, pero ocultarla del historial de forma predeterminada? No se elimina nada y cualquier trabajo en curso continuará. Usa Mostrar completadas para encontrarla y volver a abrirla más tarde.", + "reopenSession": "Volver a abrir sesión", + "resumeSession": "Reanudar", "recentTasks": "Tareas", "viewAll": "Ver todas", "tokens": "Tokens: ↑{{in}} ↓{{out}}", diff --git a/webview-ui/src/i18n/locales/fr/history.json b/webview-ui/src/i18n/locales/fr/history.json index d84cfcb190a..c25d4bfc723 100644 --- a/webview-ui/src/i18n/locales/fr/history.json +++ b/webview-ui/src/i18n/locales/fr/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Afficher les sessions terminées", + "sessionCompleted": "Terminée", + "markSessionCompleted": "Terminer et conserver la session", + "confirmSessionCompleted": "Terminer et conserver", + "completeSessionMessage": "Conserver cette session et ses messages, mais la masquer dans l'historique par défaut ? Rien n'est supprimé et tout travail en cours continuera. Utilise Afficher les sessions terminées pour la retrouver et la rouvrir plus tard.", + "reopenSession": "Rouvrir la session", + "resumeSession": "Reprendre", "recentTasks": "Tâches", "viewAll": "Voir tout", "tokens": "Tokens: ↑{{in}} ↓{{out}}", diff --git a/webview-ui/src/i18n/locales/hi/history.json b/webview-ui/src/i18n/locales/hi/history.json index 0d4cb40dd9e..291300ee057 100644 --- a/webview-ui/src/i18n/locales/hi/history.json +++ b/webview-ui/src/i18n/locales/hi/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "पूरे हुए सत्र दिखाओ", + "sessionCompleted": "पूरा हुआ", + "markSessionCompleted": "सत्र पूरा करो और रखो", + "confirmSessionCompleted": "पूरा करो और रखो", + "completeSessionMessage": "इस सत्र और इसके संदेशों को रखते हुए इसे इतिहास में डिफ़ॉल्ट रूप से छिपाना है? कुछ भी नहीं मिटेगा और चल रहा काम जारी रहेगा। बाद में इसे ढूँढने और दोबारा खोलने के लिए पूरे हुए सत्र दिखाओ का उपयोग करो।", + "reopenSession": "सत्र दोबारा खोलो", + "resumeSession": "फिर शुरू करो", "recentTasks": "हाल के कार्य", "history": "इतिहास", "exitSelectionMode": "चयन मोड से बाहर निकलें", diff --git a/webview-ui/src/i18n/locales/id/history.json b/webview-ui/src/i18n/locales/id/history.json index 7796061107e..0e66dd8fa58 100644 --- a/webview-ui/src/i18n/locales/id/history.json +++ b/webview-ui/src/i18n/locales/id/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Tampilkan yang selesai", + "sessionCompleted": "Selesai", + "markSessionCompleted": "Selesaikan dan simpan sesi", + "confirmSessionCompleted": "Selesaikan dan simpan", + "completeSessionMessage": "Simpan sesi ini beserta pesannya, tetapi sembunyikan dari riwayat secara default? Tidak ada yang dihapus, dan pekerjaan yang sedang berjalan akan tetap berlanjut. Gunakan Tampilkan yang selesai untuk menemukan dan membukanya kembali nanti.", + "reopenSession": "Buka kembali sesi", + "resumeSession": "Lanjutkan", "recentTasks": "Tugas", "viewAll": "Lihat Semua Tugas", "tokens": "Token: ↑{{in}} ↓{{out}}", diff --git a/webview-ui/src/i18n/locales/it/history.json b/webview-ui/src/i18n/locales/it/history.json index aa728ef8f60..bb054152a93 100644 --- a/webview-ui/src/i18n/locales/it/history.json +++ b/webview-ui/src/i18n/locales/it/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Mostra completate", + "sessionCompleted": "Completata", + "markSessionCompleted": "Completa e conserva la sessione", + "confirmSessionCompleted": "Completa e conserva", + "completeSessionMessage": "Vuoi conservare questa sessione e i suoi messaggi, ma nasconderla dalla cronologia per impostazione predefinita? Non verrà eliminato nulla e il lavoro in corso continuerà. Usa Mostra completate per trovarla e riaprirla in seguito.", + "reopenSession": "Riapri sessione", + "resumeSession": "Riprendi", "recentTasks": "Attività recenti", "history": "Cronologia", "exitSelectionMode": "Esci dalla modalità selezione", diff --git a/webview-ui/src/i18n/locales/ja/history.json b/webview-ui/src/i18n/locales/ja/history.json index b73baa3a763..c320be10b94 100644 --- a/webview-ui/src/i18n/locales/ja/history.json +++ b/webview-ui/src/i18n/locales/ja/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "完了済みを表示", + "sessionCompleted": "完了済み", + "markSessionCompleted": "セッションを完了して保持", + "confirmSessionCompleted": "完了して保持", + "completeSessionMessage": "このセッションとメッセージを残したまま、通常は履歴に表示しないようにする?何も削除されず、実行中の作業も続くよ。後で見つけて開き直すには「完了済みを表示」を使ってね。", + "reopenSession": "セッションを再度開く", + "resumeSession": "再開", "recentTasks": "最近のタスク", "history": "履歴", "exitSelectionMode": "選択モードを終了", diff --git a/webview-ui/src/i18n/locales/ko/history.json b/webview-ui/src/i18n/locales/ko/history.json index 0363feaaffb..4c981557b05 100644 --- a/webview-ui/src/i18n/locales/ko/history.json +++ b/webview-ui/src/i18n/locales/ko/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "완료된 세션 표시", + "sessionCompleted": "완료됨", + "markSessionCompleted": "세션 완료 및 보관", + "confirmSessionCompleted": "완료 및 보관", + "completeSessionMessage": "이 세션과 메시지를 보관하되 기본적으로 기록에서 숨길까? 아무것도 삭제되지 않고 실행 중인 작업도 계속돼. 나중에 찾아서 다시 열려면 완료된 세션 표시를 사용해 줘.", + "reopenSession": "세션 다시 열기", + "resumeSession": "재개", "recentTasks": "최근 작업", "history": "기록", "exitSelectionMode": "선택 모드 종료", diff --git a/webview-ui/src/i18n/locales/nl/history.json b/webview-ui/src/i18n/locales/nl/history.json index 012059ed047..469f2e3f69f 100644 --- a/webview-ui/src/i18n/locales/nl/history.json +++ b/webview-ui/src/i18n/locales/nl/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Voltooide sessies tonen", + "sessionCompleted": "Voltooid", + "markSessionCompleted": "Sessie voltooien en bewaren", + "confirmSessionCompleted": "Voltooien en bewaren", + "completeSessionMessage": "Deze sessie en de berichten bewaren, maar standaard verbergen in de geschiedenis? Er wordt niets verwijderd en lopend werk gaat door. Gebruik Voltooide sessies tonen om de sessie later te vinden en te heropenen.", + "reopenSession": "Sessie heropenen", + "resumeSession": "Hervatten", "recentTasks": "Recente taken", "history": "Geschiedenis", "exitSelectionMode": "Selectiemodus verlaten", diff --git a/webview-ui/src/i18n/locales/pl/history.json b/webview-ui/src/i18n/locales/pl/history.json index 7ec4b40d8f5..4945d70e17a 100644 --- a/webview-ui/src/i18n/locales/pl/history.json +++ b/webview-ui/src/i18n/locales/pl/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Pokaż zakończone", + "sessionCompleted": "Zakończona", + "markSessionCompleted": "Zakończ i zachowaj sesję", + "confirmSessionCompleted": "Zakończ i zachowaj", + "completeSessionMessage": "Zachować tę sesję i jej wiadomości, ale domyślnie ukryć ją w historii? Nic nie zostanie usunięte, a trwająca praca będzie kontynuowana. Użyj Pokaż zakończone, aby później znaleźć sesję i otworzyć ją ponownie.", + "reopenSession": "Otwórz sesję ponownie", + "resumeSession": "Wznów", "recentTasks": "Ostatnie zadania", "history": "Historia", "exitSelectionMode": "Wyłącz tryb wyboru", diff --git a/webview-ui/src/i18n/locales/pt-BR/history.json b/webview-ui/src/i18n/locales/pt-BR/history.json index 7966df1f463..d6a0709e98d 100644 --- a/webview-ui/src/i18n/locales/pt-BR/history.json +++ b/webview-ui/src/i18n/locales/pt-BR/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Mostrar concluídas", + "sessionCompleted": "Concluída", + "markSessionCompleted": "Concluir e manter sessão", + "confirmSessionCompleted": "Concluir e manter", + "completeSessionMessage": "Manter esta sessão e suas mensagens, mas ocultá-la do histórico por padrão? Nada será excluído e qualquer trabalho em andamento continuará. Use Mostrar concluídas para encontrá-la e reabri-la depois.", + "reopenSession": "Reabrir sessão", + "resumeSession": "Retomar", "recentTasks": "Tarefas recentes", "history": "Histórico", "exitSelectionMode": "Sair do modo de seleção", diff --git a/webview-ui/src/i18n/locales/ru/history.json b/webview-ui/src/i18n/locales/ru/history.json index 7852362348b..de4d9aeb288 100644 --- a/webview-ui/src/i18n/locales/ru/history.json +++ b/webview-ui/src/i18n/locales/ru/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Показать завершённые", + "sessionCompleted": "Завершена", + "markSessionCompleted": "Завершить и сохранить сессию", + "confirmSessionCompleted": "Завершить и сохранить", + "completeSessionMessage": "Сохранить эту сессию и её сообщения, но по умолчанию скрыть её из истории? Ничего не удаляется, а текущая работа продолжится. Используй «Показать завершённые», чтобы позже найти сессию и открыть её снова.", + "reopenSession": "Открыть сессию снова", + "resumeSession": "Продолжить", "recentTasks": "Недавние задачи", "history": "История", "exitSelectionMode": "Выйти из режима выбора", diff --git a/webview-ui/src/i18n/locales/tr/history.json b/webview-ui/src/i18n/locales/tr/history.json index fb7b6c68320..7b152666a9e 100644 --- a/webview-ui/src/i18n/locales/tr/history.json +++ b/webview-ui/src/i18n/locales/tr/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Tamamlananları göster", + "sessionCompleted": "Tamamlandı", + "markSessionCompleted": "Oturumu tamamla ve sakla", + "confirmSessionCompleted": "Tamamla ve sakla", + "completeSessionMessage": "Bu oturum ve mesajları saklansın, ancak varsayılan olarak geçmişte gizlensin mi? Hiçbir şey silinmez ve devam eden çalışmalar sürer. Daha sonra bulup yeniden açmak için Tamamlananları göster'i kullan.", + "reopenSession": "Oturumu yeniden aç", + "resumeSession": "Sürdür", "recentTasks": "Son görevler", "history": "Geçmiş", "exitSelectionMode": "Seçim Modundan Çık", diff --git a/webview-ui/src/i18n/locales/vi/history.json b/webview-ui/src/i18n/locales/vi/history.json index 779953e5406..8367ca6ace0 100644 --- a/webview-ui/src/i18n/locales/vi/history.json +++ b/webview-ui/src/i18n/locales/vi/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "Hiện phiên đã hoàn tất", + "sessionCompleted": "Đã hoàn tất", + "markSessionCompleted": "Hoàn tất và giữ phiên", + "confirmSessionCompleted": "Hoàn tất và giữ lại", + "completeSessionMessage": "Giữ phiên này cùng các tin nhắn nhưng mặc định ẩn khỏi lịch sử? Không có gì bị xóa và mọi công việc đang chạy vẫn tiếp tục. Dùng Hiện phiên đã hoàn tất để tìm và mở lại sau.", + "reopenSession": "Mở lại phiên", + "resumeSession": "Tiếp tục", "recentTasks": "Nhiệm vụ gần đây", "history": "Lịch sử", "exitSelectionMode": "Thoát chế độ chọn", diff --git a/webview-ui/src/i18n/locales/zh-CN/history.json b/webview-ui/src/i18n/locales/zh-CN/history.json index 20a73240ea9..e37d5012094 100644 --- a/webview-ui/src/i18n/locales/zh-CN/history.json +++ b/webview-ui/src/i18n/locales/zh-CN/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "显示已完成", + "sessionCompleted": "已完成", + "markSessionCompleted": "完成并保留会话", + "confirmSessionCompleted": "完成并保留", + "completeSessionMessage": "保留此会话及其消息,但默认在历史记录中隐藏?不会删除任何内容,正在运行的工作也会继续。之后可通过“显示已完成”找到并重新打开会话。", + "reopenSession": "重新打开会话", + "resumeSession": "继续", "recentTasks": "最近任务", "history": "历史记录", "exitSelectionMode": "退出多选模式", diff --git a/webview-ui/src/i18n/locales/zh-TW/history.json b/webview-ui/src/i18n/locales/zh-TW/history.json index 1e12190a69b..120f2e74943 100644 --- a/webview-ui/src/i18n/locales/zh-TW/history.json +++ b/webview-ui/src/i18n/locales/zh-TW/history.json @@ -1,4 +1,11 @@ { + "showCompleted": "顯示已完成", + "sessionCompleted": "已完成", + "markSessionCompleted": "完成並保留工作階段", + "confirmSessionCompleted": "完成並保留", + "completeSessionMessage": "保留此工作階段及其訊息,但預設在歷程記錄中隱藏?不會刪除任何內容,執行中的工作也會繼續。之後可透過「顯示已完成」找到並重新開啟工作階段。", + "reopenSession": "重新開啟工作階段", + "resumeSession": "繼續", "recentTasks": "最近工作", "history": "歷史紀錄", "exitSelectionMode": "離開選擇模式",