diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index a563b6a4ee3a7..470091f334fb7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -555,8 +555,40 @@ describe("parseResolvedPath", () => { // Path.layer joins with POSIX separators here, so the test windir is a POSIX path. const WSL_EXE = "/windows/System32/wsl.exe"; +const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; +const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; + +const registrySpawner = (keys: ReadonlyArray) => + ChildProcessSpawner.make((command) => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode( + command._tag === "StandardCommand" && + command.command === "reg.exe" && + keys.some((key) => command.args.includes(key)) + ? 0 + : 1, + ), + ), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); -const isAvailable = (policy?: Parameters[0]) => +const isAvailable = ( + policy?: Parameters[0], + serviceKeys: ReadonlyArray = [STORE_SERVICE], +) => makeIsAvailable("win32", "/windows").pipe( Effect.provide( Layer.mergeAll( @@ -565,9 +597,17 @@ const isAvailable = (policy?: Parameters[ DesktopManagedPolicy.layerTest(policy), ), ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, registrySpawner(serviceKeys)), ); describe("makeIsAvailable", () => { + it.effect("needs a registered WSL service, not just the System32 install stub", () => + Effect.gen(function* () { + assert.isFalse(yield* isAvailable(undefined, [])); + assert.isTrue(yield* isAvailable(undefined, [INBOX_SERVICE])); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index f1d2fccde537b..9d9540a65dc7d 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1119,13 +1119,50 @@ const getUserHomeImpl = ( Effect.orElseSucceed(() => Option.none()), ); +// Store/MSI WSL registers WSLService and inbox WSL registers LxssManager; either key means installed. +const WSL_SERVICE_KEYS = [ + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", +] as const; +const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); + +const wslServiceRegistered = Effect.scoped( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const registered = yield* Effect.forEach( + WSL_SERVICE_KEYS, + (key) => + spawner + .spawn( + ChildProcess.make("reg.exe", ["query", key], { + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + killSignal: "SIGTERM", + forceKillAfter: PROCESS_TERMINATE_GRACE, + }), + ) + .pipe(Effect.flatMap((handle) => handle.exitCode)), + { concurrency: "unbounded" }, + ); + return registered.some((exitCode) => (exitCode as unknown as number) === 0); + }), +).pipe( + Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.orElseSucceed(() => false), +); + export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* ( platform: NodeJS.Platform, windir: string, ): Effect.fn.Return< boolean, never, - FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy + | FileSystem.FileSystem + | Path.Path + | DesktopManagedPolicy.DesktopManagedPolicy + | ChildProcessSpawner.ChildProcessSpawner > { if (platform !== "win32") return false; const path = yield* Path.Path; @@ -1134,6 +1171,8 @@ export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable" if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) { return false; } + // System32\wsl.exe is also an install stub on Windows without WSL, so check for its service. + if (!(yield* wslServiceRegistered)) return false; // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none. return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( Effect.map((found) => found === undefined), @@ -1245,6 +1284,7 @@ export const layer = Layer.effect( // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O. const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, environment.path), Effect.provideService( DesktopManagedPolicy.DesktopManagedPolicy, diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts index 8a6ed2e03085a..50a004d679003 100644 --- a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts +++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts @@ -5,6 +5,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; export const REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL = msg("Remove queued message"); @@ -43,7 +44,9 @@ export function resolveThreadQueueRowControls(input: { displayText: isAttachmentOnlyBootstrapPrompt(input.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(input.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(input.text, (reference) => reference.label), + ), ).trim(), isEditing, }; diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 09ee65c32172b..48d62fb4575b7 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -1024,7 +1024,12 @@ const threadShowCommand = Command.make("show", { const messages = yield* Effect.forEach(latest, (item) => readFullText(tools, threadId, item).pipe( Effect.map((text) => ({ - role: item.type === "user_message" ? "user" : "assistant", + role: + item.type === "assistant_message" + ? "assistant" + : item.createdBy === "system" + ? "system" + : "user", runId: item.runId, text, })), diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index a0953eb509e5f..cbe4be1e4b42f 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + MessageId, NodeId, type OrchestratorMcpThreadReadResult, type OrchestrationV2ThreadProjection, @@ -431,6 +432,134 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn }).pipe(Effect.provide(layer), Effect.runPromise); }); +it("readThread does not attribute the /compact T3 Code sends before a stale send to the user", async () => { + const compactRunId = RunId.make("run-mcp-compact-on-return"); + const sendRunId = RunId.make("run-mcp-held-send"); + const compactMessageId = MessageId.make("message-mcp-compact-on-return"); + const sendMessageId = MessageId.make("message-mcp-held-send"); + const projection = { + thread: baseThread({ + threadId: parentThreadId, + title: "Parent", + instanceId: parentInstanceId, + model: "gpt-5.4", + }), + runs: [ + makeRun({ id: compactRunId, ordinal: 1, status: "completed" }), + makeRun({ id: sendRunId, ordinal: 2, status: "completed" }), + ], + visibleTurnItems: [], + providerTurns: [], + runtimeRequests: [], + messages: [ + { + id: compactMessageId, + threadId: parentThreadId, + runId: compactRunId, + role: "user", + text: "/compact", + attachments: [], + createdBy: "user", + creationSource: "web", + idleCompaction: "onReturn", + }, + { + id: sendMessageId, + threadId: parentThreadId, + runId: sendRunId, + role: "user", + text: "use webgpu", + attachments: [], + createdBy: "user", + creationSource: "web", + }, + ], + contextTransfers: [], + subagents: [], + updatedAt: now, + } as unknown as OrchestrationV2ThreadProjection; + const userRow = (position: number, runId: RunId, messageId: MessageId, text: string) => ({ + position, + visibility: "visible", + sourceThreadId: parentThreadId, + sourceItemId: TurnItemId.make(`turn-item-mcp-user-${position}`), + item: { + type: "user_message", + runId, + messageId, + status: "completed", + title: null, + text, + attachments: [], + updatedAt: now, + }, + }); + const rows = [ + userRow(0, compactRunId, compactMessageId, "/compact"), + { + position: 1, + visibility: "visible", + sourceThreadId: parentThreadId, + sourceItemId: TurnItemId.make("turn-item-mcp-compaction"), + item: { + type: "compaction", + runId: compactRunId, + status: "completed", + title: null, + summary: "Context compacted", + updatedAt: now, + }, + }, + userRow(2, sendRunId, sendMessageId, "use webgpu"), + ]; + + const layer = layerOrchestratorService.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getTimelinePage: () => + Effect.succeed({ + items: rows as unknown as OrchestrationV2ThreadProjection["visibleTurnItems"], + totalItems: rows.length, + hasMore: false, + hasEarlier: false, + }), + getThreadRecords: () => Effect.succeed(projection), + getProjectThreadRecords: () => Effect.succeed(projection), + getRunCount: () => Effect.succeed(projection.runs.length), + getThreadShell: () => + Effect.succeed(projection.thread as unknown as OrchestrationV2ThreadShell), + } satisfies Partial), + ServerSettings.layerTest(), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([]), + } satisfies Partial), + Layer.mock(ProjectService.ProjectService)({}), + Layer.mock(SecretRequests.SecretRequests)({}), + Layer.mock(RemoteDelegation.RemoteDelegation)({}), + Layer.mock(ScheduledTaskService.ScheduledTaskService)({ + list: () => Effect.succeed({ tasks: [] }), + } satisfies Partial), + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({ + list: () => Effect.succeed([]), + } satisfies Partial), + NodeCrypto.layer, + ), + ), + ); + + await Effect.gen(function* () { + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + for (const view of ["activity", "messages"] as const) { + const result = yield* service.readThread(makeScope(), { threadId: parentThreadId, view }); + const fromUser = result.items.filter( + (item) => item.type === "user_message" && item.createdBy === "user", + ); + expect(fromUser.map((item) => item.text)).toEqual(["use webgpu"]); + } + }).pipe(Effect.provide(layer), Effect.runPromise); +}); + it("readThread returns the newest items that fit the response budget", async () => { const projection = { thread: baseThread({ diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index ccd41144a5ea8..551a84109cfa2 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -106,6 +106,7 @@ describe("OrchestratorMcpService", () => { threadId: parentThreadId, origin: "app_owned", childThreadId, + title: "Merge", driver: "codex", model: "gpt-5.6-terra", result: "terminal result", @@ -252,6 +253,13 @@ describe("OrchestratorMcpService", () => { const commandIds = yield* Ref.get(acknowledgementCommandIds); assert.equal(commandIds.length, 2); assert.notEqual(commandIds[0], commandIds[1]); + + const missing = yield* service + .taskStatus(scope, NodeId.make("node:mcp-ack-missing")) + .pipe(Effect.flip); + assert.equal(missing.code, "task_not_found"); + assert.include(missing.message, "No delegated task with id node:mcp-ack-missing"); + assert.include(missing.message, `${taskId} (Merge)`); }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies)))); }), ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 4062c509812c4..156555c74d695 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -1,6 +1,7 @@ import { CommandId, type RunId, + idleCompactionOf, isProviderAvailable, MessageId, type ModelSelection, @@ -154,6 +155,7 @@ const TASK_WAKE_EVENTS = [ { thread: "child", eventType: "runtime-request.updated" }, ] as const; const SECRET_REQUEST_POLL_INTERVAL_MS = 500; +const MAX_LISTED_TASKS = 10; const DEFAULT_THREAD_LIST_LIMIT = 10; const DEFAULT_THREAD_READ_LIMIT = 10; const DEFAULT_THREAD_RUN_LIMIT = 10; @@ -1227,7 +1229,8 @@ function timelineItem(input: { ...(input.row.item.type === "subagent" ? { subagentId: input.row.item.subagentId } : {}), runId: input.row.item.runId, messageId, - createdBy: message?.createdBy ?? null, + createdBy: + message === undefined ? null : idleCompactionOf(message) ? "system" : message.createdBy, creationSource: message?.creationSource ?? null, ...(message?.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }), type: input.row.item.type, @@ -1805,6 +1808,33 @@ const make = Effect.gen(function* () { const requestKey = (clientRequestId: string | undefined): Effect.Effect => clientRequestId === undefined ? random.uuidV4() : Effect.succeed(clientRequestId); + const taskNotFound = Effect.fn("OrchestratorMcpService.taskNotFound")(function* ( + scope: McpThreadInvocationScope, + taskId: NodeId, + ): Effect.fn.Return { + const { subagents } = yield* loadThreadRecords(scope.thread.threadId, ["subagents"], { + omitSettledSubagents: true, + }); + const open = subagents.filter( + (task) => + task.origin === "app_owned" && + (task.childThreadId !== null || task.remoteChild !== undefined), + ); + const listed = open + .slice(0, MAX_LISTED_TASKS) + .map((task) => (task.title ? `${task.id} (${task.title})` : task.id)) + .join(", "); + const more = + open.length > MAX_LISTED_TASKS ? `, and ${open.length - MAX_LISTED_TASKS} more` : ""; + return yield* failure( + "task_not_found", + `No delegated task with id ${taskId} exists on thread ${scope.thread.threadId}. ` + + (open.length === 0 + ? "This thread has no open delegated tasks." + : `Open delegated tasks on this thread: ${listed}${more}.`), + ); + }); + const readTask = Effect.fn("OrchestratorMcpService.readTask")(function* ( scope: McpThreadInvocationScope, taskId: NodeId, @@ -1820,10 +1850,7 @@ const make = Effect.gen(function* () { candidate.threadId === scope.thread.threadId, ); if (task === undefined || (task.childThreadId === null && task.remoteChild === undefined)) { - return yield* failure( - "task_not_found", - `Delegated task ${taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, taskId); } if (task.childThreadId === null) { return yield* readRemoteTask(scope, task, waitTimedOut, acknowledgeTerminal); @@ -3006,10 +3033,7 @@ const make = Effect.gen(function* () { task.remoteChild !== undefined, ); if (remoteTask === undefined) { - return yield* failure( - "task_not_found", - `Delegated task ${input.taskId} does not belong to thread ${scope.thread.threadId}.`, - ); + return yield* taskNotFound(scope, input.taskId); } return yield* remoteDelegation.cancel(scope, remoteTask, input); } diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..5cbb4975e5e57 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -1327,6 +1327,16 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); yield* startTurn(1, false); yield* throughPromptSettled; + // Progress keeps a command past the post-settle hold bound, which counts silence only. + for (const minute of [10, 20, 30]) { + yield* TestClock.adjust("10 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "in_progress", + rawOutput: { output: `fetched ${minute} pages` }, + }); + } yield* TestClock.adjust("10 minutes"); yield* send({ sessionUpdate: "tool_call_update", @@ -1349,6 +1359,115 @@ describe("AntigravityAdapterV2 work after the prompt ends", () => { }).pipe(Effect.provide(layerSession)), ); + // A command whose terminal update never arrives would hold the run in Working forever with + // an empty pending list and a finished reply above Stop. + it.effect("settles a silent background command after the post-settle hold timeout", () => + Effect.gen(function* () { + const { command, offers, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + const prompt = yield* throughPromptSettled; + + // A running tool keeps the inactivity watchdog re-armed, so 20 silent minutes do not + // settle this run on their own. + yield* TestClock.adjust("20 minutes"); + yield* TestClock.adjust("11 minutes"); + const run = yield* until((event) => event.type === "turn.terminal"); + const terminal = run.at(-1); + assert.equal( + terminal?.type === "turn.terminal" && terminal.status, + "completed", + "the bounded hold finalizes the turn instead of leaving it running forever", + ); + assert.equal(terminal?.type === "turn.terminal" && terminal.failure, null); + assert.lengthOf(offers, 0, "a silent command produces no wake on its own"); + const commandItem = [...prompt, ...run].findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.nativeItemRef?.nativeId === command.toolCallId, + ); + assert.isTrue( + commandItem?.type === "turn_item.updated" && commandItem.turnItem.status === "completed", + "the silent command is no longer left as live activity on a settled run", + ); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps a silent scheduled wake in its run past the command hold bound", () => + Effect.gen(function* () { + const { usage, offers, send, startTurn, until, throughPromptSettled } = + yield* openSessionWithRunningCommand({}, undefined, undefined, { + initialToolCalls: [ + { + sessionUpdate: "tool_call", + toolCallId: "call_schedule", + kind: "other", + title: "Run schedule", + status: "in_progress", + rawInput: { DurationSeconds: 3600, Prompt: "Continue the task" }, + }, + ], + }); + yield* startTurn(1, false); + yield* throughPromptSettled; + yield* TestClock.adjust("61 minutes"); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "call_schedule", + status: "completed", + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Picked the task back up." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include( + JSON.stringify(run), + "Picked the task back up.", + "the wake reply stays in the run", + ); + assert.lengthOf(offers, 0); + }).pipe(Effect.provide(layerSession)), + ); + + it.effect("keeps an unanswered question open past the command hold bound", () => + Effect.gen(function* () { + const { command, usage, send, startTurn, until, throughPromptSettled, requestPermission } = + yield* openSessionWithRunningCommand({ WaitMsBeforeAsync: 10000 }); + yield* startTurn(1, false); + yield* throughPromptSettled; + const question = yield* requestPermission( + { + sessionId: "mock-session-1", + toolCall: { toolCallId: "interaction_1", kind: "other", title: "Which port?" }, + options: [ + { optionId: "3000", name: "3000", kind: "allow_once" }, + { optionId: "8080", name: "8080", kind: "allow_once" }, + ], + }, + { requestId: "question-1", method: "session/request_permission" }, + ).pipe(Effect.forkScoped({ startImmediately: true })); + yield* TestClock.adjust("31 minutes"); + yield* Fiber.interrupt(question); + yield* send({ + sessionUpdate: "tool_call_update", + ...command, + status: "completed", + rawOutput: { output: "Command exited with code 0.", exit_code: 0 }, + }); + yield* send({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "Here is the chart." }, + }); + yield* send(usage); + yield* TestClock.adjust("3 seconds"); + const run = yield* until((event) => event.type === "turn.terminal"); + assert.include(JSON.stringify(run), "Here is the chart.", "the question kept the run open"); + }).pipe(Effect.provide(layerSession)), + ); + // Command 2 finishes during reply 1; agy dequeues command 2 after reply 1's usage_update and // needs >3 s before streaming reply 2. Wait for reply 2 (bounded by the 2-minute quiet limit), // but still finalize at 3 s when both commands were batched into reply 1. diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 3f629c813b615..c20afa04e31b8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -41,6 +41,7 @@ import { watchAntigravityPromptOutcome } from "../../provider/acp/AntigravityTur import { antigravityApprovalOptions, antigravityToolOutlivesPrompt, + antigravityCommandOutlivesPrompt, antigravitySubagentOutput, classifyAntigravitySubagentToolCall, extractAntigravityUserInputQuestion, @@ -244,6 +245,12 @@ export function makeAntigravityAcpAdapterFlavor( wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true, toolOutlivesPrompt: antigravityToolOutlivesPrompt, + // agy sometimes loses the terminal update or wake for a background command, which would + // hold the turn in Working forever. 30 minutes still leaves long commands room. + postSettleCommandHold: { + timeout: "30 minutes", + isCommand: antigravityCommandOutlivesPrompt, + }, // session/cancel ends the agent's running commands, so only Stop sends it once the prompt // has ended. A message sent while a command runs leaves the command alone. preserveRuntimeOnSettledInterrupt: true, diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index ef4ffcf35c11b..d30748a0df77c 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -12809,6 +12809,28 @@ describe("CodexAdapterV2 post-settle continuation", () => { { operation: "delete", path: "/w/e.ts" }, { operation: "add", path: "/w/a.ts" }, ]); + assert.equal( + fileChanges[0]?.diffStr, + [ + 'diff --git "a//w/c.ts" "b//w/d.ts"', + '--- "a//w/c.ts"', + '+++ "b//w/d.ts"', + "@@", + 'diff --git "a//w/e.ts" "b//w/e.ts"', + '--- "a//w/e.ts"', + "+++ /dev/null", + "@@ -1,1 +0,0 @@", + "-gone", + "\\ No newline at end of file", + 'diff --git "a//w/a.ts" "b//w/a.ts"', + "--- /dev/null", + '+++ "b//w/a.ts"', + "@@ -0,0 +1,1 @@", + "+export {};", + "\\ No newline at end of file", + "", + ].join("\n"), + ); }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index e5dfd83559292..181ed17fd5c16 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -178,6 +178,35 @@ type CodexFileChangeKinds = Readonly< Record >; +// Diff parsers split at Git headers once one exists, so each file of a multi-file patch needs its own. +function codexMultiFilePatch( + changes: ReadonlyArray, +): string { + return changes + .map(({ path, kind, diff }) => { + const oldPath = path; + const newPath = (kind.type === "update" && kind.move_path) || path; + const git = `diff --git ${JSON.stringify(`a/${oldPath}`)} ${JSON.stringify(`b/${newPath}`)}\n`; + if (kind.type === "update" && diff.startsWith("diff --git ")) return diff; + if (kind.type === "update" && diff.startsWith("--- ")) return `${git}${diff}`; + let hunks = diff; + // Codex records added and deleted files as their raw contents. + if (kind.type !== "update") { + const lines = diff.split("\n"); + const hasFinalNewline = diff.endsWith("\n"); + if (hasFinalNewline) lines.pop(); + const added = kind.type === "add"; + const range = `1,${lines.length}`; + hunks = `@@ -${added ? "0,0" : range} +${added ? range : "0,0"} @@\n${lines.map((line) => `${added ? "+" : "-"}${line}`).join("\n")}\n${hasFinalNewline ? "" : "\\ No newline at end of file\n"}`; + } + const before = kind.type === "add" ? "/dev/null" : JSON.stringify(`a/${oldPath}`); + const after = kind.type === "delete" ? "/dev/null" : JSON.stringify(`b/${newPath}`); + return `${git}--- ${before}\n+++ ${after}\n${hunks}`; + }) + .map((section) => (section.endsWith("\n") ? section : `${section}\n`)) + .join(""); +} + function codexFileChangeApprovalPrompt(input: { readonly reason?: string | null; readonly grantRoot?: string | null; @@ -4285,7 +4314,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updatedAt, type: "file_change", fileName: firstChange.path, - diffStr: firstChange.diff, + diffStr: + item.changes.length > 1 ? codexMultiFilePatch(item.changes) : firstChange.diff, changes: item.changes.map((change) => { const movePath = change.kind.type === "update" ? change.kind.move_path : undefined; return movePath diff --git a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts index 796bc854d28d6..a000e05471bc6 100644 --- a/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts +++ b/apps/server/src/provider/acp/AcpJsonRpcConnection.test.ts @@ -1621,6 +1621,26 @@ describe("AcpSessionRuntime", () => { }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + it.effect("fails startup when the agent never answers initialize", () => + Effect.gen(function* () { + const initializeSent = yield* Deferred.make(); + const runtime = yield* AcpSessionRuntime.make({ + ...mockRuntimeOptions, + // A live child that reads stdin and never replies, like one stuck in disk sleep. + spawn: { command: "node", args: ["-e", "process.stdin.resume()"] }, + requestLogger: (event) => + event.method === "initialize" && event.status === "started" + ? Deferred.succeed(initializeSent, undefined) + : Effect.void, + }); + const startup = yield* runtime.start().pipe(Effect.forkChild); + yield* Deferred.await(initializeSent); + yield* TestClock.adjust("30 minutes"); + const exit = yield* Fiber.await(startup); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + it.effect("sends a cancel after the cancel timeout when its prompt never goes out", () => Effect.gen(function* () { const runtime = yield* AcpSessionRuntime.make({ diff --git a/apps/server/src/provider/acp/AntigravityProtocol.ts b/apps/server/src/provider/acp/AntigravityProtocol.ts index c718667dcf42e..2e59a78e376b4 100644 --- a/apps/server/src/provider/acp/AntigravityProtocol.ts +++ b/apps/server/src/provider/acp/AntigravityProtocol.ts @@ -55,6 +55,12 @@ const ANTIGRAVITY_SCHEDULE_TITLES = new Set(["Run schedule", "Running schedule"] */ export function antigravityToolOutlivesPrompt(toolCall: AcpToolCallState): boolean { if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return true; + return antigravityCommandOutlivesPrompt(toolCall); +} + +/** A non-daemon command the agent awaits; unlike a schedule, it reports progress while it runs. */ +export function antigravityCommandOutlivesPrompt(toolCall: AcpToolCallState): boolean { + if (toolCall.title !== undefined && ANTIGRAVITY_SCHEDULE_TITLES.has(toolCall.title)) return false; const input = toolCall.data.rawInput; return toolCall.kind === "execute" && !(Predicate.isObject(input) && input.IsDaemon === true); } diff --git a/apps/server/src/socketHeartbeat.test.ts b/apps/server/src/socketHeartbeat.test.ts new file mode 100644 index 0000000000000..2cb002bbf8862 --- /dev/null +++ b/apps/server/src/socketHeartbeat.test.ts @@ -0,0 +1,39 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Scope from "effect/Scope"; +import * as Socket from "effect/socket/Socket"; +import * as TestClock from "effect/testing/TestClock"; + +import { + SOCKET_HEARTBEAT_FRAME, + SOCKET_HEARTBEAT_INTERVAL, + withSocketHeartbeat, +} from "./socketHeartbeat.ts"; + +describe("withSocketHeartbeat", () => { + it.effect("writes a heartbeat each interval until the writer's scope closes", () => + Effect.gen(function* () { + const written: Array = []; + const socket = withSocketHeartbeat( + Socket.make({ + reader: Effect.never, + writer: Effect.succeed({ + write: (chunk) => Effect.sync(() => void written.push(chunk)), + writeAll: (chunks) => Effect.sync(() => void written.push(...chunks)), + }), + }), + ); + const scope = yield* Scope.make(); + yield* Scope.provide(socket.writer, scope); + + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.deepStrictEqual(written, [SOCKET_HEARTBEAT_FRAME, SOCKET_HEARTBEAT_FRAME]); + + yield* Scope.close(scope, Exit.void); + yield* TestClock.adjust(SOCKET_HEARTBEAT_INTERVAL); + assert.strictEqual(written.length, 2); + }), + ); +}); diff --git a/apps/server/src/socketHeartbeat.ts b/apps/server/src/socketHeartbeat.ts new file mode 100644 index 0000000000000..6ffd9c9cf785c --- /dev/null +++ b/apps/server/src/socketHeartbeat.ts @@ -0,0 +1,27 @@ +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Socket from "effect/socket/Socket"; + +// Reverse proxies close a socket after 60 seconds without upstream bytes +// (nginx proxy_read_timeout, AWS ALB), and a suspended client stops pinging. +export const SOCKET_HEARTBEAT_INTERVAL = Duration.seconds(20); + +// RPC clients count any decoded frame as liveness and ignore unsolicited pongs. +export const SOCKET_HEARTBEAT_FRAME = '{"_tag":"Pong"}'; + +/** Server side: writes a heartbeat frame on an interval for as long as the writer is open. */ +export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket { + return Socket.make({ + reader: socket.reader, + writer: Effect.tap(socket.writer, (writer) => + writer + .write(SOCKET_HEARTBEAT_FRAME) + .pipe( + Effect.delay(SOCKET_HEARTBEAT_INTERVAL), + Effect.forever, + Effect.ignore, + Effect.forkScoped, + ), + ), + }); +} diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index d9a661c7b1237..b3ad640db4c7a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -10325,6 +10325,35 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "publishes a new branch prefixed with another remote's name under its full name", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const origin = yield* makeTmpDir("git-remote-"); + const fork = yield* makeTmpDir("git-fork-"); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(origin, ["init", "--bare"]); + yield* git(fork, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", origin]); + // e.g. the remote T3 adds when checking out a pull request from alice's fork. + yield* git(cwd, ["remote", "add", "alice", fork]); + yield* git(cwd, ["checkout", "-b", "alice/fix"]); + yield* writeTextFile(cwd, "fix.txt", "fix\n"); + yield* git(cwd, ["add", "-A"]); + yield* driver.commit(cwd, "Add fix", ""); + + const pushed = yield* driver.pushCurrentBranch(cwd, null); + + assert.deepInclude(pushed, { status: "pushed", upstreamBranch: "origin/alice/fix" }); + assert.equal( + yield* git(origin, ["--git-dir=.", "rev-parse", "refs/heads/alice/fix"]), + yield* git(cwd, ["rev-parse", "HEAD"]), + ); + }), + ); + it.effect("still pushes a git-mangled tracking alias to its upstream head", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 8f3e3e16ca12b..f863f01bdb40a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2147,14 +2147,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.map(parseRemoteNamesInGitOrder), ); - const resolvePublishBranchName = Effect.fn("resolvePublishBranchName")(function* ( - cwd: string, - branchName: string, - ) { - const remoteNames = yield* listRemoteNames(cwd).pipe(Effect.orElseSucceed(() => [])); - const parsedRemoteRef = parseRemoteRefWithRemoteNames(branchName, remoteNames); - return parsedRemoteRef?.branchName ?? branchName; - }); + // Only the destination remote's prefix is dropped; `alice/fix` pushed to origin keeps its full name. + const resolvePublishBranchName = (branchName: string, remoteName: string) => + parseRemoteRefWithRemoteNames(branchName, [remoteName])?.branchName ?? branchName; const hasAnyRemote = (cwd: string) => resolveRepositoryPaths(cwd).pipe( @@ -3680,7 +3675,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // A gone local upstream still gets the full local name, as below. const branchName = goneUpstream?.branchName ?? - (configuredRemoteName === "." ? branch : yield* resolvePublishBranchName(cwd, branch)); + (configuredRemoteName === "." ? branch : resolvePublishBranchName(branch, remoteName)); return { remoteName, branchName, @@ -3731,10 +3726,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( Effect.orElseSucceed(() => null), ); - const branchName = yield* resolvePublishBranchName(cwd, branch); + const remoteName = publishRemoteName ?? upstream.remoteName; return { - remoteName: publishRemoteName ?? upstream.remoteName, - branchName, + remoteName, + branchName: resolvePublishBranchName(branch, remoteName), publishes: true, upstream, pushRemote: null, @@ -3774,7 +3769,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const requestedRemoteName = options?.remoteName?.trim() || null; if (requestedRemoteName) { - const publishBranch = yield* resolvePublishBranchName(cwd, branch); + const publishBranch = resolvePublishBranchName(branch, requestedRemoteName); yield* executeGitWithStableDiagnostics( "GitVcsDriver.pushCurrentBranch.pushWithRequestedRemote", cwd, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index ddd07fcfad656..d1db4372ab871 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -201,6 +201,7 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { makePrepareTerminalLaunch } from "./workspace/restoreMissingWorktree.ts"; import { terminalOutputStream, withOutputWindow } from "./terminal/OutputProtocol.ts"; +import { withSocketHeartbeat } from "./socketHeartbeat.ts"; import * as ServerBrowser from "./preview/ServerBrowser.ts"; import * as DeviceService from "./device/DeviceService.ts"; import { remoteSshDeviceHosts } from "./device/localSshDeviceHost.ts"; @@ -3826,20 +3827,21 @@ export const layer = Layer.unwrap( ), ), ); - const framedRpcWebSocketHttpEffect = url.value.searchParams.has( - SOCKET_FRAME_PARTS_QUERY_PARAM, - ) - ? rpcWebSocketHttpEffect.pipe( - Effect.provideService( - HttpServerRequest.HttpServerRequest, - // The RPC server upgrades the request itself, so its socket is - // wrapped through the request it reads. - Object.create(request, { - upgrade: { value: Effect.map(request.upgrade, splitLargeSocketFrames) }, - }), - ), - ) - : rpcWebSocketHttpEffect; + const splitFrames = url.value.searchParams.has(SOCKET_FRAME_PARTS_QUERY_PARAM); + const framedRpcWebSocketHttpEffect = rpcWebSocketHttpEffect.pipe( + Effect.provideService( + HttpServerRequest.HttpServerRequest, + // The RPC server upgrades the request itself, so its socket is + // wrapped through the request it reads. + Object.create(request, { + upgrade: { + value: Effect.map(request.upgrade, (socket) => + withSocketHeartbeat(splitFrames ? splitLargeSocketFrames(socket) : socket), + ), + }, + }), + ), + ); return yield* Effect.acquireUseRelease( sessions.markConnected(session.sessionId), () => diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d17af4f620755..be1360704063f 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3940,9 +3940,15 @@ export default function ChatView(props: ChatViewProps) { onExpandImage={onExpandTimelineImageStable} onFileOpen={openFileAttachmentStable} editingQueuedAttachments={queuedRunEdit.editingAttachments} + removedEditingQueuedAttachments={ + queuedRunEdit.removedEditingAttachments + } onRemoveEditingQueuedAttachment={ queuedRunEdit.removeEditingAttachment } + onRestoreEditingQueuedAttachment={ + queuedRunEdit.restoreEditingAttachment + } /> )} diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 402156b001286..485df8083a215 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -112,6 +112,9 @@ import { import { COMPOSER_UNDO_GROUP_DELAY, type ComposerChangeKind, + type ComposerHistoryRevision, + composerHistoryRevisionOf, + createComposerHistoryRevisionPlugin, groupUndoByChangeKind, markAsClipboardEdit, markAsCompositionReplace, @@ -170,6 +173,8 @@ export interface ComposerPromptEditorHandle { isCaretOnVisualEdge: (edge: "start" | "end") => boolean; } +export type ComposerPromptHistoryChange = ComposerHistoryRevision; + export interface ComposerPromptEditorProps { draftKey?: string; value: string; @@ -203,7 +208,11 @@ export interface ComposerPromptEditorProps { contextIds: string[], /** False when only the caret or selection moved. */ textChanged: boolean, + /** ProseMirror history revision and direction for this change. */ + history?: ComposerPromptHistoryChange, ) => void; + /** Fired after editor mount or controlled document rewrites that bypass onChange. */ + onControlledHistoryChange?: ((history: ComposerPromptHistoryChange) => void) | undefined; onVisibleSelectionChange?: () => void; onCommandKeyDown?: (key: string, event: KeyboardEvent, isTaskItem?: boolean) => boolean; onPageScrollKeyDown?: (key: "PageUp" | "PageDown") => void; @@ -797,11 +806,17 @@ type TiptapEditor = NonNullable>; const SILENT_SELECTION_META = "composerSilentSelection"; +const CARRIED_HISTORY_DIRECTION_META = "composerCarriedHistoryDirection"; + function replaceSkillChips( editor: TiptapEditor, replacements: ReturnType, + carriedHistoryDirection?: ComposerPromptHistoryChange["direction"], ): void { const transaction = editor.state.tr.setMeta("addToHistory", false); + if (carriedHistoryDirection) { + transaction.setMeta(CARRIED_HISTORY_DIRECTION_META, carriedHistoryDirection); + } for (const { from, to, node } of replacements) transaction.replaceWith(from, to, node); editor.view.dispatch(transaction); } @@ -849,6 +864,9 @@ const ComposerUndoGroupingExtension = Extension.create< addStorage() { return { previous: null }; }, + addProseMirrorPlugins() { + return [createComposerHistoryRevisionPlugin()]; + }, dispatchTransaction({ transaction, next }) { this.storage.previous = groupUndoByChangeKind(transaction, this.storage.previous); next(transaction); @@ -994,6 +1012,7 @@ function ComposerPromptEditorTiptapInner( placeholderClassName, placeholderSuffix, onChange, + onControlledHistoryChange, onVisibleSelectionChange, onCommandKeyDown, onPageScrollKeyDown, @@ -1020,6 +1039,7 @@ function ComposerPromptEditorTiptapInner( // The editor config is built once, so its handlers reach the current callbacks through here. const readCallbacks = useStableCallback(() => ({ onChange, + onControlledHistoryChange, onVisibleSelectionChange, onCommandKeyDown, isPathQueryActive, @@ -1120,13 +1140,23 @@ function ComposerPromptEditorTiptapInner( [updated.state.selection.$from.nodeBefore, updated.state.selection.$from.nodeAfter].some( (node) => node?.isInline && node.isAtom && !node.isText && node.type.name !== "hardBreak", ); + const textChanged = previousSnapshot.value !== nextValue; + const rawHistory = composerHistoryRevisionOf(updated.state); + const carriedDirection = transaction.getMeta(CARRIED_HISTORY_DIRECTION_META) as + | ComposerPromptHistoryChange["direction"] + | undefined; + const history = + carriedDirection && rawHistory.direction === null + ? { ...rawHistory, direction: carriedDirection } + : rawHistory; readCallbacks().onChange( nextValue, nextCursor, nextExpandedCursor, suppressTrigger, contextIds, - previousSnapshot.value !== nextValue, + textChanged, + history, ); }; @@ -1556,7 +1586,7 @@ function ComposerPromptEditorTiptapInner( isKnownModel, ).filter(({ node }) => node.isText); if (stale.length > 0) { - replaceSkillChips(updated, stale); + replaceSkillChips(updated, stale, composerHistoryRevisionOf(updated.state).direction); return; } } @@ -1704,6 +1734,9 @@ function ComposerPromptEditorTiptapInner( emitUpdate: false, }, ); + readCallbacks().onControlledHistoryChange?.(composerHistoryRevisionOf(editor.state)); + } else if (initialSelection) { + readCallbacks().onControlledHistoryChange?.(composerHistoryRevisionOf(editor.state)); } selectMarkdownOffset(editor, value, normalizedExpandedCursor); const map = serializeEditorDoc(editor.state.doc); @@ -1744,6 +1777,7 @@ function ComposerPromptEditorTiptapInner( expandEditorCursor, initialExpandedCursor, literalText, + readCallbacks, richText, skillLabelFor, isKnownModel, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6fb651c3471f6..64c6af44120ce 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -23,6 +23,7 @@ import { import type { KeybindingCommand, AssistantCitation, + ComposerContextId, ResponseContextRecord, ChatAttachment as ContractChatAttachment, ChatFileAttachment, @@ -120,7 +121,10 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { + type QueuedAttachmentContextBinding, reconcileAttachmentContextReferences, + recordChiplessQueuedImageRemoval, + recordQueuedImageHistoryRevision, useRetainedContextPayloads, } from "./composerContextUndo"; import { ComposerBanner } from "./ComposerBanner"; @@ -133,7 +137,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, - isImageOnlyClipboardHtml, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -165,6 +170,7 @@ import { import { type ComposerCitationCommentRequest, type ComposerPromptEditorHandle, + type ComposerPromptHistoryChange, ComposerPromptEditorTiptap as ComposerPromptEditor, } from "../ComposerPromptEditorTiptap"; import { @@ -286,6 +292,7 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; import { cancelHeldComposerSend, countPreparingComposerImages, @@ -456,8 +463,11 @@ export interface ChatComposerProps { editingQueuedAttachments: ReadonlyArray<{ readonly attachment: ContractChatAttachment; readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; }> | null; + removedEditingQueuedAttachments?: ReadonlyArray | undefined; onRemoveEditingQueuedAttachment: (attachmentId: string) => void; + onRestoreEditingQueuedAttachment?: ((attachment: ContractChatAttachment) => void) | undefined; onCompactContext: () => void; onSend: ( @@ -598,7 +608,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onExpandImage, onFileOpen, editingQueuedAttachments, + removedEditingQueuedAttachments, onRemoveEditingQueuedAttachment, + onRestoreEditingQueuedAttachment, } = props; const { activePendingProgress: incomingPendingProgress, @@ -656,6 +668,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion.id, ) : null; + const queuedEditOwnsComposer = + questionAttachmentTarget === null && pendingUserInputs.length === 0; + const activeEditingQueuedAttachments = queuedEditOwnsComposer ? editingQueuedAttachments : null; + const activeRemovedEditingQueuedAttachments = queuedEditOwnsComposer + ? removedEditingQueuedAttachments + : undefined; const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget; const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget); const questionTakesSnapShots = @@ -756,33 +774,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, expandImage: (imageId: string) => { - const preview = buildExpandedImagePreview( - composerImages, - imageId, - copyComposerSnapshotStable, - ); + const preview = + buildExpandedImagePreview(composerImages, imageId, copyComposerSnapshotStable) ?? + buildExpandedImagePreview( + (activeEditingQueuedAttachments ?? []).flatMap(({ attachment, url }) => + isQueuedImageAttachment(attachment) && url ? [{ ...attachment, previewUrl: url }] : [], + ), + imageId, + ); if (preview) onExpandImage(preview); }, - openFile: setPreviewFileId, + openFile: (fileId: string) => { + if (composerFiles.some((file) => file.id === fileId)) { + setPreviewFileId(fileId); + return; + } + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (queuedFile && isQueuedFileAttachment(queuedFile)) onFileOpen(queuedFile); + }, openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path), expandVideo: (fileId: string) => { const file = composerFiles.find((candidate) => candidate.id === fileId); - if (!file || !isVideoAttachment(file)) return; - const localPreview = buildExpandedImagePreview([file], file.id); - if (localPreview) { - onExpandImage(localPreview); + if (file && isVideoAttachment(file)) { + const localPreview = buildExpandedImagePreview([file], file.id); + if (localPreview) { + onExpandImage(localPreview); + return; + } + if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + return; + } + const persistedPreview = buildAttachmentVideoPreview(environmentId, { + type: "file", + id: file.uploadedAttachmentId, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + }); + if (persistedPreview) onExpandImage(persistedPreview); return; } - if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (!queuedFile || !isQueuedFileAttachment(queuedFile) || !isVideoAttachment(queuedFile)) { return; } - const persistedPreview = buildAttachmentVideoPreview(environmentId, { - type: "file", - id: file.uploadedAttachmentId, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - }); + const persistedPreview = buildAttachmentVideoPreview(environmentId, queuedFile); if (persistedPreview) onExpandImage(persistedPreview); }, openPullRequest: (event: React.MouseEvent, url: string) => { @@ -797,6 +837,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentContexts: composerEnvironmentContexts, images: composerImages, files: composerFiles, + existingAttachments: activeEditingQueuedAttachments ?? undefined, + environmentId, uploadsByImageId, }); const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length; @@ -1392,12 +1434,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [ - record.kind === "image" && attachment.type === "image" && attachment.source - ? { ...record, source: attachment.source } - : record, - ]; + return [record]; }), + ...(activeEditingQueuedAttachments ?? []).flatMap(({ attachment, contextIds }) => { + if (!isQueuedImageAttachment(attachment) && !isQueuedFileAttachment(attachment)) return []; + return (contextIds ?? []) + .filter((contextId) => wanted.has(contextId)) + .map((contextId) => + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + ); + }), ]; if (records.length === 0) return null; const fragment = encodeComposerContextFragment({ @@ -1422,6 +1472,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const copyComposerSnapshotStable = useStableCallback(copyComposerSnapshot); const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment); + const retainedContextPayloads = useRetainedContextPayloads(composerDraftTargetKey); const { loadThreadTranscript, countReservedAttachments, @@ -1446,6 +1497,43 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments: activeRemovedEditingQueuedAttachments, + onRestoreQueuedAttachment: (attachment) => { + if (!queuedEditOwnsComposer) return; + if (isQueuedImageAttachment(attachment)) { + retainedContextPayloads.queuedImageHistory.pendingRestoredIds.add(attachment.id); + } + onRestoreEditingQueuedAttachment?.(attachment); + }, + }); + + const onControlledHistoryChangeStable = useStableCallback( + (history: ComposerPromptHistoryChange) => { + if (!queuedEditOwnsComposer) return; + recordQueuedImageHistoryRevision( + retainedContextPayloads.queuedImageHistory, + history, + activeRemovedEditingQueuedAttachments ?? [], + ); + }, + ); + + const onRemoveEditingQueuedAttachmentStable = useStableCallback((attachmentId: string) => { + const entry = activeEditingQueuedAttachments?.find( + (item) => item.attachment.id === attachmentId, + ); + if ( + entry && + isQueuedImageAttachment(entry.attachment) && + entry.contextIds && + entry.contextIds.length > 0 + ) { + const referenced = new Set(collectInlineContextIds(promptRef.current)); + if (!entry.contextIds.some((contextId) => referenced.has(contextId))) { + recordChiplessQueuedImageRemoval(retainedContextPayloads.queuedImageHistory, attachmentId); + } + } + onRemoveEditingQueuedAttachment(attachmentId); }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers @@ -1642,8 +1730,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) syncComposerDraftPersistedAttachments, ]); - const retainedContextPayloads = useRetainedContextPayloads(composerDraftTargetKey); - const onPromptChange = ( nextPrompt: string, nextCursor: number, @@ -1651,6 +1737,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], textChanged: boolean, + history?: ComposerPromptHistoryChange, ) => { refreshWorkspaceSnapshotOnTyping(); const trigger = cursorAdjacentToMention @@ -1761,6 +1848,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const attachmentChanges = reconcileAttachmentContextReferences({ referencedContextIds: referenced, files: composerFiles, + queuedAttachments: (activeEditingQueuedAttachments ?? []).map( + ({ attachment, contextIds }) => ({ + attachment, + contextIds: contextIds ?? [], + }), + ), + removedQueuedAttachments: activeRemovedEditingQueuedAttachments ?? [], + history, + textChanged, images: composerImages, previewAnnotations: composerPreviewAnnotations, retained: retainedContextPayloads, @@ -1780,6 +1876,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (attachmentChanges.filesToRestore.length > 0) { addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); } + for (const attachmentId of attachmentChanges.queuedAttachmentIdsToRemove) { + onRemoveEditingQueuedAttachment(attachmentId); + } + for (const attachment of attachmentChanges.queuedAttachmentsToRestore) { + onRestoreEditingQueuedAttachment?.(attachment); + } setComposerCursor(nextCursor); updateTrigger(trigger); }; @@ -2947,18 +3049,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const pastedContext = !isLiteralPendingAnswer && (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; + const canAttachFiles = !pastedContext && activeThreadId !== null && files.length > 0; + const htmlImageContent = + canAttachFiles && plainText.length > 0 + ? clipboardHtmlImageContent(event.clipboardData.getData("text/html")) + : "none"; if ( folders.length > 0 || - (!pastedContext && - activeThreadId && - files.length > 0 && + (canAttachFiles && shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment, - htmlIsOnlyImage: - plainText.length > 0 && - isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + htmlIsOnlyImage: htmlImageContent === "only-image", })) ) { event.preventDefault(); @@ -2971,6 +3074,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } if (pastedContext) return; + const imagesBesideText = imagesToAttachBesidePastedText({ + files, + plainText, + bypassAutoAttachment, + htmlHasImageAndText: htmlImageContent === "image-and-text", + }); + if (imagesBesideText.length > 0) void addComposerAttachments(imagesBesideText); if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } @@ -3805,12 +3915,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) )} {!isComposerCollapsedMobile && - pendingUserInputs.length === 0 && - editingQueuedAttachments !== null && - editingQueuedAttachments.length > 0 && ( + activeEditingQueuedAttachments !== null && + activeEditingQueuedAttachments.length > 0 && ( )} @@ -3833,7 +3942,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ) : null} reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + ), ) .trim() .replace(/\s+/g, " "); diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index d8318b7279e7d..20ea71f88adcd 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -10,6 +10,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { parseGoalCommand, type ChatAttachment as ContractChatAttachment, @@ -272,7 +273,9 @@ export function QueuedRunsControl({ const previewText = isAttachmentOnlyBootstrapPrompt(item.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(item.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(item.text, (reference) => reference.label), + ), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; // The server decides on the agent's text, and a goal command can stop the turn. diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index f842566d7cd60..ac43d667d80ca 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -13,6 +13,7 @@ import { composerFileAttachmentMimeType, fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, + imagesToAttachBesidePastedText, normalizeComposerImageFileMimeType, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; @@ -141,6 +142,12 @@ describe("composer attachment files", () => { expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( true, ); + // A QQ or WeChat message has its text beside an in the HTML: the image attaches too. + const message = { files: [image], plainText: "Look at this", htmlHasImageAndText: true }; + expect(shouldHandleComposerAttachmentPaste(message)).toBe(false); + expect(imagesToAttachBesidePastedText(message)).toEqual([image]); + expect(imagesToAttachBesidePastedText({ ...message, htmlHasImageAndText: false })).toEqual([]); + expect(imagesToAttachBesidePastedText({ ...message, bypassAutoAttachment: true })).toEqual([]); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 191c5841185ff..538d2dfd67304 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -247,11 +247,33 @@ function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { .every((line) => names.has(line)); } -/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ -export function isImageOnlyClipboardHtml(html: string): boolean { - if (html.length === 0) return false; +/** + * A browser's Copy Image puts only an in text/html; a chat message (QQ, WeChat) puts its text + * beside the ; rich text sources (Word, Pages) put only the text there. + */ +export function clipboardHtmlImageContent(html: string): "only-image" | "image-and-text" | "none" { + if (html.length === 0) return "none"; const body = new DOMParser().parseFromString(html, "text/html").body; - return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; + if (body.querySelector("img") === null) return "none"; + return (body.textContent ?? "").trim().length === 0 ? "only-image" : "image-and-text"; +} + +function isPastedImageFile(file: File): boolean { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; +} + +/** The images of a message copied with its text: they attach while the text pastes as text. */ +export function imagesToAttachBesidePastedText(input: { + readonly files: ReadonlyArray; + readonly plainText: string; + readonly bypassAutoAttachment?: boolean; + readonly htmlHasImageAndText: boolean; +}): File[] { + if (input.bypassAutoAttachment || input.plainText.length === 0 || !input.htmlHasImageAndText) { + return []; + } + return input.files.filter(isPastedImageFile); } export function shouldHandleComposerAttachmentPaste(input: { @@ -269,10 +291,7 @@ export function shouldHandleComposerAttachmentPaste(input: { ) { return true; } - const hasImage = input.files.some((file) => { - const classification = classifyComposerAttachmentFile(file); - return classification === "image" || classification === "unsupported-image"; - }); + const hasImage = input.files.some(isPastedImageFile); if (input.plainText.length === 0) { return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } diff --git a/apps/web/src/components/chat/composerContextUndo.test.ts b/apps/web/src/components/chat/composerContextUndo.test.ts index a763b47a0d6d7..7daeee345c026 100644 --- a/apps/web/src/components/chat/composerContextUndo.test.ts +++ b/apps/web/src/components/chat/composerContextUndo.test.ts @@ -1,10 +1,32 @@ -import type { PreviewAnnotationPayload } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + type ChatFileAttachment, + type ChatImageAttachment, + type PreviewAnnotationPayload, +} from "@t3tools/contracts"; +import { getSchema } from "@tiptap/core"; +import { history, redo, undo } from "@tiptap/pm/history"; +import { EditorState, TextSelection, type Transaction } from "@tiptap/pm/state"; +import StarterKit from "@tiptap/starter-kit"; import { describe, expect, it } from "vite-plus/test"; +import { + COMPOSER_UNDO_GROUP_DELAY, + type ComposerChangeKind, + composerHistoryRevisionOf, + createComposerHistoryRevisionPlugin, + groupUndoByChangeKind, + markAsClipboardEdit, +} from "../../composer-undo-grouping"; import type { ComposerImageAttachment } from "../../composerDraftStore"; import { buildMessageContext, previewAnnotationContextId } from "../../lib/composerContextRecords"; import { + createQueuedImageHistoryState, + type QueuedAttachmentContextBinding, reconcileAttachmentContextReferences, + recordChiplessQueuedImageRemoval, + recordQueuedImageHistoryRevision, type RetainedAttachmentContextPayloads, } from "./composerContextUndo"; @@ -37,7 +59,166 @@ const annotation = { } satisfies PreviewAnnotationPayload; function retention(): RetainedAttachmentContextPayloads { - return { files: new Map(), previewAnnotations: new Map() }; + return { + files: new Map(), + previewAnnotations: new Map(), + queuedImageHistory: createQueuedImageHistoryState(), + }; +} + +const schema = getSchema([StarterKit]); + +function createQueuedEditHarness(input: { + initialText: string; + attachments: ReadonlyArray; +}) { + let clock = 0; + let previous: ComposerChangeKind | null = null; + const retained = retention(); + const original = input.attachments; + let live = [...original]; + let removed: QueuedAttachmentContextBinding[] = []; + + const docFor = (text: string) => + schema.node("doc", null, [schema.node("paragraph", null, text ? [schema.text(text)] : [])]); + + let state = EditorState.create({ + schema, + doc: docFor(input.initialText), + plugins: [ + history({ newGroupDelay: COMPOSER_UNDO_GROUP_DELAY }), + createComposerHistoryRevisionPlugin(), + ], + }); + + const referencedIn = (text: string): Set => { + const ids = new Set(); + for (const entry of original) { + for (const contextId of entry.contextIds) { + if (text.includes(`<<${contextId}>>`)) ids.add(contextId); + } + } + return ids; + }; + + const applyAttachmentChanges = ( + result: ReturnType, + ) => { + for (const attachmentId of result.queuedAttachmentIdsToRemove) { + const removedEntry = live.find((entry) => entry.attachment.id === attachmentId); + if (!removedEntry) continue; + live = live.filter((entry) => entry.attachment.id !== attachmentId); + removed.push(removedEntry); + } + for (const restoredAttachment of result.queuedAttachmentsToRestore) { + const restoredEntry = removed.find((entry) => entry.attachment.id === restoredAttachment.id); + if (!restoredEntry) continue; + removed = removed.filter((entry) => entry.attachment.id !== restoredAttachment.id); + live = original.filter( + (entry) => + live.some((item) => item.attachment.id === entry.attachment.id) || + entry.attachment.id === restoredAttachment.id, + ); + } + }; + + const dispatchUser = (tr: Transaction) => { + clock += 80; + const prevText = state.doc.textContent; + tr.setTime(clock); + previous = groupUndoByChangeKind(tr, previous); + state = state.apply(tr); + const nextText = state.doc.textContent; + const result = reconcileAttachmentContextReferences({ + referencedContextIds: referencedIn(nextText), + files: [], + queuedAttachments: live, + removedQueuedAttachments: removed, + history: composerHistoryRevisionOf(state), + textChanged: prevText !== nextText, + images: [], + previewAnnotations: [], + retained, + }); + applyAttachmentChanges(result); + }; + + const dispatchControlledRewrite = (nextText: string) => { + clock += 80; + const tr = state.tr.replaceWith( + 0, + state.doc.content.size, + schema.node("paragraph", null, nextText ? [schema.text(nextText)] : []), + ); + tr.setTime(clock); + previous = groupUndoByChangeKind(tr, previous); + state = state.apply(tr); + state = state.apply(state.tr.setSelection(TextSelection.atEnd(state.doc))); + recordQueuedImageHistoryRevision( + retained.queuedImageHistory, + composerHistoryRevisionOf(state), + removed, + ); + }; + + recordQueuedImageHistoryRevision( + retained.queuedImageHistory, + composerHistoryRevisionOf(state), + removed, + ); + state = state.apply(state.tr.setSelection(TextSelection.atEnd(state.doc))); + + return { + text: () => state.doc.textContent, + liveIds: () => live.map((entry) => entry.attachment.id), + clickRowRemove: (attachmentId: string) => { + const entry = live.find((item) => item.attachment.id === attachmentId); + if (!entry) return; + const currentText = state.doc.textContent; + let nextText = currentText; + for (const contextId of entry.contextIds) { + nextText = nextText.replaceAll(`<<${contextId}>>`, ""); + } + live = live.filter((item) => item.attachment.id !== attachmentId); + removed = [...removed, entry]; + if (nextText !== currentText) { + dispatchControlledRewrite(nextText); + } else { + recordChiplessQueuedImageRemoval(retained.queuedImageHistory, attachmentId); + } + }, + pasteQueuedImageChip: (attachmentId: string, contextId: ComposerContextId) => { + const restoredEntry = removed.find((item) => item.attachment.id === attachmentId); + if (restoredEntry) { + retained.queuedImageHistory.pendingRestoredIds.add(attachmentId); + } + dispatchUser(markAsClipboardEdit(state.tr.insertText(`<<${contextId}>>`), "paste")); + if (restoredEntry) { + removed = removed.filter((item) => item.attachment.id !== attachmentId); + live = original.filter( + (entry) => + live.some((item) => item.attachment.id === entry.attachment.id) || + entry.attachment.id === attachmentId, + ); + } + }, + deleteChipText: (contextId: ComposerContextId) => { + const token = `<<${contextId}>>`; + const idx = state.doc.textContent.indexOf(token); + if (idx === -1) throw new Error(`Chip ${token} not found in "${state.doc.textContent}"`); + dispatchUser(state.tr.delete(idx + 1, idx + 1 + token.length)); + }, + typeGroup: (s: string) => { + clock += COMPOSER_UNDO_GROUP_DELAY + 100; + dispatchUser(state.tr.insertText(s, state.doc.content.size - 1)); + }, + undo: () => { + expect(undo(state, dispatchUser)).toBe(true); + }, + redo: () => { + expect(redo(state, dispatchUser)).toBe(true); + }, + }; } describe("reconcileAttachmentContextReferences", () => { @@ -88,4 +269,114 @@ describe("reconcileAttachmentContextReferences", () => { }), ]); }); + + it("reconciles queued files and images across keyboard deletion, row removal, paste, undo, redo, branching, and history trimming", () => { + const chipFile: ChatFileAttachment = { + type: "file", + id: ChatAttachmentId.make("server-file-1"), + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + const plainFile: ChatFileAttachment = { + type: "file", + id: ChatAttachmentId.make("server-file-2"), + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; + const imageA: ChatImageAttachment = { + type: "image", + id: ChatAttachmentId.make("server-image-a"), + name: "a.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const imageB: ChatImageAttachment = { + type: "image", + id: ChatAttachmentId.make("server-image-b"), + name: "b.png", + mimeType: "image/png", + sizeBytes: 68, + }; + const chipContextId = ComposerContextId.make("file_local-1"); + const imageAContextId = ComposerContextId.make("image_local-a"); + const imageBContextId = ComposerContextId.make("image_local-b"); + + // Deleting a chip-backed file removes it; unreferenced files and backspaced image chips stay attached. + const basic = createQueuedEditHarness({ + initialText: `Check <<${chipContextId}>> <<${imageAContextId}>>`, + attachments: [ + { attachment: chipFile, contextIds: [chipContextId] }, + { attachment: plainFile, contextIds: [] }, + { attachment: imageA, contextIds: [imageAContextId] }, + ], + }); + basic.deleteChipText(chipContextId); + expect(basic.liveIds()).toEqual([plainFile.id, imageA.id]); + basic.undo(); + expect(basic.liveIds()).toEqual([chipFile.id, plainFile.id, imageA.id]); + basic.redo(); + expect(basic.liveIds()).toEqual([plainFile.id, imageA.id]); + + // × -> Paste -> Backspace -> Undo x3 -> Redo x3 keeps image A attached after the final redo. + basic.clickRowRemove(imageA.id); + expect(basic.liveIds()).toEqual([plainFile.id]); + basic.pasteQueuedImageChip(imageA.id, imageAContextId); + expect(basic.liveIds()).toEqual([plainFile.id, imageA.id]); + basic.deleteChipText(imageAContextId); + expect(basic.liveIds()).toEqual([plainFile.id, imageA.id]); + basic.undo(); + expect(basic.liveIds()).toEqual([plainFile.id, imageA.id]); + basic.undo(); + expect(basic.liveIds()).toEqual([plainFile.id]); + basic.undo(); + expect(basic.liveIds()).toEqual([plainFile.id, imageA.id]); + basic.redo(); + expect(basic.liveIds()).toEqual([plainFile.id]); + basic.redo(); + expect(basic.liveIds()).toEqual([plainFile.id, imageA.id]); + basic.redo(); + expect(basic.liveIds()).toEqual([plainFile.id, imageA.id]); + + // Branching via a controlled row removal: × on A -> Undo -> × on B -> Backspace A -> Undo -> Redo + // must keep A attached and B removed. + const branched = createQueuedEditHarness({ + initialText: `Compare <<${imageAContextId}>> <<${imageBContextId}>>`, + attachments: [ + { attachment: imageA, contextIds: [imageAContextId] }, + { attachment: imageB, contextIds: [imageBContextId] }, + ], + }); + branched.clickRowRemove(imageA.id); + expect(branched.liveIds()).toEqual([imageB.id]); + branched.undo(); + expect(branched.liveIds()).toEqual([imageA.id, imageB.id]); + branched.clickRowRemove(imageB.id); + expect(branched.liveIds()).toEqual([imageA.id]); + branched.deleteChipText(imageAContextId); + expect(branched.liveIds()).toEqual([imageA.id]); + branched.undo(); + expect(branched.liveIds()).toEqual([imageA.id]); + branched.redo(); + expect(branched.liveIds()).toEqual([imageA.id]); + + // Overflow trimming: after 119 undo groups, × (depth 120) -> Paste (trims 121 -> 100) -> Undo + // must still remove image A. + const trimmed = createQueuedEditHarness({ + initialText: `Start <<${imageAContextId}>>`, + attachments: [{ attachment: imageA, contextIds: [imageAContextId] }], + }); + for (let i = 0; i < 119; i += 1) { + trimmed.typeGroup("x"); + } + trimmed.clickRowRemove(imageA.id); + expect(trimmed.liveIds()).toEqual([]); + trimmed.pasteQueuedImageChip(imageA.id, imageAContextId); + expect(trimmed.liveIds()).toEqual([imageA.id]); + trimmed.undo(); + expect(trimmed.liveIds()).toEqual([]); + trimmed.redo(); + expect(trimmed.liveIds()).toEqual([imageA.id]); + }); }); diff --git a/apps/web/src/components/chat/composerContextUndo.ts b/apps/web/src/components/chat/composerContextUndo.ts index fd2a0cde59341..cdd99556e302b 100644 --- a/apps/web/src/components/chat/composerContextUndo.ts +++ b/apps/web/src/components/chat/composerContextUndo.ts @@ -1,23 +1,79 @@ import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, PreviewAnnotationPayload, ThreadContextRecord, } from "@t3tools/contracts"; import { useEffect, useState } from "react"; +import type { ComposerHistoryRevision } from "../../composer-undo-grouping"; import type { ComposerFileAttachment, ComposerImageAttachment } from "../../composerDraftStore"; import { fileContextReference, previewAnnotationContextId } from "../../lib/composerContextRecords"; import type { TerminalContextDraft } from "../../lib/terminalContext"; import type { ReviewCommentContext } from "../../reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; interface RetainedPreviewAnnotation { annotation: PreviewAnnotationPayload; image: ComposerImageAttachment | undefined; } +export interface QueuedAttachmentContextBinding { + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; +} + +export interface QueuedImageHistoryState { + currentRevision: number; + readonly removedIdsByRevision: Map>; + readonly pendingRestoredIds: Set; +} + export interface RetainedAttachmentContextPayloads { files: Map; previewAnnotations: Map; + queuedImageHistory: QueuedImageHistoryState; +} + +export function createQueuedImageHistoryState(): QueuedImageHistoryState { + return { + currentRevision: 0, + removedIdsByRevision: new Map(), + pendingRestoredIds: new Set(), + }; +} + +export function recordQueuedImageHistoryRevision( + state: QueuedImageHistoryState, + history: ComposerHistoryRevision, + removedQueuedAttachments: ReadonlyArray, +): void { + const active = new Set(history.activeRevisions); + for (const revision of state.removedIdsByRevision.keys()) { + if (!active.has(revision)) state.removedIdsByRevision.delete(revision); + } + const removedImageIds = new Set(); + for (const entry of removedQueuedAttachments) { + if (isQueuedImageAttachment(entry.attachment)) { + removedImageIds.add(entry.attachment.id); + } + } + for (const restoredId of state.pendingRestoredIds) { + removedImageIds.delete(restoredId); + } + state.pendingRestoredIds.clear(); + state.currentRevision = history.revision; + state.removedIdsByRevision.set(history.revision, removedImageIds); +} + +export function recordChiplessQueuedImageRemoval( + state: QueuedImageHistoryState, + attachmentId: string, +): void { + const next = new Set(state.removedIdsByRevision.get(state.currentRevision)); + next.add(attachmentId); + state.removedIdsByRevision.set(state.currentRevision, next); } export interface RetainedContextPayloads extends RetainedAttachmentContextPayloads { @@ -35,6 +91,7 @@ function createRetainedContextPayloads(): RetainedContextPayloads { environments: new Map(), files: new Map(), previewAnnotations: new Map(), + queuedImageHistory: createQueuedImageHistoryState(), }; } @@ -51,7 +108,14 @@ export function useRetainedContextPayloads(draftTargetKey: string): RetainedCont // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- clears the retained payload maps when the draft target changes or the composer unmounts useEffect( () => () => { - for (const payloads of Object.values(retained)) payloads.clear(); + retained.terminals.clear(); + retained.reviewComments.clear(); + retained.threads.clear(); + retained.environments.clear(); + retained.files.clear(); + retained.previewAnnotations.clear(); + retained.queuedImageHistory.removedIdsByRevision.clear(); + retained.queuedImageHistory.pendingRestoredIds.clear(); }, [retained], ); @@ -61,12 +125,18 @@ export function useRetainedContextPayloads(draftTargetKey: string): RetainedCont export function reconcileAttachmentContextReferences(input: { referencedContextIds: ReadonlySet; files: ReadonlyArray; + queuedAttachments?: ReadonlyArray; + removedQueuedAttachments?: ReadonlyArray; + history?: ComposerHistoryRevision | undefined; + textChanged?: boolean; images: ReadonlyArray; previewAnnotations: ReadonlyArray; retained: RetainedAttachmentContextPayloads; }): { filesToRemove: string[]; filesToRestore: ComposerFileAttachment[]; + queuedAttachmentIdsToRemove: string[]; + queuedAttachmentsToRestore: ChatAttachment[]; annotationIdsToRemove: string[]; annotationsToRestore: RetainedPreviewAnnotation[]; } { @@ -86,6 +156,57 @@ export function reconcileAttachmentContextReferences(input: { return file ? [file] : []; }); + const history = input.history; + const removedQueuedAttachments = input.removedQueuedAttachments ?? []; + if (history) { + if (history.direction === null && input.textChanged) { + recordQueuedImageHistoryRevision( + input.retained.queuedImageHistory, + history, + removedQueuedAttachments, + ); + } else if (history.direction !== null) { + input.retained.queuedImageHistory.currentRevision = history.revision; + } + } + + const removedAtRevision = + history?.direction != null + ? input.retained.queuedImageHistory.removedIdsByRevision.get(history.revision) + : undefined; + + const liveQueuedAttachments = input.queuedAttachments ?? []; + const liveQueuedAttachmentIds = new Set( + liveQueuedAttachments.map((entry) => entry.attachment.id), + ); + const queuedAttachmentIdsToRemove: string[] = []; + for (const entry of liveQueuedAttachments) { + if (entry.contextIds.length === 0) continue; + if (entry.contextIds.some((contextId) => input.referencedContextIds.has(contextId))) continue; + if (isQueuedFileAttachment(entry.attachment)) { + queuedAttachmentIdsToRemove.push(entry.attachment.id); + } else if ( + isQueuedImageAttachment(entry.attachment) && + removedAtRevision?.has(entry.attachment.id) + ) { + queuedAttachmentIdsToRemove.push(entry.attachment.id); + } + } + const restoredQueuedAttachmentIds = new Set(); + const queuedAttachmentsToRestore: ChatAttachment[] = []; + for (const entry of removedQueuedAttachments) { + if ( + entry.contextIds.length === 0 || + liveQueuedAttachmentIds.has(entry.attachment.id) || + restoredQueuedAttachmentIds.has(entry.attachment.id) + ) { + continue; + } + if (!entry.contextIds.some((contextId) => input.referencedContextIds.has(contextId))) continue; + restoredQueuedAttachmentIds.add(entry.attachment.id); + queuedAttachmentsToRestore.push(entry.attachment); + } + const imagesById = new Map(input.images.map((image) => [image.id, image])); const liveAnnotationContextIds = new Set( input.previewAnnotations.map((annotation) => previewAnnotationContextId(annotation.id)), @@ -106,5 +227,12 @@ export function reconcileAttachmentContextReferences(input: { return retained ? [retained] : []; }); - return { filesToRemove, filesToRestore, annotationIdsToRemove, annotationsToRestore }; + return { + filesToRemove, + filesToRestore, + queuedAttachmentIdsToRemove, + queuedAttachmentsToRestore, + annotationIdsToRemove, + annotationsToRestore, + }; } diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts index 49d22add3a239..29a36aa7911e5 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.test.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts @@ -1,4 +1,11 @@ -import { EnvironmentId, MessageId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + EnvironmentId, + MessageId, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { beforeEach, describe, expect, it } from "vite-plus/test"; @@ -10,7 +17,13 @@ import { } from "../../composerDraftStore"; import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; import { environmentContextRecord, responseContextRecord } from "../../lib/composerContextRecords"; -import { prepareQueuedEditAttachments, recoverQueuedMessageEdit } from "./queuedMessageEdit"; +import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { + attachmentContextIdsForRecord, + matchRestorableQueuedAttachment, + prepareQueuedEditAttachments, + recoverQueuedMessageEdit, +} from "./queuedMessageEdit"; const environmentId = EnvironmentId.make("remote-environment"); const threadTarget = scopeThreadRef(environmentId, ThreadId.make("thread:edit")); @@ -193,6 +206,143 @@ describe("queued message file edits", () => { expect(store.getComposerDraft(threadTarget)).toBeNull(); }); + it("strips existing queued attachment references when recovering an edit into the thread draft", () => { + const store = useComposerDraftStore.getState(); + const chip = formatInlineContextReference({ + kind: "image", + contextId: "image_queued-1", + label: "image.png", + }); + store.setPrompt(editTarget, `Check ${chip} closely`); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `Check ${chip}`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("kept"); + expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Check closely"); + expect(store.getComposerDraft(editTarget)).toBeNull(); + + store.clearComposerContent(threadTarget); + store.setPrompt(editTarget, chip); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `${chip} note`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("discarded"); + expect(store.getComposerDraft(threadTarget)).toBeNull(); + }); + + it("maps existing queued attachments to matching wire context ids", () => { + const imageId = ChatAttachmentId.make("server-image-1"); + const fileId = ChatAttachmentId.make("server-file-1"); + const otherFileId = ChatAttachmentId.make("server-file-2"); + const imageContextId = ComposerContextId.make("image_local-1"); + const fileContextId = ComposerContextId.make("file_local-1"); + const imageAttachment = { + type: "image" as const, + id: imageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const fileAttachment = { + type: "file" as const, + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + const unreferencedFile = { + type: "file" as const, + id: otherFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; + const context = { + version: 1 as const, + records: [ + { + version: 1 as const, + kind: "image" as const, + contextId: imageContextId, + label: "image.png", + attachmentId: imageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }, + { + version: 1 as const, + kind: "file" as const, + contextId: fileContextId, + label: "notes.txt", + attachmentId: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + ], + }; + + expect(attachmentContextIdsForRecord(context, imageAttachment)).toEqual([imageContextId]); + expect(attachmentContextIdsForRecord(context, fileAttachment)).toEqual([fileContextId]); + expect(attachmentContextIdsForRecord(context, unreferencedFile)).toEqual([]); + }); + + it("matches a removed queued attachment for same-environment paste while rejecting other environments or payloads", () => { + const fileId = ChatAttachmentId.make("server-file-1"); + const contextId = ComposerContextId.make("file_local-1"); + const removedAttachment = { + type: "file" as const, + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + const record = { + version: 1 as const, + kind: "file" as const, + contextId, + label: "notes.txt", + attachmentId: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toEqual({ attachment: removedAttachment, contextId }); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: EnvironmentId.make("other-environment"), + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record: { ...record, attachmentId: ChatAttachmentId.make("different-file") }, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + }); + it("does not overwrite a separate draft when the queued run leaves", () => { const store = useComposerDraftStore.getState(); store.setPrompt(threadTarget, "Separate draft"); diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts index e6b59e3a96b83..ca58777dcb44a 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.ts @@ -1,5 +1,14 @@ import { resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit"; -import type { ChatAttachment, ResponseContextRecord } from "@t3tools/contracts"; +import type { + ChatAttachment, + ChatFileAttachment, + ChatImageAttachment, + ComposerContextId, + ComposerContextRecord, + EnvironmentId, + OrchestrationMessageContext, + ResponseContextRecord, +} from "@t3tools/contracts"; import * as Equal from "effect/Equal"; import { composerDraftHasUserContent, @@ -11,6 +20,68 @@ import { import { msg } from "gt-react"; import { m } from "../../i18n/messages"; import { releaseDraftAttachments } from "../../lib/attachmentUploadQueue"; +import { + attachmentContextRecord, + isSameComposerContextPayload, +} from "../../lib/composerContextRecords"; +import { removeInlineContextReference } from "../../lib/composerContextReferences"; + +export function isQueuedImageAttachment( + attachment: ChatAttachment, +): attachment is ChatImageAttachment { + return attachment.type === "image"; +} + +export function isQueuedFileAttachment( + attachment: ChatAttachment, +): attachment is ChatFileAttachment { + return attachment.type === "file"; +} + +export function attachmentContextIdsForRecord( + context: OrchestrationMessageContext | undefined, + attachment: Pick, +): ComposerContextId[] { + return (context?.records ?? []).flatMap((record) => + record.kind === attachment.type && + "attachmentId" in record && + record.attachmentId === attachment.id + ? [record.contextId] + : [], + ); +} + +export function matchRestorableQueuedAttachment(input: { + readonly environmentId: EnvironmentId; + readonly sourceEnvironmentId: EnvironmentId | null; + readonly record: Extract; + readonly removedQueuedAttachments: ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; + }>; +}): { readonly attachment: ChatAttachment; readonly contextId: ComposerContextId } | null { + if (input.sourceEnvironmentId !== input.environmentId) return null; + const match = input.removedQueuedAttachments.find( + ({ attachment, contextIds }) => + (isQueuedImageAttachment(attachment) || isQueuedFileAttachment(attachment)) && + attachment.type === input.record.kind && + contextIds.some((contextId) => + isSameComposerContextPayload( + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + input.record, + ), + ), + ); + if (!match || match.contextIds.length === 0) return null; + const contextId = + match.contextIds.find((candidate) => candidate === input.record.contextId) ?? + match.contextIds[0]!; + return { attachment: match.attachment, contextId }; +} /** Staged attachments upload as soon as they are added, so a dropped edit must release them. */ export function discardQueuedEditDraft(target: ComposerThreadTarget): void { @@ -31,9 +102,21 @@ export function recoverQueuedMessageEdit(input: { readonly originalText: string; readonly originalReplyTo: ResponseContextRecord | null; readonly removedExistingAttachment?: boolean; + readonly existingAttachmentContextIds?: ReadonlyArray; }): "kept" | "discarded" | "clean" { const store = useComposerDraftStore.getState(); const draft = store.getComposerDraft(input.editTarget); + const strippedPrompt = + draft && (input.existingAttachmentContextIds?.length ?? 0) > 0 + ? input.existingAttachmentContextIds!.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + draft.prompt, + ) + : draft?.prompt; + const recoveredDraft = + draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt + ? { ...draft, prompt: strippedPrompt } + : draft; const recovery = resolveQueuedEditExit({ editChanged: input.removedExistingAttachment === true || @@ -42,10 +125,13 @@ export function recoverQueuedMessageEdit(input: { (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0)), // A cleared edit has nothing to put back, so it can only be discarded. threadDraftEmpty: - composerDraftHasUserContent(draft) && + composerDraftHasUserContent(recoveredDraft) && !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget)), }); if (recovery === "kept") { + if (draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt) { + store.setPrompt(input.editTarget, strippedPrompt); + } store.moveComposerContent(input.editTarget, input.threadTarget); store.clearComposerContent(input.editTarget); } else { diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 61d0abd7319a6..458f39dc98638 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -10,6 +10,7 @@ import * as Schema from "effect/Schema"; import type { RefObject } from "react"; import type { ChatComposerProps } from "./ChatComposer"; import { + type ChatAttachment, type ComposerContextClipboardFragment, type ComposerContextRecord, type EnvironmentId, @@ -59,6 +60,8 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; import { useStableCallback } from "../../hooks/useStableCallback"; import { countPreparingComposerImages } from "./preparingComposerImages"; +import type { QueuedAttachmentContextBinding } from "./composerContextUndo"; +import { matchRestorableQueuedAttachment } from "./queuedMessageEdit"; const isUnreachable = Schema.is( Schema.Union([ConnectionTransientError, ConnectionBlockedError, EnvironmentRpcUnavailableError]), @@ -94,6 +97,8 @@ export function useComposerContextImport(input: { readonly promptRef: RefObject; readonly pendingThreadImportsRef: RefObject>; readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; + readonly removedQueuedAttachments?: ReadonlyArray | undefined; + readonly onRestoreQueuedAttachment?: ((attachment: ChatAttachment) => void) | undefined; }) { const { environmentId, @@ -112,6 +117,8 @@ export function useComposerContextImport(input: { promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments, + onRestoreQueuedAttachment, } = input; const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); @@ -433,6 +440,19 @@ export function useComposerContextImport(input: { case "image": case "file": { if (skippedDependentAttachmentIds.has(record.contextId)) break; + if (questionAttachmentTarget === null && !conflicts) { + const restored = matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId, + record, + removedQueuedAttachments: removedQueuedAttachments ?? [], + }); + if (restored) { + onRestoreQueuedAttachment?.(restored.attachment); + rewritten.set(record.contextId, restored.contextId); + break; + } + } if (sourceEnvironmentId === null && !conflicts) { rewritten.set(record.contextId, record.contextId); break; diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index a88da51cce16e..5ad406da5ef91 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -2,6 +2,7 @@ import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { EnvironmentId, ChatAttachmentId, + ComposerContextId, MessageId, RunId, ThreadId, @@ -363,22 +364,83 @@ describe("useQueuedRunEdit", () => { expect(draft?.environmentContexts).toEqual([machine]); }); - it("saves only the thread mentions still in the edited message", async () => { + it("saves only the thread mentions and attachments still in the edited message", async () => { const { hook } = setup(); mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); const kept = threadContextRecord(THREAD_B, "Kept"); const removed = threadContextRecord(THREAD_A, "Removed"); + const removedImageId = ChatAttachmentId.make("server-image-removed"); + const keptFileId = ChatAttachmentId.make("server-file-kept"); + const removedImageContextId = ComposerContextId.make("image_local-removed"); + const keptFileContextId = ComposerContextId.make("file_local-kept"); + const removedImage = { + type: "image" as const, + id: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFile = { + type: "file" as const, + id: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; + const removedImageRecord = { + version: 1 as const, + kind: "image" as const, + contextId: removedImageContextId, + label: "image.png", + attachmentId: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFileRecord = { + version: 1 as const, + kind: "file" as const, + contextId: keptFileContextId, + label: "legacy.pdf", + attachmentId: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; const messageId = MessageId.make("message-1"); - const text = [kept, removed] - .map((record) => formatInlineContextReference(threadContextReference(record))) - .join(" and "); - const messages = [{ id: messageId, text, context: { version: 1, records: [kept, removed] } }]; + const text = [ + formatInlineContextReference(threadContextReference(kept)), + formatInlineContextReference(threadContextReference(removed)), + formatInlineContextReference({ + kind: "image", + contextId: removedImageContextId, + label: "image.png", + }), + ].join(" and "); + const messages = [ + { + id: messageId, + text, + context: { version: 1, records: [kept, removed, removedImageRecord, keptFileRecord] }, + }, + ]; await using _screen = await render(view(THREAD_A, "queued", hook, messages)); - await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] })); + await act(() => + requireHook(hook).beginEdit({ + runId: RUN, + messageId, + text, + attachments: [removedImage, keptFile], + }), + ); const target = requireHook(hook).draftTarget; - await act(() => useComposerDraftStore.getState().setThreadContexts(target, [kept])); + await act(() => { + useComposerDraftStore.getState().setThreadContexts(target, [kept]); + requireHook(hook).removeEditingAttachment(removedImageId); + }); const draft = useComposerDraftStore.getState().getComposerDraft(target); + expect(draft?.prompt).not.toContain(removedImageContextId); await requireHook(hook).saveEdit( { ...savedContent(draft?.prompt ?? ""), threadContexts: draft?.threadContexts ?? [] }, () => {}, @@ -387,7 +449,11 @@ describe("useQueuedRunEdit", () => { expect(mocks.editQueuedRun).toHaveBeenCalledWith( expect.objectContaining({ input: expect.objectContaining({ - edit: expect.objectContaining({ context: { version: 1, records: [kept] } }), + text: draft?.prompt, + edit: expect.objectContaining({ + attachments: [keptFile], + context: { version: 1, records: [keptFileRecord, kept] }, + }), }), }), ); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index 77989f8aebc0d..89f2be2acfbf8 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -69,6 +69,7 @@ import type { ChatComposerHandle } from "./ChatComposer"; import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; import { composerDraftContentChanged } from "./composerSend.logic"; import { + attachmentContextIdsForRecord, discardQueuedEditDraft, prepareQueuedEditAttachments, recoverQueuedMessageEdit, @@ -80,10 +81,9 @@ interface EditingQueuedRun { readonly runId: RunId; readonly messageId: MessageId; readonly originalText: string; + readonly originalAttachments: ReadonlyArray; readonly existingAttachments: ReadonlyArray; readonly context?: OrchestrationMessageContext | undefined; - /** Removing a server attachment changes the message even when the draft looks untouched. */ - readonly removedExistingAttachment?: true; } // Keyed by the route thread, so an edit survives navigating away and back. @@ -238,13 +238,34 @@ export function useQueuedRunEdit(input: { const urlByAttachmentId = new Map( imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]), ); + const originalReferencedContextIds = + editing === null ? null : new Set(collectInlineContextIds(editing.originalText)); + const attachmentContextIds = (attachment: ChatAttachment) => + editing === null + ? [] + : attachmentContextIdsForRecord(editing.context, attachment).filter((contextId) => + originalReferencedContextIds!.has(contextId), + ); const editingAttachments = editing === null ? null : editing.existingAttachments.map((attachment) => ({ attachment, url: urlByAttachmentId.get(attachment.id) ?? null, + contextIds: attachmentContextIds(attachment), })); + const existingAttachmentIds = new Set( + (editing?.existingAttachments ?? []).map((attachment) => attachment.id), + ); + const removedEditingAttachments = + editing === null + ? [] + : editing.originalAttachments + .filter((attachment) => !existingAttachmentIds.has(attachment.id)) + .map((attachment) => ({ + attachment, + contextIds: attachmentContextIds(attachment), + })); const focusComposerSoon = () => { window.requestAnimationFrame(() => composerRef.current?.focusAtEnd()); @@ -290,6 +311,7 @@ export function useQueuedRunEdit(input: { runId: request.runId, messageId: request.messageId, originalText: text, + originalAttachments: request.attachments, existingAttachments: request.attachments, context, }, @@ -313,7 +335,13 @@ export function useQueuedRunEdit(input: { threadTarget: threadDraftTarget, originalText: edit.originalText, originalReplyTo: reply ?? null, - removedExistingAttachment: edit.removedExistingAttachment === true, + removedExistingAttachment: + edit.existingAttachments.length < edit.originalAttachments.length, + existingAttachmentContextIds: (edit.context?.records ?? []).flatMap((record) => + (record.kind === "image" || record.kind === "file") && "attachmentId" in record + ? [record.contextId] + : [], + ), }); if (recovery === "clean") return; const title = appAtomRegistry.get( @@ -345,13 +373,52 @@ export function useQueuedRunEdit(input: { focusComposerSoon(); }); const removeEditingAttachment = useStableCallback((attachmentId: string) => { + const contextIds = + editing === null + ? [] + : (() => { + const removed = editing.existingAttachments.find( + (attachment) => attachment.id === attachmentId, + ); + return removed ? attachmentContextIdsForRecord(editing.context, removed) : []; + })(); queuedRunEdits.update(editKey, (current) => ({ ...current, - removedExistingAttachment: true, existingAttachments: current.existingAttachments.filter( (attachment) => attachment.id !== attachmentId, ), })); + if (editing !== null && contextIds.length > 0) { + const target = queuedRunEditDraftId(routeThreadRef, editing.runId); + const store = useComposerDraftStore.getState(); + const currentPrompt = store.getComposerDraft(target)?.prompt ?? ""; + const nextPrompt = contextIds.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + currentPrompt, + ); + if (nextPrompt !== currentPrompt) store.setPrompt(target, nextPrompt); + } + }); + const restoreEditingAttachment = useStableCallback((attachment: ChatAttachment) => { + queuedRunEdits.update(editKey, (current) => { + if (current.existingAttachments.some((entry) => entry.id === attachment.id)) { + return current; + } + const restoredIds = new Set([ + ...current.existingAttachments.map((entry) => entry.id), + attachment.id, + ]); + const existingAttachments = current.originalAttachments.filter((entry) => + restoredIds.has(entry.id), + ); + return { + ...current, + existingAttachments: + existingAttachments.length > current.existingAttachments.length + ? existingAttachments + : [...current.existingAttachments, attachment], + }; + }); }); // The same move as the queued row's "Send now" while a turn runs. @@ -478,9 +545,11 @@ export function useQueuedRunEdit(input: { isSaving, draftTarget, editingAttachments, + removedEditingAttachments, beginEdit, cancelEdit, removeEditingAttachment, + restoreEditingAttachment, saveEdit, }; } diff --git a/apps/web/src/components/composerContextPresentation.test.ts b/apps/web/src/components/composerContextPresentation.test.ts index 77b0a5fb7815e..641e190ef86a3 100644 --- a/apps/web/src/components/composerContextPresentation.test.ts +++ b/apps/web/src/components/composerContextPresentation.test.ts @@ -1,8 +1,16 @@ -import { ThreadId } from "@t3tools/contracts"; +import { ChatAttachmentId, ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { buildMessageContext } from "~/lib/composerContextRecords"; -import { composerContextRecordsFromDraft } from "./composerContextPresentation"; +import { composerFileNeedsReattach } from "~/composerDraftStore"; +import { + attachmentContextRecord, + buildMessageContext, + isSameComposerContextPayload, +} from "~/lib/composerContextRecords"; +import { + composerContextRecordsFromDraft, + uploadedContextRecordFromDraft, +} from "./composerContextPresentation"; describe("composerContextRecordsFromDraft", () => { it("resolves each wire reference to its own backing draft even when producer ids collide", () => { @@ -53,4 +61,88 @@ describe("composerContextRecordsFromDraft", () => { expect(draftRecords.get(record.contextId)?.kind).toBe(record.kind); } }); + + it("resolves existing queued attachments under their original wire context ids", () => { + const environmentId = EnvironmentId.make("env-1"); + const imageContextId = ComposerContextId.make("image_local-shot"); + const fileContextId = ComposerContextId.make("file_local-notes"); + const imageId = ChatAttachmentId.make("server-shot"); + const fileId = ChatAttachmentId.make("server-notes"); + const source = { + kind: "snap-shot" as const, + capturedAt: "2026-11-22T14:00:00.000Z", + appName: "Safari", + windowTitle: "Example", + }; + const imageAttachment = { + type: "image" as const, + id: imageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + source, + }; + const draftRecords = composerContextRecordsFromDraft({ + terminalContexts: [], + environmentId, + existingAttachments: [ + { + attachment: imageAttachment, + url: "http://127.0.0.1/assets/server-shot", + contextIds: [imageContextId], + }, + { + attachment: { + type: "file", + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + url: null, + contextIds: [fileContextId], + }, + ], + }); + + const imageEntry = draftRecords.get(imageContextId); + expect(imageEntry).toMatchObject({ + kind: "image", + record: { + id: imageId, + name: "image.png", + previewUrl: "http://127.0.0.1/assets/server-shot", + source, + }, + }); + const uploadedImageRecord = uploadedContextRecordFromDraft(imageEntry!); + expect(uploadedImageRecord).toMatchObject({ + kind: "image", + contextId: imageContextId, + attachmentId: imageId, + source, + }); + expect( + isSameComposerContextPayload( + uploadedImageRecord!, + attachmentContextRecord({ + attachment: imageAttachment, + attachmentId: imageId, + contextId: imageContextId, + }), + ), + ).toBe(true); + + const fileEntry = draftRecords.get(fileContextId); + expect(fileEntry?.kind).toBe("file"); + if (fileEntry?.kind === "file") { + expect(composerFileNeedsReattach(fileEntry.record)).toBe(false); + expect(fileEntry.record.uploadEnvironmentId).toBe(environmentId); + } + expect(uploadedContextRecordFromDraft(fileEntry!)).toMatchObject({ + kind: "file", + contextId: fileContextId, + attachmentId: fileId, + }); + }); }); diff --git a/apps/web/src/components/composerContextPresentation.tsx b/apps/web/src/components/composerContextPresentation.tsx index ab7ce9b40186b..0fb3f31e5413e 100644 --- a/apps/web/src/components/composerContextPresentation.tsx +++ b/apps/web/src/components/composerContextPresentation.tsx @@ -2,7 +2,10 @@ import ChatMarkdown from "./ChatMarkdown"; import { isSvgAttachment } from "@t3tools/shared/image"; import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview"; import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, + EnvironmentId, PreviewAnnotationPayload, ThreadContextRecord, } from "@t3tools/contracts"; @@ -40,6 +43,7 @@ import { } from "~/lib/composerContextRecords"; import type { TerminalContextDraft } from "~/lib/terminalContext"; import type { ReviewCommentContext } from "~/reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./chat/queuedMessageEdit"; import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts"; import { EnvironmentContextChip } from "./EnvironmentContextChip"; import { ThreadContextChip } from "./ThreadContextChip"; @@ -60,6 +64,11 @@ import { UnresolvedChip, } from "./contextChipParts"; +export interface ComposerImageContextAttachment extends Omit { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; +} + export type ComposerDraftContextRecord = | { kind: "terminal"; record: TerminalContextDraft } | { kind: "review-comment"; record: ReviewCommentContext } @@ -68,8 +77,18 @@ export type ComposerDraftContextRecord = record: PreviewAnnotationPayload; screenshot?: ComposerImageAttachment | undefined; } - | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined } - | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined } + | { + kind: "image"; + record: ComposerImageContextAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } + | { + kind: "file"; + record: ComposerFileAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } | { kind: "thread"; record: ThreadContextRecord } | { kind: "environment"; record: EnvironmentContextRecord }; @@ -84,7 +103,7 @@ export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new M export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) { if (entry.kind !== "image" && entry.kind !== "file") return null; - return uploadedAttachmentContextRecord(entry.record, entry.upload); + return uploadedAttachmentContextRecord(entry.record, entry.upload, entry.contextId); } export const ComposerContextRecordsContext = createContext( @@ -99,9 +118,44 @@ export function composerContextRecordsFromDraft(input: { environmentContexts?: ReadonlyArray; images?: ReadonlyArray; files?: ReadonlyArray; + existingAttachments?: + | ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; + }> + | undefined; + environmentId?: EnvironmentId | undefined; uploadsByImageId?: Readonly>; }): ComposerDraftContextRecords { const records = new Map(); + for (const entry of input.existingAttachments ?? []) { + for (const contextId of entry.contextIds ?? []) { + if (isQueuedImageAttachment(entry.attachment)) { + records.set(contextId, { + kind: "image", + contextId, + record: { + ...entry.attachment, + previewUrl: entry.url ?? "", + file: null, + uploadedAttachmentId: entry.attachment.id, + }, + }); + } else if (isQueuedFileAttachment(entry.attachment)) { + records.set(contextId, { + kind: "file", + contextId, + record: { + ...entry.attachment, + file: null, + uploadedAttachmentId: entry.attachment.id, + ...(input.environmentId ? { uploadEnvironmentId: input.environmentId } : {}), + }, + }); + } + } + } for (const record of input.images ?? []) { records.set(imageContextReference(record).contextId, { kind: "image", @@ -183,7 +237,7 @@ function useUploadStatusSuffix( } function attachmentTooltip( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: Pick, upload: AttachmentUploadState | undefined, resolve: MessageResolver, ): string { @@ -193,7 +247,7 @@ function attachmentTooltip( } function ImageContextChip(props: { - record: ComposerImageAttachment; + record: ComposerImageContextAttachment; upload: AttachmentUploadState | undefined; }) { const actions = use(ComposerContextActionsContext); diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 4cb082a1f7ddd..e0b0d92a764ac 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -3,6 +3,7 @@ import type { ContextMenuSource } from "@t3tools/contracts"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { T, useGT } from "gt-react"; import { SquarePenIcon, XIcon } from "lucide-react"; import { @@ -85,7 +86,9 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const gt = useGT(); const promptPreview = assistantCitationsToPlainText( - replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + ), ) .trim() .split("\n", 1)[0] ?? ""; diff --git a/apps/web/src/composer-undo-grouping.ts b/apps/web/src/composer-undo-grouping.ts index 708b4f41fe52a..ba5aaa4cb7e89 100644 --- a/apps/web/src/composer-undo-grouping.ts +++ b/apps/web/src/composer-undo-grouping.ts @@ -1,5 +1,5 @@ -import { closeHistory, isHistoryTransaction } from "@tiptap/pm/history"; -import type { Transaction } from "@tiptap/pm/state"; +import { closeHistory, isHistoryTransaction, redoDepth, undoDepth } from "@tiptap/pm/history"; +import { type EditorState, Plugin, PluginKey, type Transaction } from "@tiptap/pm/state"; import { ReplaceStep } from "@tiptap/pm/transform"; // Whole-draft rewrites make all edits adjacent; explicit boundaries keep change kinds separate. @@ -7,6 +7,122 @@ export const COMPOSER_UNDO_GROUP_DELAY = 1000; export type ComposerChangeKind = "insert" | "delete" | "other"; +export interface ComposerHistoryRevision { + readonly revision: number; + readonly activeRevisions: ReadonlyArray; + readonly direction: "undo" | "redo" | null; +} + +interface ComposerHistoryRevisionState { + readonly current: number; + readonly nextId: number; + readonly undo: ReadonlyArray; + readonly redo: ReadonlyArray; + readonly direction: "undo" | "redo" | null; +} + +const composerHistoryRevisionPluginKey = new PluginKey( + "composerHistoryRevision", +); + +/** + * Mirrors ProseMirror's undo/redo event stacks with monotonic revision IDs so + * external state stays accurate across controlled rewrites and history overflow trimming. + * Register after the ProseMirror history plugin. + */ +export function createComposerHistoryRevisionPlugin(): Plugin { + return new Plugin({ + key: composerHistoryRevisionPluginKey, + state: { + init(): ComposerHistoryRevisionState { + return { current: 0, nextId: 1, undo: [], redo: [], direction: null }; + }, + apply(tr, prev, oldState, newState): ComposerHistoryRevisionState { + const prevUndoDepth = Number(undoDepth(oldState)); + const prevRedoDepth = Number(redoDepth(oldState)); + const nextUndoDepth = Number(undoDepth(newState)); + const nextRedoDepth = Number(redoDepth(newState)); + + if (isHistoryTransaction(tr)) { + if (nextUndoDepth < prevUndoDepth) { + const landed = prev.undo.at(-1) ?? prev.current; + const nextRedo = [...prev.redo, prev.current]; + return { + current: landed, + nextId: prev.nextId, + undo: prev.undo.slice(0, -1), + redo: + nextRedo.length > nextRedoDepth + ? nextRedo.slice(nextRedo.length - nextRedoDepth) + : nextRedo, + direction: "undo", + }; + } + if (nextRedoDepth < prevRedoDepth) { + const landed = prev.redo.at(-1) ?? prev.current; + const nextUndo = [...prev.undo, prev.current]; + return { + current: landed, + nextId: prev.nextId, + undo: + nextUndo.length > nextUndoDepth + ? nextUndo.slice(nextUndo.length - nextUndoDepth) + : nextUndo, + redo: prev.redo.slice(0, -1), + direction: "redo", + }; + } + return { ...prev, direction: null }; + } + + const appended = tr.getMeta("appendedTransaction") as Transaction | undefined; + if ( + tr.steps.length === 0 || + tr.getMeta("addToHistory") === false || + appended?.getMeta("addToHistory") === false || + (appended && isHistoryTransaction(appended)) + ) { + return { ...prev, direction: null }; + } + + if (nextUndoDepth !== prevUndoDepth) { + const nextUndo = [...prev.undo, prev.current]; + return { + current: prev.nextId, + nextId: prev.nextId + 1, + undo: + nextUndo.length > nextUndoDepth + ? nextUndo.slice(nextUndo.length - nextUndoDepth) + : nextUndo, + redo: [], + direction: null, + }; + } + + return { + current: prev.current, + nextId: prev.nextId, + undo: prev.undo, + redo: [], + direction: null, + }; + }, + }, + }); +} + +export function composerHistoryRevisionOf(state: EditorState): ComposerHistoryRevision { + const revisionState = composerHistoryRevisionPluginKey.getState(state); + if (!revisionState) { + return { revision: 0, activeRevisions: [0], direction: null }; + } + return { + revision: revisionState.current, + activeRevisions: [...revisionState.undo, revisionState.current, ...revisionState.redo], + direction: revisionState.direction, + }; +} + const CLIPBOARD_EDIT_META = "composerClipboardEdit"; const COMPOSITION_REPLACE_META = "composerCompositionReplace"; diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts index 31b7239719f1a..6f1c9d3bb8227 100644 --- a/apps/web/src/lib/composerContextRecords.ts +++ b/apps/web/src/lib/composerContextRecords.ts @@ -9,6 +9,8 @@ import { COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, } from "@t3tools/contracts"; import type { + ChatFileAttachment, + ChatImageAttachment, ComposerContextId, ComposerContextRecord, EnvironmentContextRecord, @@ -488,39 +490,59 @@ export function fileContextReference(file: ComposerFileAttachment): ComposerCont }; } +export type ComposerContextAttachment = + | ComposerImageAttachment + | ComposerFileAttachment + | (Omit & { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; + }) + | ChatImageAttachment + | ChatFileAttachment; + export interface BoundComposerAttachment { - attachment: ComposerImageAttachment | ComposerFileAttachment; + attachment: ComposerContextAttachment; attachmentId: string; + contextId?: ComposerContextId | undefined; } /** Returns null until the attachment has a server id. */ export function uploadedAttachmentContextRecord( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: ComposerContextAttachment, upload: AttachmentUploadState | undefined, + contextId?: ComposerContextId, ): ImageContextRecord | FileContextRecord | null { const attachmentId = - attachment.type === "file" && attachment.uploadedAttachmentId !== undefined + "uploadedAttachmentId" in attachment && attachment.uploadedAttachmentId !== undefined ? attachment.uploadedAttachmentId : upload?.status === "ready" ? upload.attachmentId : undefined; - return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId }); + return attachmentId === undefined + ? null + : attachmentContextRecord({ attachment, attachmentId, contextId }); } export function attachmentContextRecord( bound: BoundComposerAttachment, ): ImageContextRecord | FileContextRecord { - const { attachment, attachmentId } = bound; + const { attachment, attachmentId, contextId } = bound; const base = { version: 1 as const, - contextId: toKindScopedComposerContextId(attachment.type, attachment.id), + contextId: contextId ?? toKindScopedComposerContextId(attachment.type, attachment.id), label: sanitizeComposerContextLabel(attachment.name, attachment.type), attachmentId, name: attachment.name, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, }; - return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" }; + return attachment.type === "image" + ? { + ...base, + kind: "image", + ...(attachment.source !== undefined ? { source: attachment.source } : {}), + } + : { ...base, kind: "file" }; } export function buildMessageContext(input: { diff --git a/packages/client-runtime/src/operations/threadTitle.ts b/packages/client-runtime/src/operations/threadTitle.ts index 0f57de34036a5..bb1fcd7648dbf 100644 --- a/packages/client-runtime/src/operations/threadTitle.ts +++ b/packages/client-runtime/src/operations/threadTitle.ts @@ -3,6 +3,7 @@ import type { MFunctionType } from "gt-i18n/types"; import type { ChatAttachment } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { truncate } from "@t3tools/shared/String"; import { collectComposerModelMentions } from "../composerModelMentions.ts"; @@ -45,7 +46,7 @@ export function threadTitleTextFromPrompt( return reference.label; }); return ( - normalizeTitleSeed(modelMentionsAsSlugs(prose)) || + normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) || (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "") ); } diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 2c488b6bdd83c..b08eef243fc3e 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -85,6 +85,8 @@ export type AcpSessionRuntimeEvent = }; const defaultSessionLoadTimeout = Duration.seconds(90); +// A live child that never answers the handshake would otherwise hold the start open forever. +const startupRequestTimeout = Duration.seconds(90); const defaultSessionLoadReplayIdleGap = Duration.seconds(2); const defaultCancelTimeout = Duration.seconds(15); const maxStartupMetadataUpdates = 32; @@ -1399,6 +1401,25 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( Effect.andThen(runLoggedRequest(method, payload, effect)), ); + const withStartupTimeout = ( + method: string, + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.timeoutOrElse({ + duration: startupRequestTimeout, + orElse: () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + operation: "call-rpc", + method, + detail: `${method} timed out waiting for RPC response`, + cause: undefined, + }), + ), + }), + ); + const runLoggedRequest = ( method: string, payload: unknown, @@ -2297,7 +2318,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const initializeResult = yield* runLoggedRequest( "initialize", initializePayload, - acp.agent.initialize(initializePayload), + withStartupTimeout("initialize", acp.agent.initialize(initializePayload)), ); yield* options.onInitialized?.(initializeResult) ?? Effect.void; return initializeResult; @@ -2445,7 +2466,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( sessionSetupResult = yield* runLoggedRequest( "session/resume", resumePayload, - acp.agent.resumeSession(resumePayload), + withStartupTimeout("session/resume", acp.agent.resumeSession(resumePayload)), ); } else { return yield* new EffectAcpErrors.AcpRequestError({ @@ -2462,7 +2483,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const created = yield* runLoggedRequest( "session/new", createPayload, - acp.agent.createSession(createPayload), + withStartupTimeout("session/new", acp.agent.createSession(createPayload)), ); sessionId = created.sessionId; sessionSetupResult = created; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 21fe311588906..908c99e4eaeb3 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -637,6 +637,15 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Finalize a settled turn held only by running commands once the session has been silent for + * `timeout`, so a command that never reports back cannot leave the thread in Working forever. + * Other holds (questions, schedules, subagents) keep the turn open as before. + */ + readonly postSettleCommandHold?: { + readonly timeout: Duration.Input; + readonly isCommand: (toolCall: AcpToolCallState) => boolean; + }; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -2742,7 +2751,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const notePromptProgress = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) { - if (promptInactivityTimeoutMillis === undefined) return; + if ( + promptInactivityTimeoutMillis === undefined && + flavor.postSettleCommandHold === undefined + ) { + return; + } if ( notification !== undefined && !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate) @@ -4274,11 +4288,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isMonitorEndNoticeText = (text: string): boolean => /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); - const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + const hasDeferredBackgroundWork = ( + context: ActiveAcpTurn, + ignoreTool?: (tool: AcpToolCallState) => boolean, + ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { + if (ignoreTool?.(tool) === true) continue; if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) return true; } @@ -8835,6 +8853,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); + const schedulePostSettleHoldExpiry = Effect.fn("AcpAdapterV2.schedulePostSettleHoldExpiry")( + function* (context: ActiveAcpTurn) { + const hold = flavor.postSettleCommandHold; + if (hold === undefined) return; + if (!context.promptSettled || context.finalized) return; + const timeoutMillis = Duration.toMillis(hold.timeout); + const isRunningCommand = (tool: AcpToolCallState) => + toolStatus(tool.status) === "running" && hold.isCommand(tool); + let quietSince = yield* Clock.currentTimeMillis; + // Armed even without a command yet: a pending reply can still start one. + yield* Effect.gen(function* () { + while (!context.finalized) { + quietSince = Math.max(quietSince, context.lastProgressAt); + const now = yield* Clock.currentTimeMillis; + const remaining = quietSince + timeoutMillis - now; + if (remaining > 0) { + yield* Effect.sleep(Duration.millis(remaining)); + continue; + } + if ( + context.tools.values().some(isRunningCommand) && + !hasDeferredBackgroundWork(context, isRunningCommand) + ) { + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + return; + } + // Something else still holds the turn; count silence again once it clears. + quietSince = now; + } + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { @@ -9265,6 +9316,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + yield* schedulePostSettleHoldExpiry(context); if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9665,6 +9717,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (!context.finalized) { + yield* schedulePostSettleHoldExpiry(context); if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else { diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index 5317347aad13b..c8c17b84a9b7b 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { collectComposerInlineTokens as collectWithoutMath, type CollectComposerInlineTokensOptions, + composerFileLinksToPlainText, composerMathRanges, } from "./composerInlineTokens.ts"; import { markdownMathRanges } from "./markdownMath.ts"; @@ -230,3 +231,16 @@ describe("collectComposerInlineTokens", () => { ).toEqual(["$x_i$"]); }); }); + +describe("composerFileLinksToPlainText", () => { + it("shows file mentions by name and leaves other links as written", () => { + const mentions = ["src/foo.ts", ".gitignore", "pkg/__init__.py", "docs/My File (draft).md"] + .map(serializeComposerFileLink) + .join(" "); + expect(composerFileLinksToPlainText(`Review ${mentions}`)).toBe( + "Review foo.ts .gitignore __init__.py My File (draft).md", + ); + const links = "See [docs](https://example.com) and [the config](src/config.ts)"; + expect(composerFileLinksToPlainText(links)).toBe(links); + }); +}); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index b11a42b74a945..80a1b4d6916ae 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,3 +1,5 @@ +import { fileBasename } from "./path.ts"; + /** The formulas a Markdown parser finds in text, as source offsets. */ export type FindMathRanges = ( text: string, @@ -173,3 +175,16 @@ export function collectComposerInlineTokens( ) .sort((left, right) => left.start - right.start); } + +/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */ +export function composerFileLinksToPlainText(text: string): string { + let result = ""; + let cursor = 0; + // The composer reads a link as a mention only before whitespace, so one may end the text. + for (const token of collectMentionTokens(`${text} `)) { + if (!token.source.startsWith("[")) continue; + result += text.slice(cursor, token.start) + fileBasename(token.value); + cursor = token.end; + } + return result + text.slice(cursor); +} diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index b528c1ced5a8a..04a633bba7096 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -21,6 +21,8 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo import { decodeGitLabMergeRequestJson, decodeGitLabMergeRequestListJson, + type NormalizedGitLabMergeRequestRecord, + withSourceProjectPath, } from "./gitLabMergeRequests.ts"; import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; @@ -377,6 +379,10 @@ const decodeGitLabMergeRequestProject = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })), ); +const decodeGitLabProjectPath = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ path_with_namespace: TrimmedNonEmptyString })), +); + const RawGitLabNamespaceSchema = Schema.Struct({ id: Schema.Number, }); @@ -559,6 +565,35 @@ export const make = Effect.gen(function* () { ), ); + // glab's MR JSON names a fork's source project only by `source_project_id`. + const resolveSourceProjectPaths = Effect.fn("GitLabCli.resolveSourceProjectPaths")(function* ( + cwd: string, + records: ReadonlyArray, + paths: Map, + ) { + const ids = new Set(); + for (const record of records) { + const id = record.unresolvedSourceProjectId; + if (id !== undefined && !paths.has(id)) ids.add(id); + } + yield* Effect.forEach( + ids, + (id) => + execute({ cwd, args: ["api", `projects/${id}`] }).pipe( + Effect.flatMap((result) => decodeGitLabProjectPath(result.stdout.trim())), + Effect.map((project) => project.path_with_namespace), + Effect.orElseSucceed(() => null), + Effect.map((path) => void paths.set(id, path)), + ), + { concurrency: 8, discard: true }, + ); + return records.map((record) => + record.unresolvedSourceProjectId === undefined + ? record + : withSourceProjectPath(record, paths.get(record.unresolvedSourceProjectId) ?? null), + ); + }); + return GitLabCli.of({ execute, listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) { @@ -566,6 +601,7 @@ export const make = Effect.gen(function* () { let pageSize = limit; let page = 1; const items: GitLabMergeRequestSummary[] = []; + const sourceProjectPaths = input.source?.owner ? new Map() : null; while (items.length < limit) { const result = yield* execute({ cwd: input.cwd, @@ -600,7 +636,11 @@ export const make = Effect.gen(function* () { cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated", }); } - items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt)); + // Only a fork head can match a fork's merge request, so other lookups skip the API calls. + const records = sourceProjectPaths + ? yield* resolveSourceProjectPaths(input.cwd, decoded.success, sourceProjectPaths) + : decoded.success; + items.push(...records.map(toSummaryWithOptionalUpdatedAt)); // Count raw entries: the decoder drops invalid ones, which would end paging early. const entries = decodeJsonArray(raw); if ( @@ -635,7 +675,9 @@ export const make = Effect.gen(function* () { ); } - return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success)); + return resolveSourceProjectPaths(input.cwd, [decoded.success], new Map()).pipe( + Effect.map(([record]) => toSummaryWithOptionalUpdatedAt(record!)), + ); }), ), ), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts index 7038e6a82d630..abd2f7b82f218 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts @@ -106,6 +106,97 @@ it.effect("lists a nested-group fork's merge requests by source branch and names }), ); +// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its +// source project only by `source_project_id`, never by a `source_project` path. +it.effect("names a fork merge request's source project from real glab list output", () => + Effect.gen(function* () { + const branch = "feature/fork-work"; + const mergeRequest = (iid: number, sourceProjectId: number) => ({ + id: 9000 + iid, + iid, + project_id: 100, + title: `Work ${iid}`, + state: "opened", + target_branch: "main", + source_branch: branch, + source_project_id: sourceProjectId, + target_project_id: 100, + draft: false, + sha: "0123456789abcdef0123456789abcdef01234567", + updated_at: "2026-04-07T15:00:00.000Z", + references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` }, + web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`, + }); + const output = JSON.stringify([ + mergeRequest(1, 101), + mergeRequest(2, 101), + mergeRequest(3, 100), + mergeRequest(4, 102), + ]); + const apiCalls: ReadonlyArray[] = []; + const provider = yield* GitLabSourceControlProvider.make.pipe( + Effect.provide( + GitLabCli.layer.pipe( + Layer.provideMerge( + TestSourceControlHost.layer({ + process: { + run: (input) => + Effect.sync(() => { + if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output); + apiCalls.push(input.args); + return TestSourceControlHost.processOutput( + input.args[1] === "projects/101" + ? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" }) + : "not json", + ); + }), + }, + }), + ), + Layer.provide(FileSystem.layerNoop({})), + ), + ), + ); + + const upstreamHead = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: branch, + state: "open", + limit: 20, + }); + expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toEqual([]); + + const changeRequests = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: `alice:${branch}`, + state: "open", + limit: 20, + }); + // GitManager drops a cross-repository MR whose head project is unnamed. + expect(changeRequests).toMatchObject([ + { + number: 1, + isCrossRepository: true, + headRepositoryNameWithOwner: "alice/upstream", + headRepositoryOwnerLogin: "alice", + }, + { number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" }, + { number: 3, isCrossRepository: false }, + { number: 4, isCrossRepository: true }, + ]); + expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toHaveLength(2); + expect(apiCalls).toEqual( + expect.arrayContaining([ + ["api", "projects/101"], + ["api", "projects/102"], + ]), + ); + }), +); + const withRepository = ( test: (input: { readonly git: (...args: string[]) => Effect.Effect; diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index 8e5077044c6b3..c5a2d56037172 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -210,6 +210,13 @@ it.effect( headSelectors: ["octocat:feature", "feature"], state: "open", }), + { headSelectors: ["octocat:feature"], limit: 100 }, + ); + assert.deepStrictEqual( + provider.headBranchProbe?.({ + headSelectors: ["feature", "octocat:feature"], + state: "open", + }), { headSelectors: ["feature"], limit: 100 }, ); }), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts index a7d5b71ca47d3..2a2d4ac3e199c 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts @@ -211,11 +211,17 @@ export const make = Effect.gen(function* () { return SourceControlProvider.SourceControlProvider.of({ kind: SourceControlProviderKind.make("gitlab"), - // GitLab lists fork merge requests by source branch with no owner filter, so read a full page. - headBranchProbe: ({ headSelectors }) => ({ - headSelectors: headSelectors.filter((selector) => !selector.includes(":")), - limit: 100, - }), + // GitLab lists fork merge requests by source branch with no owner filter, so read a full page + // once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork + // head, which tells the list to name fork source projects. + headBranchProbe: ({ headSelectors }) => { + const byBranch = new Map(); + for (const selector of headSelectors) { + const branch = SourceControlProvider.sourceBranch({ headSelector: selector }); + if (!byBranch.has(branch)) byBranch.set(branch, selector); + } + return { headSelectors: [...byBranch.values()], limit: 100 }; + }, readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")( function ({ cwd, treeish }) { return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute); diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts index ef4438f5ff3ee..a40abd786cf85 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts @@ -23,6 +23,8 @@ export interface NormalizedGitLabMergeRequestRecord { readonly isCrossRepository?: boolean; readonly headRepositoryNameWithOwner?: string | null; readonly headRepositoryOwnerLogin?: string | null; + /** Set when a cross-repository MR names its source project only by id. */ + readonly unresolvedSourceProjectId?: number; } const GitLabProjectReferenceSchema = Schema.Struct({ @@ -122,6 +124,24 @@ function normalizeGitLabMergeRequestRecord( ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}), ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + ...(isCrossRepository === true && + !sourceProjectPath && + typeof raw.source_project_id === "number" + ? { unresolvedSourceProjectId: raw.source_project_id } + : {}), + }; +} + +export function withSourceProjectPath( + record: NormalizedGitLabMergeRequestRecord, + sourceProjectPath: string | null, +): NormalizedGitLabMergeRequestRecord { + const { unresolvedSourceProjectId: _, ...resolved } = record; + const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath); + return { + ...resolved, + ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), }; } diff --git a/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts new file mode 100644 index 0000000000000..8ee5453bbba20 --- /dev/null +++ b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A queued message shows its @-file mention by name, not as a raw link", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "src/foo.ts": "export {};\n" }); + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @foo"); + await screen.getByRole("option", "foo.ts", { exact: false }).tap(); + await expect(composer).toContainText("foo.ts"); + + // The showcase recording streams for several seconds, long enough to queue behind its turn. + await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Show me again"])); + await screen.getByText("Working for", { exact: false }).waitFor(); + // Enter steers by default; the alternate send queues. + await browser.keyboard.press("ControlOrMeta+Enter"); + + const queued = screen.getByRole("listitem", "Queued message 1 of 1, not sent"); + await queued.waitFor(); + // Read the row once: the queued message sends, and its row goes, when the turn ends. + const text = await queued.textContent(); + await app.screenshot("queued-row"); + expect(text).toContain("Review foo.ts"); + }, +);