diff --git a/apps/server/package.json b/apps/server/package.json index 1acce3756ae58..cb8352940f95e 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -24,7 +24,7 @@ "node-pty": "1.2.0-beta.15", "saxes": "6.0.0", "stream-chain": "^4.2.5", - "stream-json": "3.6.0", + "stream-json": "3.7.0", "yaml": "catalog:", "yauzl": "^3.4.0" }, diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index 1888861e869e3..a646b45c570d7 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -101,7 +101,7 @@ const permissionOptionIds = { const sessionId = "mock-session-1"; let currentModeId = antigravityProfile - ? "default" + ? (process.env.T3_ACP_INITIAL_MODE ?? "default") : copilotModesProfile ? copilotModeId("agent") : "ask"; diff --git a/apps/server/src/coderEnvironment.ts b/apps/server/src/coderEnvironment.ts index dd44fe3f95517..5207aba83c12f 100644 --- a/apps/server/src/coderEnvironment.ts +++ b/apps/server/src/coderEnvironment.ts @@ -99,6 +99,7 @@ export const CODER_ENVIRONMENT_CAPABILITIES = { oneTimeSchedules: true, freshContext: true, scheduledTaskThreadModes: true, + vcsBranchStatus: true, // Links are the gateway's workspace link rules; calls between workspaces go through its hub. peerLinks: true, linkFence: true, diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 624fcc1241b35..8e3012600f457 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -106,14 +106,18 @@ export interface McpInvocationScope { /** * T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so * they get the hosted link Copy thread copies, which opens the thread in either app or a browser. + * A known `title` labels the chip for clients that cannot load this environment's threads. */ export const threadLinkFor = ( scope: Pick, threadId: ThreadId, + title?: string, ): string => { const hostedAppUrl = scope.client?.hostedAppUrl; const ref = { environmentId: scope.environmentId, threadId }; - return hostedAppUrl === undefined ? formatThreadLink(ref) : hostedThreadLink(ref, hostedAppUrl); + return hostedAppUrl === undefined + ? formatThreadLink(ref, title) + : hostedThreadLink(ref, hostedAppUrl); }; export class McpInvocationContext extends Context.Service< diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts index 8ecdd0e74e9b6..f4016ba9a7665 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts @@ -135,6 +135,7 @@ it("readThread preserves caller access errors and prefers activity-run status ov makeRun({ id: cancelledRunId, ordinal: 2, status: "cancelled" }), ], visibleTurnItems: [], + providerTurns: [], runtimeRequests: [], messages: [], contextTransfers: [], @@ -221,6 +222,7 @@ it("readThread pages cut-off text without splitting an emoji across pages", asyn }), runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })], visibleTurnItems: [], + providerTurns: [], runtimeRequests: [], messages: [], contextTransfers: [], @@ -311,6 +313,7 @@ it("taskStatus returns task.providerInstanceId rather than the driver kind", asy }), runs: [makeRun({ id: activeRunId, ordinal: 1, status: "running" })], visibleTurnItems: [], + providerTurns: [], runtimeRequests: [], messages: [], contextTransfers: [], @@ -364,6 +367,7 @@ it("taskStatus returns task.providerInstanceId rather than the driver kind", asy }), ], visibleTurnItems: [], + providerTurns: [], runtimeRequests: [], messages: [], contextTransfers: [ @@ -437,6 +441,7 @@ it("readThread and sendToThread reach threads in other projects", async () => { return parentRuns; }, visibleTurnItems: [], + providerTurns: [], runtimeRequests: [], messages: [], contextTransfers: [], @@ -473,6 +478,7 @@ it("readThread and sendToThread reach threads in other projects", async () => { }, }, ], + providerTurns: [], runtimeRequests: [], messages: [], contextTransfers: [], @@ -669,6 +675,7 @@ it("requestSecret saves a pasted value to a file without opening a card", async }), runs: [{ ...makeRun({ id: activeRunId, ordinal: 1, status: "running" }), rootNodeId: taskId }], visibleTurnItems: [], + providerTurns: [], runtimeRequests: [], messages: [], contextTransfers: [], @@ -778,6 +785,7 @@ it("requestSecret returns the unsaved note for a declined, cancelled or timed-ou card === undefined ? [] : [{ type: "secret_request", id: card.turnItemId, secretStatus: outcome }], + providerTurns: [], runtimeRequests: [], messages: [], contextTransfers: [], diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts index a43d99ae61415..dafd8003f2215 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts @@ -146,6 +146,7 @@ describe("OrchestratorMcpService", () => { turnItems: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; let hasNestedWork = true; @@ -289,6 +290,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: [], turnItems: [], } as unknown as OrchestrationV2ThreadProjection; @@ -386,6 +388,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: pendingRequest ? [{ status: "pending" }] : [], nodes: [], turnItems: [], @@ -486,6 +489,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; const layerDependencies = Layer.mergeAll( @@ -576,6 +580,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: [], turnItems: [], } as unknown as OrchestrationV2ThreadProjection; @@ -679,6 +684,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; const layerDependencies = Layer.mergeAll( @@ -762,6 +768,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; const layerDependencies = Layer.mergeAll( @@ -851,6 +858,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: [], } as unknown as OrchestrationV2ThreadProjection; const layerDependencies = Layer.mergeAll( @@ -974,6 +982,7 @@ describe("OrchestratorMcpService", () => { appOwnedTask("node:mcp-cancel-grandchild-below", childThreadId, grandchildThreadId), ], providerThreads: [], + providerTurns: [], runtimeRequests: [], }, ], @@ -998,6 +1007,7 @@ describe("OrchestratorMcpService", () => { messages: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: [], }, ], @@ -1234,6 +1244,7 @@ describe("OrchestratorMcpService provider resolution", () => { messages: [], subagents: [], providerThreads: [], + providerTurns: [], runtimeRequests: [], turnItems: [], } as unknown as OrchestrationV2ThreadProjection; @@ -3061,9 +3072,18 @@ describe("OrchestratorMcpService provider resolution", () => { ordinal: 1, status: "running", modelSelection: runSelection, + activeAttemptId: "attempt:mcp-restarted-child", }, ] : [], + // Claude ran the requested Opus on Sonnet. + providerTurns: [ + { + runAttemptId: "attempt:mcp-restarted-child", + ordinal: 1, + model: "claude-sonnet-4-6", + }, + ], } as unknown as OrchestrationV2ThreadProjection), ), }), @@ -3077,11 +3097,15 @@ describe("OrchestratorMcpService provider resolution", () => { ); yield* Effect.gen(function* () { const service = yield* OrchestratorMcpService.OrchestratorMcpService; - for (const selection of [runSelection, threadSelection]) { + for (const [selection, executedModel] of [ + [runSelection, "claude-sonnet-4-6"], + [threadSelection, null], + ] as const) { const result = yield* service.taskStatus(scope, taskId); assert.equal(result.providerInstanceId, selection.instanceId); assert.equal(result.model, selection.model); assert.deepEqual(result.options, selection.options); + assert.equal(result.executedModel, executedModel); hasRun = false; } }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(dependencies)))); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 947f7f79a2f69..a28ec1cd16742 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -63,6 +63,7 @@ import { type ServerProviderModel, ThreadId, isOrchestrationV2WorkActive, + latestProviderTurnForAttempt, resolveProjectProviderInstanceEnabled, SECRET_REQUEST_UNSAVED_NOTE, } from "@t3tools/contracts"; @@ -610,7 +611,7 @@ function pageIncludesTerminalTaskResult(input: { readonly task: OrchestrationV2Subagent; readonly target: Pick< OrchestrationV2ThreadProjection, - "thread" | "runs" | "contextTransfers" | "messages" | "turnItems" + "thread" | "runs" | "contextTransfers" | "messages" | "turnItems" | "providerTurns" >; readonly maxChars: number; }): boolean { @@ -800,7 +801,7 @@ function listItemFromShell( threadId: shell.id, projectId: shell.projectId, title: shell.title, - link: threadLinkFor(scope, shell.id), + link: threadLinkFor(scope, shell.id, shell.title), createdBy: shell.createdBy, creationSource: shell.creationSource, status: shell.activityRunStatus ?? shell.status, @@ -834,7 +835,7 @@ function threadDetail( threadId: projection.thread.id, projectId: projection.thread.projectId, title: projection.thread.title, - link: threadLinkFor(scope, projection.thread.id), + link: threadLinkFor(scope, projection.thread.id, projection.thread.title), createdBy: projection.thread.createdBy, creationSource: projection.thread.creationSource, status: active?.status ?? latest?.status ?? "idle", @@ -871,13 +872,26 @@ function threadDetail( }; } -function threadRun(run: OrchestrationV2Run): OrchestratorMcpThreadRun { +function runExecutedModel( + projection: Pick, + run: Pick | undefined, +): string | null { + return run === undefined + ? null + : (latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId)?.model ?? null); +} + +function threadRun( + projection: Pick, + run: OrchestrationV2Run, +): OrchestratorMcpThreadRun { return { runId: run.id, ordinal: run.ordinal, status: run.status, providerInstanceId: run.modelSelection.instanceId, model: run.modelSelection.model, + executedModel: runExecutedModel(projection, run), requestedAt: DateTime.formatIso(run.requestedAt), startedAt: run.startedAt === null ? null : DateTime.formatIso(run.startedAt), completedAt: run.completedAt === null ? null : DateTime.formatIso(run.completedAt), @@ -1276,10 +1290,11 @@ const make = Effect.gen(function* () { const records = parent === undefined ? threadManagement - .getProjectThreadRecords(input, ["runs", "runtimeRequests"]) + .getProjectThreadRecords(input, ["runs", "providerTurns", "runtimeRequests"]) .pipe(Effect.map((target) => ({ ...target, contextTransfers: [] }))) : threadManagement.getProjectThreadRecords(input, [ "runs", + "providerTurns", "runtimeRequests", "contextTransfers", ]); @@ -1505,6 +1520,7 @@ const make = Effect.gen(function* () { "contextTransfers", "subagents", "providerThreads", + "providerTurns", "runtimeRequests", "nodes", ], @@ -1597,7 +1613,12 @@ const make = Effect.gen(function* () { : null; const resultContextTransferId = resultTransfer?.id ?? null; const latestTerminalResultContextTransferId = resultTransferForRun(terminalRun)?.id ?? null; - const modelSelection = childRun?.modelSelection ?? + const executionRun = + task.result === null + ? (taskResultRun ?? childRun) + : (childControls.runs.find((run) => run.id === resultTransfer?.sourcePoint.runId) ?? + childRun); + const modelSelection = executionRun?.modelSelection ?? childControls.thread.modelSelection ?? { instanceId: task.providerInstanceId, model: task.model, @@ -1605,10 +1626,10 @@ const make = Effect.gen(function* () { const result = { taskId: task.id, childThreadId: task.childThreadId, - link: formatThreadLink({ - environmentId: scope.environmentId, - threadId: task.childThreadId, - }), + link: formatThreadLink( + { environmentId: scope.environmentId, threadId: task.childThreadId }, + childControls.thread.title, + ), childRunId: childRun?.id ?? null, childNodeId: task.id, status, @@ -1616,6 +1637,7 @@ const make = Effect.gen(function* () { hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun), providerInstanceId: modelSelection.instanceId, model: modelSelection.model, + executedModel: runExecutedModel(childControls, executionRun), options: modelSelection.options ?? [], summary: derivedResult, resultContextTransferId, @@ -1651,7 +1673,11 @@ const make = Effect.gen(function* () { task.completionDelivery?.state !== "acknowledged" && task.completionDelivery?.state !== "disposed" ) { - const observingRun = ThreadManagementService.latestActiveRun(parentProjection); + const observingRun = ThreadManagementService.latestActiveRun({ + runs: parentProjection.runs.filter( + (run) => run.providerInstanceId === scope.thread.providerInstanceId, + ), + }); const acknowledgementRequestKey = yield* requestKey(undefined); yield* threadManagement .dispatch({ @@ -1663,10 +1689,7 @@ const make = Effect.gen(function* () { }), parentThreadId: scope.thread.threadId, taskId, - observedByRunId: - observingRun?.providerInstanceId === scope.thread.providerInstanceId - ? observingRun.id - : null, + observedByRunId: observingRun?.id ?? null, }) .pipe( Effect.mapError((error) => @@ -1746,7 +1769,11 @@ const make = Effect.gen(function* () { ), ), ); - const observingRun = ThreadManagementService.latestActiveRun(parentProjection); + const observingRun = ThreadManagementService.latestActiveRun({ + runs: parentProjection.runs.filter( + (run) => run.providerInstanceId === scope.thread.providerInstanceId, + ), + }); yield* threadManagement .dispatch({ type: "delegated_task.completion-delivery.acknowledge", @@ -1757,10 +1784,7 @@ const make = Effect.gen(function* () { }), parentThreadId: scope.thread.threadId, taskId: task.id, - observedByRunId: - observingRun?.providerInstanceId === scope.thread.providerInstanceId - ? observingRun.id - : null, + observedByRunId: observingRun?.id ?? null, }) .pipe( Effect.mapError((error) => @@ -1776,7 +1800,10 @@ const make = Effect.gen(function* () { childThreadId: null, ...(task.remoteChild === undefined ? {} - : { remoteChild: task.remoteChild, link: formatThreadLink(task.remoteChild) }), + : { + remoteChild: task.remoteChild, + link: formatThreadLink(task.remoteChild, task.remoteChild.title), + }), childRunId: null, childNodeId: task.id, status, @@ -1784,6 +1811,7 @@ const make = Effect.gen(function* () { hasPendingChildRuns: false, providerInstanceId: task.providerInstanceId, model: task.model, + executedModel: null, summary: task.result, resultContextTransferId: null, latestTerminalRunId: null, @@ -2207,6 +2235,7 @@ const make = Effect.gen(function* () { turnItemId, label: input.label, reason: input.reason, + ...(input.url === undefined ? {} : { url: input.url }), ...(input.placeholder === undefined ? {} : { placeholder: input.placeholder }), ...(input.delivery === "file" ? { delivery: "file" as const } : {}), secretStatus, @@ -2962,7 +2991,10 @@ const make = Effect.gen(function* () { ); return { threadId, - link: formatThreadLink({ environmentId: scope.environmentId, threadId }), + link: formatThreadLink( + { environmentId: scope.environmentId, threadId }, + projection.thread.title, + ), runId: run?.id ?? null, status: run?.status ?? "idle", title: projection.thread.title, @@ -3123,7 +3155,7 @@ const make = Effect.gen(function* () { recentRuns: target.runs .toSorted((left, right) => right.ordinal - left.ordinal) .slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT) - .map(threadRun), + .map((run) => threadRun(target, run)), items: page.map((row) => timelineItem({ row, @@ -3179,7 +3211,7 @@ const make = Effect.gen(function* () { ); return { threadId: input.threadId, - link: threadLinkFor(scope, input.threadId), + link: threadLinkFor(scope, input.threadId, target.thread.title), messageId, runId: result.run.id, ...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }), diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index 376075ddd3459..66caff8e422a0 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -185,7 +185,7 @@ const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", { const RequestSecretTool = Tool.make("request_secret", { description: - 'Ask for one secret per single-line card; never combine values. Open it, don\'t offer it. Returns one-use `secretRef`, or `delivery: "file"` a file read only in its command, e.g. `adb pair "$(cat )"`. Asked how: call now. Pasted secret for child/script: `value`. Never from an old thread.', + 'Ask for one secret per single-line card; never combine values. Open it, don\'t offer it. Returns one-use `secretRef`, or `delivery: "file"` a file read only in its command, e.g. `adb pair "$(cat )"`. Asked how: call now. Sign-in link: `url`. Pasted secret for child/script: `value`. Never from an old thread.', parameters: OrchestratorMcpRequestSecretInput, success: OrchestratorMcpRequestSecretResult, failure: OrchestratorMcpFailure, diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index 2e41c39265860..5b24d2daeeeda 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -195,7 +195,7 @@ it.effect( expect(belowCeiling.result).toMatchObject({ projectId: belowCeiling.projectId, modelSelection: belowCeiling.modelSelection, - link: ``, + link: `[Fix](t3-thread://v2/environment/${belowCeiling.launched[0]?.threadId})`, }); expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required"); expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined(); diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index e4c7ee35aa0c2..0ead9e1e58826 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -254,7 +254,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { const run = result.projection.runs.find((run) => run.userMessageId === messageId); return { threadId: thread.id, - link: McpInvocationContext.threadLinkFor(scope, thread.id), + link: McpInvocationContext.threadLinkFor(scope, thread.id, thread.title), projectId: thread.projectId, modelSelection: thread.modelSelection, runId: run?.id ?? null, diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index f968312437518..32e45b5d0a1c0 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -134,7 +134,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { return { matches: matches.map((match) => ({ ...match, - link: McpInvocationContext.threadLinkFor(scope, match.threadId), + link: McpInvocationContext.threadLinkFor(scope, match.threadId, match.title), })), }; }), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 170947a86d69f..b060bae05e21e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -2767,11 +2767,15 @@ describe("ClaudeAdapterV2 background wake turns", () => { uuid: "00000000-0000-4000-8000-000000000101", session_id: WAKE_NATIVE_SESSION, }); - const makeAssistantTextFrame = (input: { readonly uuid: string; readonly text: string }) => + const makeAssistantTextFrame = (input: { + readonly uuid: string; + readonly text: string; + readonly model?: string; + }) => claudeSdkFrame({ type: "assistant", message: { - model: "claude-sonnet-4-6", + model: input.model ?? "claude-sonnet-4-6", id: `msg_${input.uuid}`, type: "message", role: "assistant", @@ -2956,6 +2960,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { readonly freshQueueOnReopen?: boolean; readonly forkSession?: ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerShape["forkSession"]; readonly allocateSessionId?: Effect.Effect; + readonly promptSuggestions?: boolean; }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -3126,6 +3131,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { providerSessionId: ProviderSessionId.make("provider-session-claude-wake"), modelSelection: CLAUDE_TEST_MODEL_SELECTION, runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY, + promptSuggestions: Effect.succeed(options?.promptSuggestions === true), }); const providerThread = yield* runtime.ensureThread({ threadId, @@ -6668,7 +6674,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { }), ); yield* Queue.offerAll(harness.sdkMessages, [ - makeAssistantTextFrame({ uuid: mainUuid, text: "Delegating." }), + // Claude reports the model it ran, which can differ from the one requested. + makeAssistantTextFrame({ + uuid: mainUuid, + text: "Delegating.", + model: "claude-opus-4-5-20251101", + }), makeAssistantErrorFrame({ uuid: "00000000-0000-4000-8000-000000000642", error: undefined, @@ -6680,6 +6691,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { const providerTurn = lastProviderTurn(harness.events); assert.equal(providerTurn.nativeTurnRef?.nativeId, mainUuid); + assert.equal(providerTurn.model, "claude-opus-4-5"); const rolledBack = yield* harness.runtime.rollbackThread({ providerThread: harness.providerThread, target: { @@ -7696,6 +7708,101 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect.each(["root", "mcp", "subagent", "remote"] as const)( + "asks Claude for suggestions only on threads a person drives (%s)", + (lineage) => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ promptSuggestions: true }); + const base = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-prompt-suggestion"), + text: "Add a subtract function.", + attachments: [], + }); + const parentThreadId = ThreadId.make("thread-claude-suggestion-parent"); + // MCP-launched root threads carry `delegatedFrom: null` at runtime. + const offered = lineage === "root" || lineage === "mcp"; + const input = + lineage === "root" + ? base + : lineage === "mcp" + ? { + ...base, + appThread: { + ...base.appThread, + delegatedFrom: null as unknown as undefined, + }, + } + : lineage === "subagent" + ? { + ...base, + appThread: { + ...base.appThread, + lineage: { + parentThreadId, + relationshipToParent: "subagent" as const, + rootThreadId: parentThreadId, + }, + }, + } + : { + ...base, + appThread: { + ...base.appThread, + delegatedFrom: { + environmentId: EnvironmentId.make("environment-claude-suggestion-parent"), + threadId: parentThreadId, + title: "Parent", + }, + }, + }; + yield* harness.runtime.startTurn(input); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000690", result: "Done." }), + ); + yield* Queue.take(harness.terminalReceipts); + // Delegated threads have no one typing, so the SDK is never asked for suggestions. + assert.equal(harness.getOpenedOptions()?.promptSuggestions, offered); + if (!offered) return; + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "prompt_suggestion", + suggestion: " add tests for subtract\n", + uuid: "00000000-0000-4000-8000-000000000691", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.until(() => + harness.events.some((event) => event.type === "prompt_suggestion.updated"), + ); + assert.deepEqual( + harness.events.filter((event) => event.type === "prompt_suggestion.updated"), + [ + { + type: "prompt_suggestion.updated", + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + threadId: harness.threadId, + runId: input.runId, + text: "add tests for subtract", + }, + ], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("merges cumulative stream usage into the message_start counts", () => Effect.gen(function* () { const harness = yield* makeWakeHarnessWithOptions({ @@ -8453,13 +8560,23 @@ describe("ClaudeAdapterV2 background wake turns", () => { it.effect.each([ { outcome: "result", turnStatus: "completed", itemStatus: "failed" }, { outcome: "interrupt", turnStatus: "interrupted", itemStatus: "interrupted" }, + { outcome: "interrupt_aborted", turnStatus: "interrupted", itemStatus: "interrupted" }, { outcome: "query_exit", turnStatus: "failed", itemStatus: "failed" }, ] as const)( "settles unfinished compaction before the $outcome terminal receipt", ({ outcome, turnStatus, itemStatus }) => Effect.gen(function* () { + const interruptSent = yield* Deferred.make(); + const abortReported = yield* Deferred.make(); const harness = yield* makeWakeHarnessWithOptions({ close: (sdkMessages) => Queue.shutdown(sdkMessages), + ...(outcome === "interrupt_aborted" + ? { + interrupt: Deferred.succeed(interruptSent, undefined).pipe( + Effect.andThen(Deferred.await(abortReported)), + ), + } + : {}), }); const attemptId = RunAttemptId.make(`claude-compact-${outcome}`); yield* harness.runtime.startTurn( @@ -8483,15 +8600,34 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); if (outcome === "query_exit") { yield* Queue.shutdown(harness.sdkMessages); - } else if (outcome === "interrupt") { + } else if (outcome === "interrupt" || outcome === "interrupt_aborted") { const idAllocator = yield* IdAllocator.IdAllocatorV2; - yield* harness.runtime.interruptTurn({ - providerThread: harness.providerThread, - providerTurnId: idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${attemptId}`, - }), - }); + const interrupting = yield* harness.runtime + .interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + }) + .pipe(Effect.forkScoped); + if (outcome === "interrupt_aborted") { + // The CLI reports the aborted compaction as failed. + yield* Deferred.await(interruptSent); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + compact_result: "failed", + compact_error: "API Error: Request was aborted.", + uuid: "00000000-0000-4000-8000-000000000223", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* Deferred.succeed(abortReported, undefined); + } + yield* Fiber.join(interrupting); } else { yield* Queue.offer( harness.sdkMessages, @@ -8512,6 +8648,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { const [running, settled] = updates; assert.equal(running?.status, "running"); assert.equal(settled?.status, itemStatus); + assert.equal( + settled?.title, + itemStatus === "failed" ? "Context compaction failed" : "Context compaction stopped", + ); + if (outcome === "interrupt_aborted") assert.isUndefined(settled?.summary); assert.equal(settled?.id, running?.id); assert.equal(settled?.ordinal, running?.ordinal); assert.deepEqual(settled?.startedAt, running?.startedAt); @@ -12284,6 +12425,49 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); assert.isFalse(yield* harness.hasPendingBackgroundWork); + + // The continuation settled with no result of its own, so a late suggestion belongs to B. + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "prompt_suggestion", + suggestion: "Check the build logs", + uuid: "00000000-0000-4000-8000-000000000692", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const userTurn = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-4d"), + text: "Ship it.", + attachments: [], + providerTurnOrdinal: 4, + }); + yield* harness.runtime.startTurn(userTurn); + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000693", result: "Shipped." }), + ); + yield* harness.awaitTerminal(4); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "prompt_suggestion", + suggestion: "Open the release notes", + uuid: "00000000-0000-4000-8000-000000000694", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.until(() => + harness.events.some((event) => event.type === "prompt_suggestion.updated"), + ); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "prompt_suggestion.updated" ? [[event.runId, event.text]] : [], + ), + [[userTurn.runId, "Open the release notes"]], + ); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index f2b6020a5deb9..1494de3717f3b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -125,6 +125,7 @@ import { type RunId, type ThreadId, resolveIdleCompaction, + isDelegatedAppThread, } from "@t3tools/contracts"; import { FILE_HEADERS_ONLY, formatPatch, structuredPatch } from "diff"; @@ -182,6 +183,7 @@ import { type ClaudeModelCatalog, getClaudeCatalogModelCapabilities, resolveClaudeModelSlug, + resolveClaudeReportedModelSlug, scopeClaudeModelCatalog, } from "../../provider/ClaudeModelCatalog.ts"; import { @@ -1663,6 +1665,7 @@ export function makeClaudeQueryOptions(input: { readonly cwd: string | null; readonly attachmentsDir?: string; readonly settings?: ClaudeSettings; + readonly promptSuggestions?: boolean; readonly sdkSettings?: string | ClaudeSdkSettings; readonly environment?: NodeJS.ProcessEnv; readonly mcpServers?: ClaudeQueryOptions["mcpServers"]; @@ -1755,6 +1758,7 @@ export function makeClaudeQueryOptions(input: { ? "bypassPermissions" : (input.permissionMode ?? "default")), includePartialMessages: true, + promptSuggestions: input.promptSuggestions === true, ...(compiledSelection.effort === undefined ? {} : { @@ -4274,6 +4278,8 @@ interface ActiveClaudeTurnContext { nativeWakeStarted: boolean; gatedFramesBeforeEcho: number; readonly heldRootFrames: Array; + // Claude can run another model than requested, such as when an organization disallows it. + executedModel: string | undefined; } interface ActiveClaudeProviderRetry { @@ -4981,6 +4987,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), openSession: Effect.fn("ClaudeAdapterV2.openSession")( function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) { + const promptSuggestionsEnabled = input.promptSuggestions ?? Effect.succeed(false); const sessionScope = yield* Effect.scope; const now = yield* DateTime.now; const session = providerSession({ @@ -5373,6 +5380,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( startedAt: context.startedAt, completedAt: null, tokenUsage, + ...(context.executedModel === undefined ? {} : { model: context.executedModel }), }, }); }); @@ -5883,6 +5891,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( status: input.status, startedAt: input.context.startedAt, completedAt: input.completedAt, + ...(input.context.executedModel === undefined + ? {} + : { model: input.context.executedModel }), }); const buildToolCallArtifacts = (input: { @@ -8700,6 +8711,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } const message = input.message; + if (message.type === "prompt_suggestion") { + // Arrives after `result`; offer it only while the completed turn is still the latest. + // A continuation can settle from buffered frames first, so its suggestion may be a user turn's. + const settled = settledTurnByNativeThread.get(liveQuery.nativeThreadId); + const text = message.suggestion.trim(); + if ( + settled !== undefined && + !isClaudeProviderContinuationTurn(settled.input) && + text.length > 0 && + (yield* Ref.get(activeTurn)) === null + ) { + yield* emitProviderEvent({ + type: "prompt_suggestion.updated", + driver: CLAUDE_PROVIDER, + threadId: settled.input.threadId, + runId: settled.input.runId, + text, + }); + } + return; + } // Track before routing: idle-wake Monitors report tasks before replaying their tool calls. yield* trackClaudeMonitorCalls(message); // Update before routing because the idle wake gate reads this. @@ -8988,6 +9020,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // CLI notices and API errors arrive as assistant messages from "". if (message.message.model && message.message.model !== "") { context.rootModels.add(message.message.model); + context.executedModel = resolveClaudeReportedModelSlug( + modelCatalog, + message.message.model, + ); } // Subagent uuids exist only in the sidechain transcript, so resume and fork cannot target them. context.nativeMessageCursor = message.uuid; @@ -9022,9 +9058,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (message.compact_result !== undefined || (message.status === null && message.permissionMode === undefined)) ) { + // The CLI reports a compaction it aborted for our interrupt as failed. + const failed = + message.compact_result === "failed" && + !(yield* Ref.get(interruptedTurns)).has(context.providerTurnId); if (message.compact_result !== undefined) { - context.compactionFailure = - message.compact_result === "failed" ? { message: message.compact_error } : null; + context.compactionFailure = failed ? { message: message.compact_error } : null; } if (context.compaction?.status === "running") { const now = yield* DateTime.now; @@ -9033,18 +9072,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( status: message.compact_result === "success" ? "completed" - : message.compact_result === "failed" + : failed ? "failed" : "interrupted", title: message.compact_result === "success" ? "Context compacted" - : message.compact_result === "failed" + : failed ? "Context compaction failed" : "Context compaction stopped", - ...(message.compact_result === "failed" && message.compact_error - ? { summary: message.compact_error } - : {}), + ...(failed && message.compact_error ? { summary: message.compact_error } : {}), completedAt: now, updatedAt: now, }; @@ -10808,6 +10845,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( attachmentsDir, settings: adapterOptions.settings, ...(forkFrom === undefined ? {} : { forkFrom }), + // Delegated threads have no one typing, so they never ask for suggestions. + promptSuggestions: + !isDelegatedAppThread(turnInput.appThread) && (yield* promptSuggestionsEnabled), ...(launchArgSettings === undefined ? {} : { sdkSettings: claudeSdkLaunchArgSettings(launchArgSettings) }), @@ -11112,6 +11152,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeWakeStarted: false, gatedFramesBeforeEcho: 0, heldRootFrames: [], + executedModel: undefined, }; const attachTurn = Effect.gen(function* () { querySession.lastTurn = context; diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index aba8280c00ca1..a8ce0d5c7ce9d 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -1277,6 +1277,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { readChildMetadata?: Parameters[2], beforeEmitInbound?: CodexReplay.CodexAppServerReplayDriver["beforeEmitInbound"], onUsageLimits?: CodexAdapterV2.CodexAdapterV2Options["onUsageLimits"], + promptSuggestions: Effect.Effect = Effect.succeed(false), ) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -1352,6 +1353,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { providerSessionId: ProviderSessionId.make(`provider-session-${transcript.scenario}`), modelSelection: CODEX_TEST_MODEL_SELECTION, runtimePolicy: CODEX_TEST_RUNTIME_POLICY, + promptSuggestions, }); const providerThread = yield* runtime.ensureThread({ threadId, @@ -1857,6 +1859,211 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect.each(["subagent", "remote", "toggled-off"] as const)( + "never samples a suggestion for a %s thread", + (delegation) => + Effect.gen(function* () { + const nativeThreadId = `suggest-${delegation}-thread`; + const prompt = "Continue the task."; + const first = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: `${delegation}-turn-1`, + prompt, + }); + const second = codexReplayPreamble({ + nativeThreadId, + nativeTurnId: `${delegation}-turn-2`, + prompt, + }); + const completed = (nativeTurnId: string): CodexReplay.CodexAppServerReplayEntry => ({ + type: "emit_inbound", + label: `${nativeTurnId} completed`, + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }); + // The second turn is a barrier: a stray sample from the first turn is sent before it ends. + const requests: Array = []; + const enabled = yield* Ref.make(true); + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: `prompt-suggestion-${delegation}`, + entries: [ + ...first, + completed(`${delegation}-turn-1`), + ...second.slice(5, 7).map((entry) => withReplayRequestId(entry, 4)), + completed(`${delegation}-turn-2`), + ], + }), + undefined, + (method) => Effect.sync(() => requests.push(method)), + undefined, + undefined, + undefined, + Ref.get(enabled), + ); + // The flag is read per turn: turning it off after the session opened stops sampling. + if (delegation === "toggled-off") yield* Ref.set(enabled, false); + const base = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(`${delegation}-attempt-1`), + text: prompt, + }); + const parentThreadId = ThreadId.make("thread-codex-suggestion-parent"); + const turn = { + ...base, + appThread: + delegation === "toggled-off" + ? base.appThread + : delegation === "subagent" + ? { + ...base.appThread, + lineage: { + parentThreadId, + relationshipToParent: "subagent" as const, + rootThreadId: parentThreadId, + }, + } + : { + ...base.appThread, + delegatedFrom: { + environmentId: EnvironmentId.make("environment-codex-suggestion-parent"), + threadId: parentThreadId, + title: "Parent", + }, + }, + }; + yield* harness.runtime.startTurn(turn); + yield* harness.awaitTerminal(1); + yield* harness.runtime.startTurn({ + ...turn, + runId: RunId.make(`${delegation}-run-2`), + attemptId: RunAttemptId.make(`${delegation}-attempt-2`), + rootNodeId: NodeId.make(`${delegation}-root-2`), + runOrdinal: 2, + providerTurnOrdinal: 2, + }); + yield* harness.awaitTerminal(2); + assert.deepEqual( + harness.terminalEvents().map((event) => event.status), + ["completed", "completed"], + ); + assert.notInclude(requests, "thread/sample"); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("samples a next-prompt suggestion after a completed root turn", () => + Effect.gen(function* () { + const nativeThreadId = "suggest-thread"; + const nativeTurnId = "suggest-turn"; + const prompt = "Add a subtract function."; + const transcript = makeCodexReplayTranscript({ + scenario: "prompt-suggestion", + entries: [ + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt }), + { + type: "emit_inbound", + label: "turn/completed", + frame: { + method: "turn/completed", + params: { + threadId: nativeThreadId, + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }), + }, + }, + }, + { + type: "expect_outbound", + label: "thread/sample", + frame: { + id: 4, + method: "thread/sample", + params: { + threadId: nativeThreadId, + expectedTurnId: nativeTurnId, + prompt: CodexAdapterV2.CODEX_PROMPT_SUGGESTION_PROMPT, + effort: "low", + }, + }, + }, + { + type: "emit_inbound", + label: "thread/sample", + frame: { + id: 4, + result: { + sourceTurnId: nativeTurnId, + responseId: "resp-suggest", + text: " add tests for subtract\n", + inputTokens: 11448, + cachedInputTokens: 11264, + outputTokens: 16, + }, + }, + }, + ], + }); + const harness = yield* makeCodexReplayHarness( + transcript, + undefined, + undefined, + undefined, + undefined, + undefined, + Effect.succeed(true), + ); + const turnInput = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("suggest-attempt"), + text: prompt, + }); + yield* harness.runtime.startTurn(turnInput); + yield* harness.until(() => + harness.events.some((event) => event.type === "prompt_suggestion.updated"), + ); + assert.deepEqual( + harness.events.filter((event) => event.type === "prompt_suggestion.updated"), + [ + { + type: "prompt_suggestion.updated", + driver: CodexAdapterV2.CODEX_DRIVER_KIND, + threadId: harness.threadId, + runId: turnInput.runId, + text: "add tests for subtract", + }, + ], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + const assistantMessages = (events: ReadonlyArray) => events.filter( ( @@ -8471,7 +8678,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { nativeThreadId, nativeTurnId: "goal-turn-1", prompt: objective, - sentPrompt: `Start working toward this goal: ${objective}`, + sentPrompt: `This thread's goal is already set. Do not call create_goal. Start working on it now: ${objective}`, }).slice(5), 5, ), @@ -8611,7 +8818,7 @@ describe("CodexAdapterV2 post-settle continuation", () => { nativeThreadId, nativeTurnId: "goal-turn-limit", prompt: atLimit, - sentPrompt: `Start working toward this goal: ${atLimit}`, + sentPrompt: `This thread's goal is already set. Do not call create_goal. Start working on it now: ${atLimit}`, }).slice(5), 5, ), diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 0c4c1f8b01236..c12fc79ca41f2 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -37,6 +37,7 @@ import { ProviderDriverKind, ProviderSetupError, type ServerProviderCompatibilityAdvisory, + isDelegatedAppThread, } from "@t3tools/contracts"; import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; import { AgentScope } from "@t3tools/shared/AgentScope"; @@ -230,6 +231,10 @@ const decodeCodexBackgroundTerminalTerminateResponse = Schema.decodeUnknownEffec const decodeCodexBackgroundTerminalsListResponse = Schema.decodeUnknownEffect( CodexBackgroundTerminalsListResponse, ); +const CodexThreadSampleResponse = Schema.Struct({ text: Schema.NullOr(Schema.String) }); +const decodeCodexThreadSampleResponse = Schema.decodeUnknownEffect(CodexThreadSampleResponse); +export const CODEX_PROMPT_SUGGESTION_PROMPT = + "Predict the next message the user will send in this conversation. Reply with only that message, written as the user would type it, in under 20 words. Do not use tools. If there is no clear next step, reply with nothing."; const CODEX_CLIENT_CAPABILITIES = { experimentalApi: true, optOutNotificationMethods: ["turn/diff/updated"], @@ -1961,6 +1966,43 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) => Queue.offer(events, event).pipe(Effect.asVoid); + const promptSuggestionsEnabled = input.promptSuggestions ?? Effect.succeed(false); + // Best effort: older Codex lacks thread/sample, and a sample fails once the user sends again. + // Delegated threads share this session but have no one typing, so they never sample. + const samplePromptSuggestion = Effect.fn("CodexAdapterV2.samplePromptSuggestion")( + function* ( + context: ActiveCodexTurnContext, + nativeThreadId: string, + nativeTurnId: string, + ) { + if ( + isDelegatedAppThread(context.input.appThread) || + !(yield* promptSuggestionsEnabled) + ) { + return; + } + const response = yield* client.raw.request("thread/sample", { + threadId: nativeThreadId, + expectedTurnId: nativeTurnId, + prompt: CODEX_PROMPT_SUGGESTION_PROMPT, + effort: "low", + }); + const suggestion = + (yield* decodeCodexThreadSampleResponse(response)).text?.trim() ?? ""; + if (suggestion.length === 0) return; + yield* emitProviderEvent({ + type: "prompt_suggestion.updated", + driver: CODEX_PROVIDER, + threadId: context.projectionThreadId, + runId: context.input.runId, + text: suggestion, + }); + }, + Effect.catchCause((cause) => + Effect.logDebug("orchestration-v2.codex-prompt-suggestion-failed", { cause }), + ), + ); + const emitImageWorkState = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (context: ActiveCodexTurnContext, pending: boolean) { @@ -5977,6 +6019,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }); yield* emitRootTerminal(hold.context, { ...hold.event, status }); yield* Deferred.succeed(hold.next, undefined); + const nativeThreadId = hold.context.providerThread.nativeThreadRef?.nativeId; + if (status === "completed" && nativeThreadId != null) { + yield* samplePromptSuggestion( + hold.context, + nativeThreadId, + hold.context.nativeTurnId, + ).pipe(Effect.forkIn(scope)); + } }); const releaseGoalHold = Effect.fnUntraced(function* ( @@ -6308,6 +6358,20 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const retainSettledContext = input.status === "completed" && (yield* turnHasRetainedBackgroundWork(input.nativeTurnId)); + // A held goal predicts when settleGoalHold completes it. + if ( + input.status === "completed" && + input.context.subagent === null && + !input.continueRun && + !holdsForGoal && + nativeThreadId != null + ) { + yield* samplePromptSuggestion( + input.context, + nativeThreadId, + input.nativeTurnId, + ).pipe(Effect.forkIn(scope)); + } if (retainSettledContext) { yield* Ref.update(settledTurns, (current) => { const updated = new Map(current); @@ -6856,7 +6920,8 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const activation = { stopped: false }; goalActivations.set(threadId, activation); yield* Effect.gen(function* () { - // A bare objective reads like a statement, so the model echoes it back. + // A bare objective gets echoed back, and "start this goal" gets a + // create_goal call that Codex rejects because the goal already exists. yield* startNativeTurn( turnInput, command.type === "set" @@ -6864,7 +6929,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...turnInput, message: { ...turnInput.message, - text: `Start working toward this goal: ${command.objective}`, + text: `This thread's goal is already set. Do not call create_goal. Start working on it now: ${command.objective}`, }, }) : [], diff --git a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts index db3a2759e3ac5..64ed215ebed5c 100644 --- a/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts +++ b/apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts @@ -1628,6 +1628,73 @@ it.layer(layerContinuationWorkerTest)("interrupted completion wakes", (it) => { it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))( "subagent follow-ups", (it) => { + it.effect("a late unobserved read wakes a pending result without restarting", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread:late-read-live"); + const runId = RunId.make("run:late-read-live"); + const taskId = NodeId.make("task:late-read-live"); + yield* seedParentWithTerminalTask({ + threadId, + projectId: ProjectId.make("project:late-read-live"), + runId, + rootNodeId: NodeId.make("root:late-read-live"), + taskId, + deliveryState: "pending", + now, + }); + const acknowledge = (key: string) => + orchestrator.dispatch({ + type: "delegated_task.completion-delivery.acknowledge", + commandId: CommandId.make(`command:late-read-live:${key}`), + parentThreadId: threadId, + taskId, + observedByRunId: null, + }); + const before = yield* orchestrator.getThreadProjection(threadId); + const liveRead = yield* acknowledge("live"); + assert.lengthOf(liveRead.storedEvents, 0); + const parent = before.runs.find((run) => run.id === runId)!; + yield* sink.write({ + events: [ + { + id: EventId.make("event:late-read-live:parent-ended"), + type: "run.updated", + threadId, + runId, + occurredAt: now, + payload: { ...parent, status: "completed", completedAt: now }, + }, + ], + }); + yield* acknowledge("ended"); + const wake = yield* requests.take; + assert.equal(wake.threadId, threadId); + assert.equal(wake.delegatedCompletion?.parentRunId, runId); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + after.subagents.find((task) => task.id === taskId)?.completionDelivery?.state, + "claimed", + ); + assert.deepEqual( + after.runs.find((run) => run.id === runId)?.delegatedCompletion?.delivery?.taskIds, + [taskId], + ); + const repeated = yield* acknowledge("repeated"); + assert.lengthOf(repeated.storedEvents, 0); + assert.deepEqual(yield* orchestrator.getThreadProjection(threadId), after); + yield* orchestrator.dispatch({ + type: "delegated_task.completion-delivery.dispose", + commandId: CommandId.make("command:late-read-live:dispose"), + parentThreadId: threadId, + taskId, + }); + }), + ); + it.effect("recovers a reserved delivery without loading conversation history", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -3418,70 +3485,84 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => { }), ); - it.effect("wakes the parent for a settled_only task once its spawning turn ended", () => - Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const eventSink = yield* EventSink.EventSinkV2; - const now = yield* DateTime.now; - const threadId = ThreadId.make("thread:settled-only-restart"); - const projectId = ProjectId.make("project:settled-only-restart"); - const runId = RunId.make("run:settled-only-restart"); - const rootNodeId = NodeId.make("node:settled-only-restart-root"); - yield* seedParentWithTerminalTask({ - threadId, - projectId, - runId, - rootNodeId, - taskId: NodeId.make("node:settled-only-restart-settled"), - deliveryState: "delivered", - now, - }); - yield* eventSink.write({ - commandId: reconcileCommandId("settled-only-restart"), - events: [ - runEvent({ - threadId, - runId, - ordinal: 1, - status: "cancelled", - now, - providerThreadId: parentProviderThreadId(threadId), - userMessageId: MessageId.make(`message:seed-user:${threadId}`), - delegatedCompletion: { disposition: "open", nextGeneration: 2, delivery: null }, - }), - runEvent({ - threadId, - runId: RunId.make("run:settled-only-restart:continuation"), - ordinal: 2, - status: "running", - now, - providerThreadId: parentProviderThreadId(threadId), - }), - ], - }); - const child = yield* seedRestartCancelledChild({ - parentThreadId: threadId, - projectId, - parentRunId: runId, - rootNodeId, - name: "settled-only-restart-child", - completionWake: "settled_only", - continuationPending: false, - now, - }); + it.effect.each([false, true])( + "wakes the parent for a settled_only result with a running continuation: %s", + (runningContinuation) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + const suffix = runningContinuation ? "running" : "idle"; + const threadId = ThreadId.make(`thread:settled-only-restart-${suffix}`); + const projectId = ProjectId.make(`project:settled-only-restart-${suffix}`); + const runId = RunId.make(`run:settled-only-restart-${suffix}`); + const rootNodeId = NodeId.make(`node:settled-only-restart-root-${suffix}`); + yield* seedParentWithTerminalTask({ + threadId, + projectId, + runId, + rootNodeId, + taskId: NodeId.make(`node:settled-only-restart-settled-${suffix}`), + deliveryState: "delivered", + now, + }); + yield* eventSink.write({ + commandId: reconcileCommandId(`settled-only-restart-${suffix}`), + events: [ + runEvent({ + threadId, + runId, + ordinal: 1, + status: "cancelled", + now, + providerThreadId: parentProviderThreadId(threadId), + userMessageId: MessageId.make(`message:seed-user:${threadId}`), + delegatedCompletion: { disposition: "open", nextGeneration: 2, delivery: null }, + }), + ...(runningContinuation + ? [ + runEvent({ + threadId, + runId: RunId.make(`run:settled-only-restart:continuation-${suffix}`), + ordinal: 2, + status: "running", + now, + providerThreadId: parentProviderThreadId(threadId), + }), + ] + : []), + ], + }); + const child = yield* seedRestartCancelledChild({ + parentThreadId: threadId, + projectId, + parentRunId: runId, + rootNodeId, + name: `settled-only-restart-child-${suffix}`, + completionWake: "settled_only", + continuationPending: false, + now, + }); - yield* orchestrator.recoverDelegatedTasks; + yield* orchestrator.dispatch({ + type: "delegated_task.completion-delivery.acknowledge", + commandId: CommandId.make(`command:settled-only-late-read-${suffix}`), + parentThreadId: threadId, + taskId: child.taskId, + observedByRunId: null, + }); + yield* orchestrator.recoverDelegatedTasks; - const projection = yield* orchestrator.getThreadProjection(threadId); - assert.equal( - projection.subagents.find((row) => row.id === child.taskId)?.completionDelivery?.state, - "claimed", - ); - assert.deepEqual( - projection.runs.find((row) => row.id === runId)?.delegatedCompletion?.delivery?.taskIds, - [child.taskId], - ); - }), + const projection = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + projection.subagents.find((row) => row.id === child.taskId)?.completionDelivery?.state, + "claimed", + ); + assert.deepEqual( + projection.runs.find((row) => row.id === runId)?.delegatedCompletion?.delivery?.taskIds, + [child.taskId], + ); + }), ); it.effect.each(["a background command", "a nested subagent"] as const)( diff --git a/apps/server/src/orchestration-v2/EffectWorker.test.ts b/apps/server/src/orchestration-v2/EffectWorker.test.ts index 2329f2aa20cf0..3be77bba74c7c 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.test.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.test.ts @@ -21,6 +21,7 @@ import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; import * as CheckpointRollbackService from "./CheckpointRollbackService.ts"; import * as CheckpointService from "./CheckpointService.ts"; @@ -113,6 +114,7 @@ function layerExecutorFor(input: { detach: () => record("detach"), otherWorkingThreads: () => Effect.succeed([]), releaseUnlessBusy: () => Effect.succeed(true), + subscribePromptSuggestion: () => Stream.empty, }), ), Layer.succeed( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 813c4e5bfe60f..661ec9130acf2 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1,4 +1,5 @@ import type { + OrchestrationV2ThreadLinkMetadata, GuestShareId, OrchestrationV2SearchThreadInput, OrchestrationV2SearchThreadResult, @@ -442,6 +443,9 @@ export interface OrchestratorV2Shape { shareId: GuestShareId, ) => Effect.Effect; /** Titles of the given threads that exist, archived ones included. */ + readonly getThreadLinkMetadata: ( + threadIds: ReadonlyArray, + ) => Effect.Effect, OrchestratorV2Error>; readonly getThreadTitles: ( threadIds: ReadonlyArray, ) => Effect.Effect, OrchestratorV2Error>; @@ -1410,6 +1414,53 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? undefined : projection.messages.find((candidate) => candidate.id === delivery.messageId); + const isUnobservedAcknowledgement = ( + command: OrchestrationV2ServerCommand, + ): command is Extract< + OrchestrationV2ServerCommand, + { readonly type: "delegated_task.completion-delivery.acknowledge" } + > & { readonly observedByRunId: null } => + command.type === "delegated_task.completion-delivery.acknowledge" && + command.observedByRunId === null; + + /** Parent run and wake message events that commit a planDelegatedCompletionDelivery result. */ + const delegatedCompletionPlanEvents = ( + threadId: ThreadId, + plan: { + readonly parentRun: OrchestrationV2Run | undefined; + readonly message: OrchestrationV2ThreadProjection["messages"][number] | undefined; + }, + threadProviderInstanceId: ProviderInstanceId, + occurredAt: DateTime.Utc, + ): ReadonlyArray> => [ + ...(plan.parentRun === undefined + ? [] + : [ + { + type: "run.updated" as const, + threadId, + runId: plan.parentRun.id, + ...(plan.parentRun.rootNodeId === null ? {} : { nodeId: plan.parentRun.rootNodeId }), + providerInstanceId: plan.parentRun.providerInstanceId, + occurredAt, + payload: plan.parentRun, + }, + ]), + ...(plan.message === undefined + ? [] + : [ + { + type: "message.updated" as const, + threadId, + ...(plan.message.runId === null ? {} : { runId: plan.message.runId }), + ...(plan.message.nodeId === null ? {} : { nodeId: plan.message.nodeId }), + providerInstanceId: plan.parentRun?.providerInstanceId ?? threadProviderInstanceId, + occurredAt, + payload: plan.message, + }, + ]), + ]; + const offerDelegatedCompletionDelivery = /* This helper runs for individual orchestration events; the enclosing operation owns the span. */ Effect.fnUntraced(function* (threadId: ThreadId, parentRunId: RunId) { @@ -2596,6 +2647,56 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : "disposed"; const now = yield* DateTime.now; const emitEvent = emit(events, command); + // A late wait can arrive after finalization held the result for its still-live spawning run. + if (isUnobservedAcknowledgement(command)) { + if ( + !isTerminalDelegatedTaskStatus(task.status) || + task.completionDelivery?.state !== "pending" + ) + return; + const parentRun = projection.runs.find((run) => run.id === task.runId); + if (parentRun !== undefined && isLiveRun(parentRun)) return; + const records = yield* projectionStore + .getThreadRecords(command.parentThreadId, ["messages", "providerTurns"], { + messageRoles: ["user"], + }) + .pipe( + Effect.mapError( + (cause) => + new OrchestratorProjectionError({ + threadId: command.parentThreadId, + cause, + }), + ), + ); + const plan = yield* planDelegatedCompletionDelivery({ + parentProjection: { ...projection, ...records }, + parentRun, + task, + updatedTask: task, + now, + }).pipe(mapDispatchError(command)); + if (plan.task.completionDelivery?.state === "pending") return; + yield* emitEvent({ + type: "subagent.updated", + threadId: command.parentThreadId, + ...(task.runId === null ? {} : { runId: task.runId }), + nodeId: task.id, + driver: task.driver, + providerInstanceId: task.providerInstanceId, + occurredAt: now, + payload: plan.task, + }); + for (const event of delegatedCompletionPlanEvents( + command.parentThreadId, + plan, + projection.thread.providerInstanceId, + now, + )) { + yield* emitEvent(event); + } + return plan.parentRun?.id; + } // task_status and t3_thread_read use distinct command IDs, so two // valid observations can race after their read preflight. Re-emit the // existing task row so the second dispatch is a successful idempotent @@ -5884,10 +5985,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio taskIds: delivery.taskIds, }; } - // Route durable mailbox deliveries and delegated task questions under the - // thread lock, using the live session's capabilities. A question queued - // behind a long parent turn is never seen. Never interrupt/restart a turn - // for a notification. + // Steer mailbox deliveries, delegated task questions, and command notices + // into an active goal under the thread lock: queued behind a long turn or a + // goal run, they are never seen. Never interrupt/restart a turn for one. + const noticeKind = command.notification?.source.kind; + const commandNotice = noticeKind === "command" && command.creationSource === "server"; if ( !freshContext && (delegatedCompletion !== undefined @@ -5895,7 +5997,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (id) => projection.subagents.find((task) => task.id === id)?.completionWake === "always", ) - : command.notification?.source.kind === "delegated_task") + : noticeKind === "delegated_task" || commandNotice) ) { const active = projection.runs.find((run) => run.status === "running"); const providerThread = projection.providerThreads.find( @@ -5911,6 +6013,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio active !== undefined && activeTurn !== undefined && providerThread?.providerSessionId != null && + (!commandNotice || providerThread.goal?.status === "active") && (activeMessage === undefined || !isNativeMaintenanceCommand(activeMessage)) ) { const session = yield* providerSessions @@ -8537,28 +8640,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: plan.task, }); - if (plan.parentRun !== undefined) { - yield* emitEvent({ - type: "run.updated", - threadId: command.parentThreadId, - runId: plan.parentRun.id, - ...(plan.parentRun.rootNodeId === null ? {} : { nodeId: plan.parentRun.rootNodeId }), - providerInstanceId: plan.parentRun.providerInstanceId, - occurredAt: now, - payload: plan.parentRun, - }); - } - if (plan.message !== undefined) { - yield* emitEvent({ - type: "message.updated", - threadId: command.parentThreadId, - ...(plan.message.runId === null ? {} : { runId: plan.message.runId }), - ...(plan.message.nodeId === null ? {} : { nodeId: plan.message.nodeId }), - providerInstanceId: - plan.parentRun?.providerInstanceId ?? parentProjection.thread.providerInstanceId, - occurredAt: now, - payload: plan.message, - }); + for (const event of delegatedCompletionPlanEvents( + command.parentThreadId, + plan, + parentProjection.thread.providerInstanceId, + now, + )) { + yield* emitEvent(event); } const node = parentProjection.nodes.find((candidate) => candidate.id === task.id); if (node !== undefined) { @@ -8954,6 +9042,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "secret_request", label: command.label, reason: command.reason, + ...(command.url === undefined ? {} : { url: command.url }), ...(command.placeholder === undefined ? {} : { placeholder: command.placeholder }), ...(command.delivery === undefined ? {} : { delivery: command.delivery }), secretStatus: command.secretStatus, @@ -12832,40 +12921,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: completionPlan.task, }, - ...(completionPlan.parentRun === undefined - ? [] - : [ - { - type: "run.updated" as const, - threadId: parentThreadId, - runId: completionPlan.parentRun.id, - ...(completionPlan.parentRun.rootNodeId === null - ? {} - : { nodeId: completionPlan.parentRun.rootNodeId }), - providerInstanceId: completionPlan.parentRun.providerInstanceId, - occurredAt: now, - payload: completionPlan.parentRun, - }, - ]), - ...(completionPlan.message === undefined - ? [] - : [ - { - type: "message.updated" as const, - threadId: parentThreadId, - ...(completionPlan.message.runId === null - ? {} - : { runId: completionPlan.message.runId }), - ...(completionPlan.message.nodeId === null - ? {} - : { nodeId: completionPlan.message.nodeId }), - providerInstanceId: - completionPlan.parentRun?.providerInstanceId ?? - parentProjection.thread.providerInstanceId, - occurredAt: now, - payload: completionPlan.message, - }, - ]), + ...delegatedCompletionPlanEvents( + parentThreadId, + completionPlan, + parentProjection.thread.providerInstanceId, + now, + ), ...(parentNode === undefined ? [] : [ @@ -13775,6 +13836,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.filterOrFail( (planned) => planned.events.length > 0 || + isUnobservedAcknowledgement(command) || command.type === "thread.background-work.settle" || command.type === "thread.interrupt.unresponsive" || command.type === "thread.stop" || @@ -13927,7 +13989,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } if ( command.type === "delegated_task.wake-policy" || - command.type === "delegated_task.remote.complete" + command.type === "delegated_task.remote.complete" || + isUnobservedAcknowledgement(command) ) { yield* mapDispatchError(command)(offerDelegatedCompletionDeliveries(command.parentThreadId)); } @@ -14439,6 +14502,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio .findGuestShareThreadId(shareId) .pipe(Effect.mapError(shellProjectionError)); }), + getThreadLinkMetadata: Effect.fn("OrchestratorV2.getThreadLinkMetadata")(function (threadIds) { + return projectionStore + .getThreadLinkMetadata(threadIds) + .pipe(Effect.mapError(shellProjectionError)); + }), getThreadTitles: Effect.fn("OrchestratorV2.getThreadTitles")(function (threadIds) { return projectionStore.getThreadTitles(threadIds).pipe(Effect.mapError(shellProjectionError)); }), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 52f5d7e43ae74..8637074cfa52d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -1327,6 +1327,24 @@ const threadWorktreePathsIncludeArchivedOnRequest = Effect.gen(function* () { { threadId: ThreadId.make("thread:active"), worktreePath: "/worktrees/active" }, { threadId: ThreadId.make("thread:archived"), worktreePath: "/worktrees/archived" }, ]); + assert.deepEqual( + yield* store.getThreadLinkMetadata([ + deleted.id, + ThreadId.make("thread:active"), + ThreadId.make("thread:archived"), + ThreadId.make("unknown"), + ]), + { + [ThreadId.make("thread:active")]: { + title: "Title for thread:active", + projectId: ProjectId.make("project:worktree-paths"), + }, + [ThreadId.make("thread:archived")]: { + title: "Title for thread:archived", + projectId: ProjectId.make("project:worktree-paths"), + }, + }, + ); assert.deepEqual( yield* store.getThreadTitles([ deleted.id, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 43e696c9c583e..90bd54a73d587 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -6,6 +6,7 @@ import * as Stream from "effect/Stream"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import { makeThreadFind } from "./ThreadFind.ts"; import type { + OrchestrationV2ThreadLinkMetadata, OrchestrationV2SearchThreadInput, OrchestrationV2SearchThreadResult, OrchestrationV2ThreadHistoryPage, @@ -562,6 +563,9 @@ export interface ProjectionStoreV2Shape { threadId?: ThreadId, ) => Effect.Effect, ProjectionStoreV2Error>; /** Titles of the given threads that exist, archived ones included. */ + readonly getThreadLinkMetadata: ( + threadIds: ReadonlyArray, + ) => Effect.Effect, ProjectionStoreV2Error>; readonly getThreadTitles: ( threadIds: ReadonlyArray, ) => Effect.Effect, ProjectionStoreV2Error>; @@ -1008,6 +1012,7 @@ export type AgentAwarenessThread = ProjectThreadAwarenessV2Input["thread"] & Pick< OrchestrationV2ThreadShell, | "projectId" + | "creationSource" | "latestRunCompletedAt" | "archivedAt" | "activeRunId" @@ -7168,6 +7173,7 @@ export const layer: Layer.Layer = Effect.map((state): AgentAwarenessThread => ({ id: state.thread.id, projectId: state.thread.projectId, + creationSource: state.thread.creationSource, archivedAt: state.thread.archivedAt, activeRunId: state.activeRunId, latestRunId: state.latestRunId, @@ -7305,6 +7311,24 @@ export const layer: Layer.Layer = })); }, Effect.mapError(shellSnapshotReadError)); + const getThreadLinkMetadata = Effect.fn("ProjectionStore.getThreadLinkMetadata")(function* ( + threadIds: ReadonlyArray, + ) { + if (threadIds.length === 0) return {}; + const rows = yield* sql<{ + readonly thread_id: ThreadId; + readonly title: string; + readonly project_id: ProjectId; + }>` + SELECT thread_id, title, project_id + FROM orchestration_v2_projection_threads + WHERE deleted_at IS NULL AND thread_id IN ${sql.in(threadIds)} + `; + return Object.fromEntries( + rows.map((row) => [row.thread_id, { title: row.title, projectId: row.project_id }]), + ); + }, Effect.mapError(shellSnapshotReadError)); + const getThreadTitles = Effect.fn("ProjectionStore.getThreadTitles")(function* ( threadIds: ReadonlyArray, ) { @@ -7484,6 +7508,7 @@ export const layer: Layer.Layer = getSettlementCandidates: readOnReader(getSettlementCandidates), getThreadsWithPullRequests: readOnReader(getThreadsWithPullRequests), getThreadTitles: readOnReader(getThreadTitles), + getThreadLinkMetadata: readOnReader(getThreadLinkMetadata), getThreadWorktreePaths: readOnReader(getThreadWorktreePaths), getOpenRemoteDelegatedTasks: getOpenRemoteDelegatedTasks.pipe(NodeSqliteClient.readOnly), getThreadProjection: readOnReader(getThreadProjection), diff --git a/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts b/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts index 66d39e1c150d1..2d52bf8b15b5c 100644 --- a/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts @@ -248,12 +248,12 @@ describe("ProviderContinuationService", () => { }); it.effect( - "a project-disabled instance refuses a delegated-completion wake exactly once, acknowledges it, and never retries", + "a project-disabled instance refuses a delegated-completion wake exactly once, disposes it, and never retries", () => { return Effect.gen(function* () { const attempts = yield* Ref.make(0); const cleared = yield* Ref.make(false); - const acknowledged = yield* Queue.unbounded(); + const disposed = yield* Queue.unbounded(); const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({ getThreadRecords: () => Effect.succeed(delegatedProjection()), dispatch: (command) => { @@ -271,7 +271,7 @@ describe("ProviderContinuationService", () => { ), ); } - return Queue.offer(acknowledged, command).pipe(Effect.as({} as never)); + return Queue.offer(disposed, command).pipe(Effect.as({} as never)); }, }); const layerWorker = ProviderContinuationService.layer.pipe( @@ -299,24 +299,22 @@ describe("ProviderContinuationService", () => { assert.equal(yield* Ref.get(attempts), 1); assert.isTrue(yield* Ref.get(cleared)); - const acknowledgements = (yield* Queue.takeAll(acknowledged)) as ReadonlyArray<{ + const dispositions = (yield* Queue.takeAll(disposed)) as ReadonlyArray<{ type: string; taskId: string; - observedByRunId: string | null; }>; assert.deepEqual( - acknowledgements.map((command) => command.taskId), + dispositions.map((command) => command.taskId), ["node-provider-continuation-first", "node-provider-continuation-second"], ); - for (const command of acknowledgements) { - assert.equal(command.type, "delegated_task.completion-delivery.acknowledge"); - assert.isNull(command.observedByRunId); + for (const command of dispositions) { + assert.equal(command.type, "delegated_task.completion-delivery.dispose"); } yield* TestClock.adjust("1 hour"); yield* Effect.yieldNow; assert.equal(yield* Ref.get(attempts), 1); - assert.equal(yield* Queue.size(acknowledged), 0); + assert.equal(yield* Queue.size(disposed), 0); }).pipe( Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)), Effect.scoped, diff --git a/apps/server/src/orchestration-v2/ProviderContinuationService.ts b/apps/server/src/orchestration-v2/ProviderContinuationService.ts index 5435130e689c2..1fe30ee0645c8 100644 --- a/apps/server/src/orchestration-v2/ProviderContinuationService.ts +++ b/apps/server/src/orchestration-v2/ProviderContinuationService.ts @@ -151,16 +151,15 @@ export const layer = Layer.effectDiscard( ids.allocate .command({ fixtureName: "delegated-completion", - commandName: "acknowledge-disabled", + commandName: "dispose-disabled", }) .pipe( - Effect.flatMap((ackCommandId) => + Effect.flatMap((disposeCommandId) => threads.dispatch({ - type: "delegated_task.completion-delivery.acknowledge", - commandId: ackCommandId, + type: "delegated_task.completion-delivery.dispose", + commandId: disposeCommandId, parentThreadId: request.threadId, taskId, - observedByRunId: null, }), ), ), diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index f27580d909aff..40a858bbeb79f 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -619,7 +619,8 @@ export const layer: Layer.Layer< case "background_work.updated": return []; case "command_output.delta": - // Live output is routed to the command output hub before ingestion. + case "prompt_suggestion.updated": + // The session manager serves these to clients before ingestion. return []; case "turn.terminal": const dismissed = yield* dismissNativeUserInputs(input, input.event.providerTurnId); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 4342b490e75bf..40bc51492a469 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -8,6 +8,7 @@ import { type ModelSelection, type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, + type OrchestrationV2PromptSuggestion, type OrchestrationV2ProviderCapabilities, type OrchestrationV2ProviderSession, type OrchestrationV2ProviderThread, @@ -2764,6 +2765,63 @@ it.effect("ProviderSessionManagerV2 terminal detach revokes the thread's MCP cre }), ); +it.effect( + "ProviderSessionManagerV2 stops serving prompt suggestions once a thread is deleted", + () => + Effect.gen(function* () { + const state = yield* Ref.make(emptyState); + const effect = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const manager = yield* ProviderSessionManager.ProviderSessionManagerV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("thread-provider-session-manager-suggestion"); + const providerSessionId = yield* idAllocator.allocate.providerSession({ + providerInstanceId: modelSelection.instanceId, + threadId, + }); + const created = yield* makeThreadCreatedEvent({ idAllocator, threadId, now }); + yield* eventSink.write({ events: [created] }); + yield* manager.open({ threadId, providerSessionId, modelSelection, runtimePolicy }); + const queue = (yield* Ref.get(state)).eventQueues.get(String(providerSessionId)); + const runId = idAllocator.derive.run({ threadId, ordinal: 1 }); + const suggest = (text: string) => + Queue.offer(queue!, { + type: "prompt_suggestion.updated", + driver: CODEX_DRIVER, + threadId, + runId, + text, + }); + const received = yield* Queue.unbounded(); + yield* manager.subscribePromptSuggestion(threadId).pipe( + Stream.runForEach((suggestion) => Queue.offer(received, suggestion)), + Effect.forkScoped, + ); + assert.isNull(yield* Queue.take(received)); + + yield* suggest("add tests"); + assert.deepEqual(yield* Queue.take(received), { runId, text: "add tests" }); + + yield* eventSink.write({ + events: [ + { + ...created, + id: yield* idAllocator.allocate.event({ threadId }), + type: "thread.deleted", + payload: { ...created.payload, deletedAt: now }, + }, + ], + }); + // A late Codex sample can land after deletion; the open subscription must drop it. + yield* suggest("ship it"); + assert.isNull(yield* Queue.take(received)); + }); + + yield* effect.pipe(Effect.scoped, Effect.provide(layerTest({ state, idleTimeoutMs: 1_000 }))); + }), +); + const openSessionWithBackgroundCommand = (fixtureName: string) => Effect.gen(function* () { const eventSink = yield* EventSink.EventSinkV2; diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index ba1deb3f52982..c4b8e94542d70 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -6,6 +6,7 @@ import { ModelSelection, OrchestrationV2DomainEvent, OrchestrationV2ProviderSession, + type OrchestrationV2PromptSuggestion, type OrchestrationV2ProviderThread, OrchestrationV2RuntimeRequest, ProviderInstanceId, @@ -32,6 +33,7 @@ import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; // Coder: no provider session or turn metrics (`withMetrics`); metrics are not carried. import { ProviderWorkspaceMissingError } from "../provider/Errors.ts"; @@ -58,6 +60,8 @@ const busyTurnPrefix = (providerThreadId: ProviderThreadId) => `${providerThread const busyTurnKey = (providerThreadId: ProviderThreadId, runOrdinal: number) => `${busyTurnPrefix(providerThreadId)}${runOrdinal}`; const UNLOAD_THREAD_TIMEOUT_MS = 10 * 1000; +/** Suggestions outlive their sessions, so keep only the most recently updated threads. */ +const MAX_PROMPT_SUGGESTIONS = 256; const WORKING_RUN_STATUSES: ReadonlySet = new Set([ "preparing", "starting", @@ -202,6 +206,10 @@ export interface ProviderSessionManagerV2Shape { readonly providerSessionId: ProviderSessionId; readonly threadId: ThreadId; }) => Effect.Effect>; + /** The thread's latest predicted next prompt, then each replacement. */ + readonly subscribePromptSuggestion: ( + threadId: ThreadId, + ) => Stream.Stream; } export class ProviderSessionManagerV2 extends Context.Service< @@ -339,10 +347,21 @@ export const layerWithOptions = ( const projectService = yield* Effect.serviceOption(ProjectService.ProjectService); const eventSink = yield* EventSink.EventSinkV2; const commandOutput = yield* CommandOutputHub.CommandOutputHub; + const promptSuggestionStore = yield* SubscriptionRef.make< + ReadonlyMap> + >(new Map()); const idAllocator = yield* IdAllocator.IdAllocatorV2; const providerEventIngestor = yield* ProviderEventIngestor.ProviderEventIngestorV2; const projectionStore = yield* ProjectionStore.ProjectionStoreV2; const agentScope = yield* AgentScope; + // Labs flag, read live: Codex per turn (its shared session outlives a toggle), Claude per query. + // Unreadable settings keep it off. + const promptSuggestionsEnabled = Option.isNone(serverSettings) + ? Effect.succeed(false) + : serverSettings.value.getSettings.pipe( + Effect.map((settings) => settings.promptSuggestionsEnabled), + Effect.orElseSucceed(() => false), + ); const agentAccessSettings = Effect.fn("ProviderSessionManagerV2.agentAccessSettings")( function* (threadId: ThreadId) { if (Option.isNone(serverSettings)) return { browser: true, device: false }; @@ -2146,6 +2165,18 @@ export const layerWithOptions = ( if (event.type === "command_output.delta") { return commandOutput.append(event); } + if (event.type === "prompt_suggestion.updated") { + return SubscriptionRef.update(promptSuggestionStore, (current) => { + const next = new Map(current); + next.delete(event.threadId); + next.set(event.threadId, { runId: event.runId, text: event.text }); + for (const threadId of next.keys()) { + if (next.size <= MAX_PROMPT_SUGGESTIONS) break; + next.delete(threadId); + } + return next; + }); + } const releaseLiveOutput = event.type === "turn_item.updated" && event.turnItem.type === "command_execution" && @@ -2389,6 +2420,7 @@ export const layerWithOptions = ( providerSessionId: input.providerSessionId, modelSelection: input.modelSelection, runtimePolicy: input.runtimePolicy, + promptSuggestions: promptSuggestionsEnabled, ...(input.resumeFromSession === undefined ? {} : { resumeFromSession: input.resumeFromSession }), @@ -2762,6 +2794,21 @@ export const layerWithOptions = ( ), ), ), + // Stored suggestions can outlive a deleted thread, so check the thread before serving one. + subscribePromptSuggestion: (threadId) => + SubscriptionRef.changes(promptSuggestionStore).pipe( + Stream.map((suggestions) => suggestions.get(threadId) ?? null), + Stream.changes, + Stream.mapEffect((suggestion) => + suggestion === null + ? Effect.succeed(null) + : projectionStore.getThread(threadId).pipe( + Effect.map((thread) => (thread.deletedAt === null ? suggestion : null)), + Effect.orElseSucceed(() => null), + ), + ), + Stream.changes, + ), } satisfies ProviderSessionManagerV2Shape); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index 55e2a9e50e3ef..8b30a961c099d 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -221,6 +221,7 @@ it.effect( readShellSnapshot: () => Effect.die("unused readShellSnapshot"), getThreadShell: () => Effect.die("unused getThreadShell"), getThreadTitles: () => Effect.die("unused getThreadTitles"), + getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"), findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"), getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)), getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"), @@ -293,6 +294,7 @@ it.effect( detach: () => Effect.void, otherWorkingThreads: () => Effect.succeed([]), releaseUnlessBusy: () => Effect.succeed(true), + subscribePromptSuggestion: () => Stream.empty, }), ); const layerControl = ProviderTurnControlService.layer.pipe( diff --git a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts index cd244e85e2c02..d6a15eb301613 100644 --- a/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts +++ b/apps/server/src/orchestration-v2/PullRequestWatchReactor.ts @@ -350,6 +350,7 @@ export const make = Effect.gen(function* () { if (tail === undefined) { const comments = new Map(); const cursors = new Set(); + let hidden = 0; while (cursor !== null) { if (cursors.has(cursor)) return null; cursors.add(cursor); @@ -366,9 +367,10 @@ export const make = Effect.gen(function* () { reviewState: null, }); } + hidden += page.hiddenCount ?? 0; cursor = page.nextCursor; } - if (thread.comments.length + comments.size < count) return null; + if (thread.comments.length + comments.size + hidden < count) return null; tail = { count, comments: [...comments.values()] }; } tails.set(thread.id, tail); diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 3cb06f3f59b65..e97d7e43e1fab 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -511,7 +511,8 @@ export function routeProviderEvent( case "background_work.updated": return [state.ownedProviderTurns.has(event.providerTurnId), state]; case "command_output.delta": - // The session manager hands live output to the command output hub; runs never see it. + case "prompt_suggestion.updated": + // The session manager serves these to clients directly; runs never see them. return [false, state]; case "turn.terminal": return event.providerTurnId === state.rootProviderTurnId diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 2b08c0b8345b6..2c311f2569753 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -651,63 +651,97 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* return { cwd, events, started, steered, interrupted, layer, startFirstTurn }; }); -it.effect("steers a delegated task question notice into the running parent turn", () => - Effect.scoped( - Effect.gen(function* () { - const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - "delegated-question-steer", - ); - yield* Effect.gen(function* () { - const orchestrator = yield* Orchestrator.OrchestratorV2; - const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; - const threadId = yield* startFirstTurn; - const { thread } = yield* orchestrator.getThreadProjection(threadId); - yield* (yield* EventSink.EventSinkV2).write({ - events: [ - { - id: EventId.make("event:composer-selection"), - type: "thread.model-selection-updated", - threadId, - providerInstanceId: instanceId, - occurredAt: yield* DateTime.now, - payload: { ...thread, modelSelection: composerSelection }, - }, - ], - }); - const messageId = MessageId.make("message:delegated-task-question:child-question"); - const notification = { - source: { - kind: "delegated_task" as const, - taskIds: [NodeId.make("task:question")], - childThreadId: ThreadId.make("thread:question-child"), - }, - outcome: "updated" as const, - summary: "Delegated task has a question", - }; - yield* orchestrator.dispatch({ - type: "message.dispatch", - commandId: CommandId.make("question-wake"), - threadId, - messageId, - text: "Delegated task asked a question", - notification, - attachments: [], - dispatchMode: { type: "queue_after_active" }, - createdBy: "agent", - creationSource: "server", - }); - yield* worker.drain(); - const after = yield* orchestrator.getThreadProjection(threadId); - assert.deepEqual(steered, ["Delegated task asked a question"]); - assert.lengthOf(started, 1); - assert.isFalse(after.runs.some((run) => run.status === "queued")); - const message = after.messages.find((candidate) => candidate.id === messageId); - assert.equal(message?.runId, started[0]?.runId); - assert.deepEqual(message?.notification, notification); - assert.deepEqual(after.thread.modelSelection, composerSelection); - }).pipe(Effect.provide(layer)); - }), - ), +it.effect.each([ + { notice: "delegated task question", goal: null, steers: true }, + { notice: "background command", goal: "active", steers: true }, + { notice: "background command", goal: null, steers: false }, +] as const)( + "a $notice notice steers into the running turn: $steers (goal $goal)", + ({ notice, goal, steers }) => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}`, + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const { thread } = yield* orchestrator.getThreadProjection(threadId); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:composer-selection"), + type: "thread.model-selection-updated", + threadId, + providerInstanceId: instanceId, + occurredAt: yield* DateTime.now, + payload: { ...thread, modelSelection: composerSelection }, + }, + ], + }); + if (goal !== null) { + const providerThread = (yield* orchestrator.getThreadProjection(threadId)) + .providerThreads[0]!; + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:goal-active"), + type: "provider-thread.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { ...providerThread, goal: { objective: "Ship it", status: goal } }, + }, + ], + }); + } + const messageId = MessageId.make("message:notice"); + const notification = + notice === "delegated task question" + ? { + source: { + kind: "delegated_task" as const, + taskIds: [NodeId.make("task:question")], + childThreadId: ThreadId.make("thread:question-child"), + }, + outcome: "updated" as const, + summary: "Delegated task has a question", + } + : { + source: { kind: "command" as const }, + outcome: "completed" as const, + summary: "Background command finished", + }; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("notice-wake"), + threadId, + messageId, + text: `${notification.summary}\nexit 0: built 12 files`, + notification, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + steered, + steers ? [`${notification.summary}\nexit 0: built 12 files`] : [], + ); + assert.lengthOf(started, 1); + assert.equal( + after.runs.some((run) => run.status === "queued"), + !steers, + ); + const message = after.messages.find((candidate) => candidate.id === messageId); + assert.deepEqual(message?.notification, notification); + if (steers) assert.equal(message?.runId, started[0]?.runId); + assert.deepEqual(after.thread.modelSelection, composerSelection); + }).pipe(Effect.provide(layer)); + }), + ), ); it.effect("sends a selected held message once and preserves the remaining queue order", () => diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index ae8f7e09d2068..87ac8a2ad1758 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -413,6 +413,14 @@ it("orders a task's assistant messages by turn item, not by timestamps", () => { assert.equal(result.text, "All steps passed."); assert.equal(result.messageId, report.message.id); assert.equal(result.turnItemId, report.turnItem.id); + const reported = { runAttemptId: run.activeAttemptId, ordinal: 1, model: "gpt-5.4-mini" }; + assert.equal( + subagentResultForRun( + { ...projection, messages: [report.message], providerTurns: [reported as never] }, + run, + ).text, + "Requested model gpt-5.4; the provider reported running gpt-5.4-mini.\n\nAll steps passed.", + ); }); it.effect("ends an orphaned native subagent's node when only its record already ended", () => diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index b444148af4cf8..d060943ec7f2a 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -424,6 +424,7 @@ export interface ThreadManagementServiceShape { >; readonly getThreadShell: Orchestrator.OrchestratorV2["Service"]["getThreadShell"]; readonly listAppOwnedChildThreadIds: Orchestrator.OrchestratorV2["Service"]["listAppOwnedChildThreadIds"]; + readonly getThreadLinkMetadata: Orchestrator.OrchestratorV2["Service"]["getThreadLinkMetadata"]; readonly getThreadTitles: Orchestrator.OrchestratorV2["Service"]["getThreadTitles"]; /** Omit `projectId` to list every project's threads. Side chats are never listed. */ readonly listProjectThreads: (input: { @@ -1610,6 +1611,7 @@ const make = Effect.gen(function* () { }, ), getThreadTitles: orchestrator.getThreadTitles, + getThreadLinkMetadata: orchestrator.getThreadLinkMetadata, listProjectThreads, sendToThread, assertProviderInstanceEnabled, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index dd5ebfa5ff689..cde562e3e46d2 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -4137,6 +4137,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { "repeated cursor", "missing comments", "thread list truncated", + "hidden reply", ])("wakes a watched thread once: %s", (mode) => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -4212,7 +4213,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { body: "Twelfth reply.", createdAt: "2999-01-01T00:00:02.000Z", }; - const incomplete = mode !== "single page" && mode !== "paginated"; + const incomplete = mode !== "single page" && mode !== "paginated" && mode !== "hidden reply"; let recovering = false; let pagesRead = 0; const reactor = yield* PullRequestWatchReactor.make.pipe( @@ -4243,7 +4244,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { isResolved: false, isOutdated: false, comments: firstTen, - commentCount: 12, + commentCount: mode === "hidden reply" ? 13 : 12, nextCommentsCursor: "after-10", }, ], @@ -4270,7 +4271,11 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { if (!recovering && mode === "missing comments") { return Effect.succeed({ comments: [], nextCursor: null }); } - return Effect.succeed({ comments: [eleventh, twelfth], nextCursor: null }); + return Effect.succeed({ + comments: [eleventh, twelfth], + nextCursor: null, + ...(mode === "hidden reply" ? { hiddenCount: 1 } : {}), + }); }, }), ), diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index b0a1b4ff2c1b4..fdd26137534f0 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -5,6 +5,7 @@ import { OrchestratorMcpFailure, type OrchestratorMcpDelegateTaskInput, type OrchestratorMcpTaskCancelResult, + type OrchestratorMcpThreadRun, type OrchestratorMcpThreadTimelineItem, type OrchestrationV2RemoteTaskChild, type OrchestrationV2Subagent, @@ -24,6 +25,7 @@ import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import type * as Tool from "effect/ai/Tool"; +import { withExecutedModelNote } from "@t3tools/provider-core/server/subagentProjection"; import type * as McpInvocationContext from "../mcp/McpInvocationContext.ts"; import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts"; @@ -259,13 +261,14 @@ const make = Effect.gen(function* () { // the forwarder scopes the launch's, and the record's names it. const key = input.clientRequestId ?? (yield* random.uuidV4()); const task = taskPrompt(input); + const title = input.title ?? parent.thread.title; const launched = yield* forwarding.call( scope, ProjectToolkit.tools.t3_thread_launch, target.environmentId, { projectId, - title: input.title ?? parent.thread.title, + title, modelSelection: { instanceId, model, ...(options === undefined ? {} : { options }) }, ...(runtimeMode === undefined ? {} : { runtimeMode }), ...(interactionMode === undefined ? {} : { interactionMode }), @@ -290,6 +293,7 @@ const make = Effect.gen(function* () { environmentId: target.environmentId, threadId: launched.threadId, label: link?.label ?? target.environmentId, + title, ...(launched.runId === null ? {} : { runId: launched.runId }), }; const recorded = yield* threads @@ -436,6 +440,7 @@ const make = Effect.gen(function* () { * The last reply `runId` gave on the task's thread there, which is its * result, read whole however long it is. A failed run prefers its error * from the activity view over an earlier reply, without taking another run's. + * Led by a note when its provider reported running another model than it asked for. */ const lastReply = Effect.fn("RemoteDelegation.lastReply")(function* ( scope: ThreadScope, @@ -446,13 +451,16 @@ const make = Effect.gen(function* () { let reply: OrchestratorMcpThreadTimelineItem | undefined; let error: OrchestratorMcpThreadTimelineItem | undefined; let afterPosition: number | undefined; + let run: OrchestratorMcpThreadRun | undefined; while (true) { const read = yield* forwarding.readThread(scope, remote.environmentId, { threadId: remote.threadId, view: failed ? "activity" : "messages", limit: 100, + runLimit: 50, ...(afterPosition === undefined ? {} : { afterPosition }), }); + run ??= read.recentRuns.find((candidate) => candidate.runId === runId); reply = read.items.findLast( (item) => item.type === "assistant_message" && (runId === null || item.runId === runId), @@ -482,7 +490,7 @@ const make = Effect.gen(function* () { text += part.text ?? ""; textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null; } - return text; + return run === undefined ? text : withExecutedModelNote(text, run.model, run.executedModel); }); /** diff --git a/apps/server/src/provider/ClaudeModelCatalog.ts b/apps/server/src/provider/ClaudeModelCatalog.ts index 57132e652ae08..4efca48f253bf 100644 --- a/apps/server/src/provider/ClaudeModelCatalog.ts +++ b/apps/server/src/provider/ClaudeModelCatalog.ts @@ -239,6 +239,19 @@ export function resolveClaudeModelSlug(catalog: ClaudeModelCatalog, slugOrAlias: return resolveClaudeCatalogModel(catalog, slugOrAlias)?.model.slug ?? slugOrAlias; } +/** Claude reports dated IDs, such as `claude-opus-4-5-20251101`, that the catalog may not list. */ +export function resolveClaudeReportedModelSlug( + catalog: ClaudeModelCatalog, + reported: string, +): string { + return ( + ( + resolveClaudeCatalogModel(catalog, reported) ?? + resolveClaudeCatalogModel(catalog, reported.replace(/-\d{8}$/, "")) + )?.model.slug ?? reported + ); +} + export function getClaudeCatalogModelCapabilities( catalog: ClaudeModelCatalog, slugOrAlias: string | null | undefined, diff --git a/apps/server/src/provider/Drivers/ClaudeAgentSdk.ts b/apps/server/src/provider/Drivers/ClaudeAgentSdk.ts index c379c9f8d2dcc..1343214d9bf52 100644 --- a/apps/server/src/provider/Drivers/ClaudeAgentSdk.ts +++ b/apps/server/src/provider/Drivers/ClaudeAgentSdk.ts @@ -42,6 +42,7 @@ const SUPPORTED_QUERY_OPTIONS: ReadonlySet = new Set([ "pathToClaudeCodeExecutable", "permissionMode", "persistSession", + "promptSuggestions", "resume", "resumeSessionAt", "sessionId", @@ -119,6 +120,9 @@ export function toClaudeCliOptions(options: Sdk.Options): Cli.Options { ...(options.onUserDialog ? { onUserDialog: options.onUserDialog } : {}), ...(options.permissionMode ? { permissionMode: options.permissionMode } : {}), ...(options.persistSession === false ? { persistSession: false } : {}), + ...(options.promptSuggestions !== undefined + ? { promptSuggestions: options.promptSuggestions } + : {}), ...(options.resume ? { resume: options.resume } : {}), ...(options.resumeSessionAt ? { resumeSessionAt: options.resumeSessionAt } : {}), ...(options.sessionId ? { sessionId: options.sessionId } : {}), diff --git a/apps/server/src/provider/Drivers/ClaudeCli.test.ts b/apps/server/src/provider/Drivers/ClaudeCli.test.ts index aac7394fb082e..9d0735d49ecbf 100644 --- a/apps/server/src/provider/Drivers/ClaudeCli.test.ts +++ b/apps/server/src/provider/Drivers/ClaudeCli.test.ts @@ -561,7 +561,8 @@ it("serves MCP Apps' control requests with the Agent SDK 0.3.316 wire shapes", a const directory = await NodeFS.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-claude-mcp-apps-")); const executable = NodePath.join(directory, "fake-claude"); // Answers only the SDK's shapes: mcp_status, mcp_read_resource { serverName, uri }, the raw - // mcp_call and list_permission_rules requests, and an initialize that carries the title. + // mcp_call and list_permission_rules requests, and an initialize that carries the title and + // prompt suggestions. await NodeFS.writeFile( executable, `#!/usr/bin/env node @@ -572,7 +573,9 @@ createInterface({ input: process.stdin }).on("line", (line) => { const request = value.request; const keys = Object.keys(request).sort().join(","); const response = - request.subtype === "initialize" && request.title === "Named thread" + request.subtype === "initialize" && + request.title === "Named thread" && + request.promptSuggestions === true ? {} : request.subtype === "mcp_status" && keys === "subtype" ? { mcpServers: [{ name: "docs", status: "connected", tools: [{ name: "show" }] }] } @@ -603,7 +606,12 @@ createInterface({ input: process.stdin }).on("line", (line) => { prompt: (async function* (): AsyncGenerator { await promptFinished; })(), - options: { pathToClaudeCodeExecutable: executable, env: process.env, title: "Named thread" }, + options: { + pathToClaudeCodeExecutable: executable, + env: process.env, + title: "Named thread", + promptSuggestions: true, + }, }); try { await runtime.initializationResult(); diff --git a/apps/server/src/provider/Drivers/ClaudeCli.ts b/apps/server/src/provider/Drivers/ClaudeCli.ts index a134ba1dd4b49..2db0c6dd3455b 100644 --- a/apps/server/src/provider/Drivers/ClaudeCli.ts +++ b/apps/server/src/provider/Drivers/ClaudeCli.ts @@ -99,6 +99,8 @@ export type Options = { readonly supportedDialogKinds?: ReadonlyArray; /** Sent in `initialize`, as the SDK does; a titled session skips Claude's own naming request. */ readonly title?: string; + /** Sent in `initialize`, as the SDK does; the CLI then emits `prompt_suggestion` messages. */ + readonly promptSuggestions?: boolean; readonly systemPrompt?: { readonly type: "preset"; readonly preset: "claude_code"; @@ -534,6 +536,9 @@ class ClaudeCliQuery implements Query { ? { supportedDialogKinds: options.supportedDialogKinds } : {}), ...(options.title !== undefined ? { title: options.title } : {}), + ...(options.promptSuggestions !== undefined + ? { promptSuggestions: options.promptSuggestions } + : {}), }).then((response) => response as SDKControlInitializeResponse); this.initialization.catch(() => undefined); this.pumpPrompt(prompt); diff --git a/apps/server/src/secrets/SecretRequests.test.ts b/apps/server/src/secrets/SecretRequests.test.ts index d7a636613973a..558b4077d99bb 100644 --- a/apps/server/src/secrets/SecretRequests.test.ts +++ b/apps/server/src/secrets/SecretRequests.test.ts @@ -110,6 +110,7 @@ const withService = ( type: "secret_request", label: "GitHub token", reason: "Used as GH_TOKEN.", + url: "https://github.com/settings/tokens", ...(options.delivery === undefined ? {} : { delivery: options.delivery }), secretStatus, }, @@ -155,6 +156,7 @@ it.effect("a saved answer becomes a one-use ref, and the thread only learns it w assert.include(dispatched[0] as object, { type: "secret_request.record", secretStatus: "saved", + url: "https://github.com/settings/tokens", }); assert.notInclude(Object.values(dispatched[0] as object).map(String), "ghp_secret"); @@ -552,6 +554,12 @@ it.effect("a pasted secret keeps its exact bytes from the tool input to the file value: "", }); assert.isTrue(Exit.isFailure(empty)); + for (const url of ["https://?state=x", "javascript:alert(1)"]) { + assert.isTrue( + Exit.isFailure(decodeSecretInputExit({ label: "Code", reason: "Sign in.", url })), + url, + ); + } const file = yield* withService( ({ service }) => service.savePasted({ diff --git a/apps/server/src/secrets/SecretRequests.ts b/apps/server/src/secrets/SecretRequests.ts index 4d4c2aec64414..75f99327c1c9d 100644 --- a/apps/server/src/secrets/SecretRequests.ts +++ b/apps/server/src/secrets/SecretRequests.ts @@ -144,6 +144,7 @@ const make = Effect.gen(function* () { turnItemId: item.id, label: item.label, reason: item.reason, + ...(item.url === undefined ? {} : { url: item.url }), ...(item.placeholder === undefined ? {} : { placeholder: item.placeholder }), ...(item.delivery === undefined ? {} : { delivery: item.delivery }), secretStatus, diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index 68e3a02e49f2d..bec2044dd70a6 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -6,6 +6,7 @@ import { ProjectId, ProjectScript, ProviderDriverKind, + type ProviderInstanceEnvironment, ProviderInstanceId, resolveProviderInstanceEnabled, SecretProviderId, @@ -1241,6 +1242,114 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("server settings" }).pipe(Effect.provide(layerServerSettings())), ); + it.effect.each( + [ + { label: "redacted then empty sensitive", duplicate: { value: "", sensitive: true } }, + { + label: "empty sensitive then redacted", + duplicate: { value: "", sensitive: true }, + redactedLast: true, + }, + { label: "redacted then plain", duplicate: { value: "plain-foo", sensitive: false } }, + { + label: "plain then redacted", + duplicate: { value: "plain-foo", sensitive: false }, + redactedLast: true, + }, + { + label: "secret reference then redacted", + duplicate: { + value: { provider: SecretProviderId.make("personal"), reference: "op://Private/FOO" }, + sensitive: true, + }, + redactedLast: true, + }, + { + label: "inline seed, redacted then empty sensitive", + duplicate: { value: "", sensitive: true }, + inline: '[{"name":"FOO","value":"stored-foo","sensitive":true}]', + }, + { + label: "inline seed with an empty duplicate, redacted then empty sensitive", + duplicate: { value: "", sensitive: true }, + inline: + '[{"name":"FOO","value":"stored-foo","sensitive":true},{"name":"FOO","value":"","sensitive":true}]', + }, + { + label: "inline seed with an empty duplicate, new value then redacted", + duplicate: { value: "new-foo", sensitive: true }, + redactedLast: true, + inline: + '[{"name":"FOO","value":"stored-foo","sensitive":true},{"name":"FOO","value":"","sensitive":true}]', + expected: "new-foo", + }, + ].map((testCase) => [testCase.label, testCase] as const), + )( + "keeps a stored secret a redacted row still claims when a duplicate name is saved (%s)", + ([, { duplicate, redactedLast, inline, expected = "stored-foo" }]) => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + const instanceId = ProviderInstanceId.make("codex_personal"); + const save = (environment: ProviderInstanceEnvironment) => + service.updateSettings({ + providerInstances: { + [instanceId]: { driver: ProviderDriverKind.make("codex"), environment, config: {} }, + }, + }); + if (inline) { + const config = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + yield* fs.writeFileString( + config.settingsPath, + `{"providerInstances":{"codex_personal":{"driver":"codex","environment":${inline},"config":{}}}}`, + ); + yield* service.getSettings; + } else { + yield* save([{ name: "FOO", value: "stored-foo", sensitive: true }]); + } + const redacted = { name: "FOO", value: "", sensitive: true, valueRedacted: true }; + const copy = { name: "FOO", ...duplicate }; + yield* save(redactedLast ? [copy, redacted] : [redacted, copy]); + + const reloaded = yield* Effect.gen(function* () { + const fresh = yield* ServerSettingsModule.ServerSettingsService; + return yield* fresh.getSettings; + }).pipe( + Effect.provide( + // Coder: managed policy is cut, so settings need only the secret store. + Layer.fresh(ServerSettingsModule.layer).pipe(Layer.provide(ServerSecretStore.layer)), + ), + ); + assert.equal( + reloaded.providerInstances[instanceId]?.environment?.[redactedLast ? 1 : 0]?.value, + expected, + ); + }).pipe(Effect.provide(layerServerSettings())), + ); + + it.effect("removes a kept secret once every row with its name is deleted", () => + Effect.gen(function* () { + const service = yield* ServerSettingsModule.ServerSettingsService; + const store = yield* ServerSecretStore.ServerSecretStore; + const instanceId = ProviderInstanceId.make("codex_personal"); + const save = (environment: ProviderInstanceEnvironment) => + service.updateSettings({ + providerInstances: { + [instanceId]: { driver: ProviderDriverKind.make("codex"), environment, config: {} }, + }, + }); + yield* save([{ name: "FOO", value: "stored-foo", sensitive: true }]); + yield* save([ + { name: "FOO", value: "", sensitive: true, valueRedacted: true }, + { name: "FOO", value: "plain-foo", sensitive: false }, + ]); + const secretName = "provider-env-Y29kZXhfcGVyc29uYWw-Rk9P"; + assert.isTrue(Option.isSome(yield* store.get(secretName))); + yield* save([]); + assert.isTrue(Option.isNone(yield* store.get(secretName))); + }).pipe(Effect.provide(layerServerSettingsWithSecrets())), + ); + it.effect.each([true, false])( "preserves duplicate secret operation order (sensitive last: %s)", (sensitiveLast) => diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index f57df2e5f704d..a11ef718ab33b 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -968,13 +968,22 @@ const make = Effect.gen(function* () { const persistSettingsSecrets = (current: ServerSettings, next: ServerSettings) => Effect.sync(() => { + // Only sensitive rows own a stored secret; a plain duplicate must not hide one from cleanup. const previous = new Map(); + const inlineValues = new Map(); mapSettingsSecrets(current, (secret) => { + if (!secret.sensitive) return secret; previous.set(secret.secretName, secret); + if (!secret.redacted && secret.value.length > 0) { + inlineValues.set(secret.secretName, secret.value); + } return secret; }); const changes: SecretChange[] = []; const nextSecretNames = new Set(); + const keptSecretNames = new Set(); + const writtenSecretNames = new Set(); + const inlineWrites = new Map(); const settings = mapSettingsSecrets(withEchoedSecretReferences(current, next), (secret) => { const metadata = { secretName: secret.secretName, @@ -989,24 +998,34 @@ const make = Effect.gen(function* () { changes.push({ ...metadata, kind: "remove", operation: "remove-secret" }); return { value: secret.value, redacted: false }; } - const old = previous.get(secret.secretName); - const inlineValue = - old?.sensitive && !old.redacted && old.value.length > 0 ? old.value : undefined; - const value = secret.redacted ? inlineValue : secret.value; - if (value === undefined) { + if (secret.redacted) { + keptSecretNames.add(secret.secretName); nextSecretNames.add(secret.secretName); + const inlineValue = inlineValues.get(secret.secretName); + if (inlineValue !== undefined) { + inlineWrites.set(secret.secretName, { + ...metadata, + kind: "write", + value: textEncoder.encode(inlineValue), + }); + } return { value: "", redacted: true }; } - if (value.length === 0) { + if (secret.value.length === 0) { changes.push({ ...metadata, kind: "remove", operation: "remove-secret" }); return { value: "", redacted: false }; } nextSecretNames.add(secret.secretName); - changes.push({ ...metadata, kind: "write", value: textEncoder.encode(value) }); + writtenSecretNames.add(secret.secretName); + changes.push({ ...metadata, kind: "write", value: textEncoder.encode(secret.value) }); return { value: "", redacted: true }; }); + // A legacy inline value only moves to the store when no row in this save replaces it. + for (const [secretName, change] of inlineWrites) { + if (!writtenSecretNames.has(secretName)) changes.push(change); + } for (const secret of previous.values()) { - if (!secret.sensitive || nextSecretNames.has(secret.secretName)) continue; + if (nextSecretNames.has(secret.secretName)) continue; if (changes.some((change) => change.secretName === secret.secretName)) continue; changes.push({ kind: "remove", @@ -1020,7 +1039,13 @@ const make = Effect.gen(function* () { : {}), }); } - return { settings, changes }; + return { + settings, + // A redacted row still claims its stored secret, so a duplicate row must not remove it. + changes: changes.filter( + (change) => change.kind === "write" || !keptSecretNames.has(change.secretName), + ), + }; }); const rollbackSettingsSecretWrites = ( diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index 7ce98c374c1ad..95bea38cab09b 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -33,6 +33,7 @@ import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as TerminalManager from "./terminal/Manager.ts"; import { CodexProviderCapabilitiesV2 } from "./orchestration-v2/Adapters/CodexAdapterV2.ts"; import { ServerActivation } from "./serverActivation.ts"; +import { withWorkspaceLease } from "./workspace/workspaceLease.ts"; import { describe, expect, it } from "@effect/vitest"; import { EventId, @@ -349,6 +350,7 @@ const cleanupFixture = ( let onLiveCheck: Effect.Effect = Effect.void; let outboxStatus: string | null = null; let fullStatusCalls = 0; + let gitInspections = 0; let snapshotReads = 0; let terminalListener: ((event: TerminalMetadataStreamEvent) => Effect.Effect) | undefined; let events: Stream.Stream = Stream.empty; @@ -358,6 +360,7 @@ const cleanupFixture = ( ...git, execute: (input) => Effect.gen(function* () { + gitInspections++; // Before Git's own clean check: inside `git worktree remove`, or on // Windows the same status check the removal makes before deleting. if ( @@ -553,6 +556,7 @@ const cleanupFixture = ( ...paths, }, }) ?? Effect.void, + gitInspections: () => gitInspections, fullStatusCalls: () => fullStatusCalls, snapshotReads: () => snapshotReads, sessionLiveChecks: () => sessionLiveChecks, @@ -2250,6 +2254,67 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.live.each([ + { days: 8, reason: "Inactive for 1 of 8 days" }, + { days: null, reason: "No rules apply" }, + ])("keeps an ineligible age/delete-only worktree without Git ($days)", ({ days, reason }) => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* cleanupFixture({ + ...DEFAULT_SERVER_SETTINGS.storageCleanup, + worktreeAfterDays: days, + worktreeOnDelete: true, + }); + fixture.setThreads([ + shell({ + branch: "feature", + worktreePath: fixture.worktree, + latestUserMessageAt: DateTime.makeUnsafe( + DateTime.toEpochMillis(yield* DateTime.now) - DAY_MS, + ), + }), + ]); + yield* fixture.fs.writeFileString(`${fixture.worktree}/tracked.txt`, "local edit\n"); + const report = yield* fixture.service.runNow; + expect(report.entries[0]).toMatchObject({ + outcome: "kept", + reason, + bytes: null, + }); + expect(fixture.gitInspections()).toBe(0); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }), + ), + ); + it.live("lets a turn acquire the checkout during accounting and protects its new activity", () => + runCleanupTest( + Effect.gen(function* () { + const fixture = yield* pausedMeasurementFixture(); + const cleanup = yield* fixture.service.runNow.pipe(Effect.forkChild); + yield* Deferred.await(fixture.measuring); + yield* withWorkspaceLease( + fixture.worktree, + Effect.sync(() => { + fixture.setThreads([ + shell({ + branch: "feature", + worktreePath: fixture.worktree, + status: "running", + }), + ]); + }), + ); + yield* Deferred.succeed(fixture.resume, undefined); + const report = yield* Fiber.join(cleanup); + expect(report.entries[0]).toMatchObject({ + outcome: "kept", + reason: "Thread activity or shared worktree changed since check", + bytes: null, + }); + expect(yield* fixture.fs.exists(fixture.worktree)).toBe(true); + }), + ), + ); it.live("still removes a worktree when measuring its size fails", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index cb3c7816ca252..0ab5fc7081923 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -836,6 +836,20 @@ const make = Effect.gen(function* () { ); if (root !== null && !isFilesystemRoot(root, path)) roots.push(root); } + const worktreePathReason = Effect.fn("StorageCleanup.worktreePathReason")(function* ( + worktreePath: string, + ) { + // Allow symlinked parents, never a symlinked worktree directory. + const realPath = yield* fs.realPath(worktreePath); + const realParent = yield* fs.realPath(path.dirname(worktreePath)); + if (realPath !== path.join(realParent, path.basename(worktreePath))) + return "worktree is a symbolic link"; + if (!roots.some((root) => inside(root, realPath))) + return "outside the managed worktree folder"; + if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File") + return "not a linked worktree"; + return null; + }); const deletedRows = yield* sql<{ payload_json: string; workspaceRoot: string }>` SELECT t.payload_json, p.workspace_root AS "workspaceRoot" FROM orchestration_v2_projection_threads t @@ -924,21 +938,6 @@ const make = Effect.gen(function* () { if (group.some((member) => member.branch !== thread.branch)) return keep("a subagent thread's branch differs from this worktree's branch"); if (hasTerminal(worktreePath)) return keep(waitForStop("open terminal")); - // Compare canonical roots while allowing symlinked parents, never symlinked worktree directories. - const realPath = yield* fs.realPath(worktreePath); - const realParent = yield* fs.realPath(path.dirname(worktreePath)); - if (realPath !== path.join(realParent, path.basename(worktreePath))) - return keep("worktree is a symbolic link"); - if (!roots.some((root) => inside(root, realPath))) - return keep("outside the managed worktree folder"); - if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects])) - return keep("contains a project checkout"); - if ((yield* fs.stat(path.join(worktreePath, ".git"))).type !== "File") - return keep("not a linked worktree"); - if (yield* branchChanged(worktreePath, thread.branch)) - return keep("repository or branch changed"); - const changes = yield* localChangesReason(worktreePath, settings); - if (changes !== null) return keep(changes); if ( [...group, ...settlementChain.slice(1)].some( (member) => @@ -948,7 +947,6 @@ const make = Effect.gen(function* () { ) ) return keep(waitForStop("settled moments ago")); - const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }); const old = !deleted && settings.worktreeAfterDays !== null && @@ -968,7 +966,31 @@ const make = Effect.gen(function* () { : old ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} days` : `settled for ${settledDays} days`; - if (!eligible && (settings.worktreeUnchanged || settings.worktreeOnMerge)) { + const notDueReason = + !deleted && settings.worktreeAfterDays !== null + ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days` + : settings.worktreeSettledAfterDays !== null + ? settledFor === null + ? "not settled" + : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days` + : settings.worktreeOnMerge + ? "not merged" + : settings.worktreeUnchanged + ? "has commits beyond the default branch" + : "no rules apply"; + // Only Git-based rules can make a not-yet-due worktree eligible, so skip Git otherwise. + if (!eligible && !settings.worktreeUnchanged && !settings.worktreeOnMerge) + return keep(notDueReason); + const pathReason = yield* worktreePathReason(worktreePath); + if (pathReason !== null) return keep(pathReason); + if (yield* containsProjectRoot(worktreePath, [project, ...snapshot.projects])) + return keep("contains a project checkout"); + if (yield* branchChanged(worktreePath, thread.branch)) + return keep("repository or branch changed"); + const changes = yield* localChangesReason(worktreePath, settings); + if (changes !== null) return keep(changes); + const head = yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" }); + if (!eligible) { const repositoryCwd = path.resolve(project.workspaceRoot); const remotes = yield* git.execute({ operation: "StorageCleanup.listRemotes", @@ -1063,18 +1085,7 @@ const make = Effect.gen(function* () { } if (!eligible && remote === null) return keep("has commits beyond the project branch"); } - if (!eligible) - return keep( - !deleted && settings.worktreeAfterDays !== null - ? `inactive for ${Math.floor((now - activityAt) / DAY_MS)} of ${settings.worktreeAfterDays} days` - : settings.worktreeSettledAfterDays !== null - ? settledFor === null - ? "not settled" - : `settled for ${settledDays} of ${settings.worktreeSettledAfterDays} days` - : settings.worktreeOnMerge - ? "not merged" - : "has commits beyond the default branch", - ); + if (!eligible) return keep(notDueReason); // Re-read this path's threads and sessions so new activity cancels removal; full per-worktree snapshots take seconds. const blockedSinceCheck = Effect.fnUntraced(function* () { const latestProjects = yield* projectStore.listShells(); @@ -1165,53 +1176,61 @@ const make = Effect.gen(function* () { }); const blocked = yield* blockedSinceCheck(); if (blocked !== null) return keep(blocked); + // Size is an estimate; provider startup must not wait for directory traversal. const bytes = yield* measureWorktree(worktreePath); - const blockedWhileMeasuring = yield* blockedSinceCheck(); - if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring); - if (yield* branchChanged(worktreePath, thread.branch)) - return keep("repository or branch changed since check"); - if ( - (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !== - head.commitSha - ) - return keep("commit changed since check"); - const finalChanges = yield* localChangesReason(worktreePath, settings); - if (finalChanges !== null) return keep(finalChanges); - const currentSettings = yield* settingsService.getSettings; - const current = resolveWorktreeCleanup(currentSettings, thread.projectId); - if ( - currentSettings.autoResumeLimitedThreads !== serverSettings.autoResumeLimitedThreads || - currentSettings.snoozeLimitedThreads !== serverSettings.snoozeLimitedThreads || - Object.keys(settings).some( - (key) => - current[key as keyof typeof settings] !== settings[key as keyof typeof settings], - ) - ) - return keep("settings changed since check"); - // Clean only untracked files. Ordinary worktrees retain Git's final tracked-edit check. - if (settings.worktreeKeepWhen === "tracked-changes") - yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean"); - const submodules = yield* submoduleRemoval(worktreePath, settings); - if (submodules.reason !== null) return keep(submodules.reason); - if (submodules.force) { - const changes = yield* localChangesReason(worktreePath, settings); - if (changes !== null) return keep(changes); - } - yield* removeLinkedWorktree({ - operation: "StorageCleanup.cleanupGit", - cwd: project.workspaceRoot, + yield* withWorkspaceLease( worktreePath, - // Git requires force for submodules; recursive checks above cannot make removal atomic. - force: submodules.force, - execute: git.execute, - run: (args) => cleanupGit(project.workspaceRoot, [...args], "git worktree remove"), - }); - entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes }); - yield* gitManager.invalidateStatus(project.workspaceRoot); - // Preserve branch/path so ProviderTurnStartService can recreate the checkout on resume. - yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id }); + Effect.gen(function* () { + const pathReason = yield* worktreePathReason(worktreePath); + if (pathReason !== null) return keep(pathReason); + const blockedWhileMeasuring = yield* blockedSinceCheck(); + if (blockedWhileMeasuring !== null) return keep(blockedWhileMeasuring); + if (yield* branchChanged(worktreePath, thread.branch)) + return keep("repository or branch changed since check"); + if ( + (yield* git.resolveCommit({ cwd: worktreePath, revision: "HEAD" })).commitSha !== + head.commitSha + ) + return keep("commit changed since check"); + const finalChanges = yield* localChangesReason(worktreePath, settings); + if (finalChanges !== null) return keep(finalChanges); + const currentSettings = yield* settingsService.getSettings; + const current = resolveWorktreeCleanup(currentSettings, thread.projectId); + if ( + currentSettings.autoResumeLimitedThreads !== + serverSettings.autoResumeLimitedThreads || + currentSettings.snoozeLimitedThreads !== serverSettings.snoozeLimitedThreads || + Object.keys(settings).some( + (key) => + current[key as keyof typeof settings] !== settings[key as keyof typeof settings], + ) + ) + return keep("settings changed since check"); + // Clean only untracked files. Ordinary worktrees retain Git's final tracked-edit check. + if (settings.worktreeKeepWhen === "tracked-changes") + yield* cleanupGit(worktreePath, ["clean", "-ffdx"], "git clean"); + const submodules = yield* submoduleRemoval(worktreePath, settings); + if (submodules.reason !== null) return keep(submodules.reason); + if (submodules.force) { + const changes = yield* localChangesReason(worktreePath, settings); + if (changes !== null) return keep(changes); + } + yield* removeLinkedWorktree({ + operation: "StorageCleanup.cleanupGit", + cwd: project.workspaceRoot, + worktreePath, + // Git requires force for submodules; recursive checks above cannot make removal atomic. + force: submodules.force, + execute: git.execute, + run: (args) => cleanupGit(project.workspaceRoot, [...args], "git worktree remove"), + }); + entries.push({ ...entry, outcome: "removed", reason: sentence(removalReason), bytes }); + yield* gitManager.invalidateStatus(project.workspaceRoot); + // Preserve branch/path so ProviderTurnStartService can recreate the checkout on resume. + yield* Effect.logInfo("storage cleanup removed worktree", { threadId: thread.id }); + }), + ); }).pipe( - (effect) => withWorkspaceLease(worktreePath, effect), Effect.catch((error) => Effect.gen(function* () { entries.push({ diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index fce3c5f3e69d6..4b3435585970e 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -2138,6 +2138,25 @@ it.layer( }), ); + it.effect("starts bash as a login shell on macOS only", () => + Effect.gen(function* () { + for (const [platform, shell, args] of [ + ["darwin", "/bin/bash", ["-l"]], + ["darwin", "/opt/homebrew/bin/bash", ["-l"]], + ["linux", "/bin/bash", undefined], + ["win32", "C:\\Program Files\\Git\\bin\\bash.exe", undefined], + ["darwin", "/bin/zsh", ["-o", "nopromptsp"]], + ["linux", "/bin/zsh", ["-o", "nopromptsp"]], + ["win32", "pwsh.exe", ["-NoLogo"]], + ] as const) { + const { manager, ptyAdapter } = yield* createManager(5, { + shellResolver: () => shell, + }).pipe(Effect.provide(layerWithHostPlatform(platform))); + yield* manager.open(openInput()); + expect.soft(ptyAdapter.spawnInputs[0]?.args, `${platform} ${shell}`).toEqual(args); + } + }), + ); it.effect("removes terminal metadata subscriptions when initial delivery fails", () => Effect.gen(function* () { const { manager } = yield* createManager(); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 466168ec5633d..4383bda4b55cb 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -571,6 +571,10 @@ function shellCandidateFromCommand( if (platform !== "win32" && shellName === "zsh") { return { shell: command, args: ["-o", "nopromptsp"] }; } + // Login shells load ~/.bash_profile, matching macOS terminal startup. + if (platform === "darwin" && shellName === "bash") { + return { shell: command, args: ["-l"] }; + } return { shell: command }; } diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 9b3ba69ef7a22..cf01e452351e7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -4338,13 +4338,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("flattens a generated name when a branch at its parent path blocks it", () => + it.effect.each(["t3", "T3"])("flattens a generated name when parent %s blocks it", (parent) => Effect.gen(function* () { const cwd = yield* makeTmpDir(); yield* initRepoWithCommit(cwd); const driver = yield* GitVcsDriver.GitVcsDriver; // A local `t3` branch is why launches start on the flat `t3-` temporary branch. - yield* git(cwd, ["branch", "t3"]); + yield* git(cwd, ["branch", parent]); yield* git(cwd, ["checkout", "-b", "t3-abcd1234"]); yield* git(cwd, ["branch", "t3-fix-login"]); @@ -4359,26 +4359,112 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("skips a flattened name that a nested branch blocks", () => + it.effect.each(["t3-fix-login/child", "T3-Fix-Login/child", "T3-FIX-LOGIN"])( + "skips a flattened name blocked by %s", + (occupied) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* git(cwd, ["branch", "t3"]); + yield* git(cwd, ["checkout", "-b", "t3-abcd1234"]); + yield* git(cwd, ["branch", occupied]); + + const renamed = yield* driver.renameBranch({ + cwd, + oldBranch: "t3-abcd1234", + newBranch: "t3/fix-login", + }); + + assert.equal(renamed.branch, "t3-fix-login-1"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3-fix-login-1"); + }), + ); + + it.effect("refuses exhausted automatic suffixes without changing existing branches", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); + const { initialBranch } = yield* initRepoWithCommit(cwd); const driver = yield* GitVcsDriver.GitVcsDriver; - yield* git(cwd, ["branch", "t3"]); - yield* git(cwd, ["checkout", "-b", "t3-abcd1234"]); - yield* git(cwd, ["branch", "t3-fix-login/child"]); - - const renamed = yield* driver.renameBranch({ - cwd, - oldBranch: "t3-abcd1234", - newBranch: "t3/fix-login", - }); - - assert.equal(renamed.branch, "t3-fix-login-1"); - assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3-fix-login-1"); + const oid = yield* git(cwd, ["rev-parse", "HEAD"]); + for (let index = 0; index <= 100; index += 1) { + yield* git(cwd, [ + "update-ref", + `refs/heads/${index === 0 ? "topic" : `topic-${index}`}`, + oid, + ]); + } + const result = yield* driver + .renameBranch({ cwd, oldBranch: initialBranch, newBranch: "topic" }) + .pipe(Effect.result); + assert.isTrue(Result.isFailure(result)); + if (Result.isFailure(result)) + assert.include(result.failure.detail, "Could not find an available branch name"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + assert.equal((yield* driver.listLocalBranchNames(cwd)).length, 102); }), ); + it.effect.each(["rename", "createWorktree"] as const)( + "preserves a concurrent creator's branch when %s loses the atomic ref operation", + (operation) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const expected = yield* git(cwd, [ + "commit-tree", + "HEAD^{tree}", + "-m", + "concurrent winner", + ]); + const original = yield* GitVcsDriver.GitVcsDriver; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let claimed = false; + const spawner = ChildProcessSpawner.make((command) => + Effect.gen(function* () { + if ( + !claimed && + ChildProcess.isStandardCommand(command) && + command.args[0] === "branch" && + command.args.includes(operation === "rename" ? "-m" : "--no-track") + ) { + claimed = true; + yield* original + .execute({ + cwd, + operation: "test.concurrentCreator", + args: ["update-ref", "refs/heads/topic", expected, ""], + }) + .pipe(Effect.orDie); + } + return yield* delegate.spawn(command); + }), + ); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.provide(layerServerConfig), + ); + const result = yield* ( + operation === "rename" + ? driver + .renameBranch({ cwd, oldBranch: initialBranch, newBranch: "topic" }) + .pipe(Effect.asVoid) + : driver + .createWorktree({ + cwd, + refName: initialBranch, + newRefName: "topic", + path: NodePath.join(cwd, "checkout"), + }) + .pipe(Effect.asVoid) + ).pipe(Effect.result); + assert.isTrue(claimed); + assert.isTrue(Result.isFailure(result)); + assert.equal(yield* git(cwd, ["rev-parse", "refs/heads/topic"]), expected); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + }), + ); + it.effect("rejects a missing branch without restoring a matching dirty file", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -4975,13 +5061,15 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { { cwd, path: null, refName: initialBranch, newRefName: "feature/custom-dir" }, { worktreesDirectory }, ); - const expected = pathService.join( - worktreesDirectory, - pathService.basename(cwd), - "feature-custom-dir", + assert.equal( + pathService.dirname(created.worktree.path), + pathService.join(worktreesDirectory, pathService.basename(cwd)), + ); + assert.match( + pathService.basename(created.worktree.path), + /^feature-custom-dir-[0-9a-f]{16}$/, ); - assert.equal(created.worktree.path, expected); - assert.equal(yield* fileSystem.exists(expected), true); + assert.equal(yield* fileSystem.exists(created.worktree.path), true); const error = yield* driver .createWorktree( @@ -5001,6 +5089,33 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "keeps generated paths distinct across branch spellings and equal repository basenames", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* makeTmpDir(); + const worktreesDirectory = yield* makeTmpDir(); + const driver = yield* GitVcsDriver.GitVcsDriver; + const paths = new Set(); + for (const owner of ["one", "two"]) { + const cwd = path.join(root, owner, "repository"); + yield* fs.makeDirectory(cwd, { recursive: true }); + const { initialBranch } = yield* initRepoWithCommit(cwd); + for (const branch of ["feat/a", "feat-a"]) { + const created = yield* driver.createWorktree( + { cwd, path: null, refName: initialBranch, newRefName: branch }, + { worktreesDirectory }, + ); + paths.add(created.worktree.path); + assert.equal(yield* git(created.worktree.path, ["branch", "--show-current"]), branch); + } + } + assert.equal(paths.size, 4); + }), + ); + it.effect("keeps generated worktree folders short without changing long branch names", () => Effect.gen(function* () { const pathService = yield* Path.Path; @@ -5015,6 +5130,8 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { `feature/${"a".repeat(40)}/5fac`, `feature/${"a".repeat(40)}/18828`, `${"a".repeat(22)}😀/${"b".repeat(30)}`, + "😀".repeat(60), + "界".repeat(80), "z".repeat(40), "z".repeat(41), ]; @@ -5024,8 +5141,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { { worktreesDirectory }, ); const folder = pathService.basename(created.worktree.path); - assert.isAtMost(folder.length, 40); - if (branch.length <= 40) assert.equal(folder, branch); + assert.isAtMost(Buffer.byteLength(folder), 40); assert.equal(yield* git(created.worktree.path, ["branch", "--show-current"]), branch); assert.include( yield* git(cwd, ["-c", "core.quotePath=false", "worktree", "list", "--porcelain"]), diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index e642faf0f66a1..ef817f92e292b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1249,38 +1249,38 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd: string, requestedBranch: string, ) { - // A branch at a parent path (such as `t3`) blocks every ref nested under it, so no suffix - // would help; flatten to a sibling the way temporary worktree branches already do. - const segments = requestedBranch.split("/"); - let blockedByParent = false; - for (let index = 1; index < segments.length && !blockedByParent; index += 1) { - blockedByParent = yield* branchExists(cwd, segments.slice(0, index).join("/")); + // Exceeding the limit fails the command, so the set is never built from a partial list. + const { stdout } = yield* executeGit( + "GitVcsDriver.resolveAvailableBranchName", + cwd, + ["for-each-ref", "--format=%(refname:strip=2)", "refs/heads/"], + { maxOutputBytes: 16 * 1024 * 1024 }, + ); + // Reserve case variants too: loose refs can live on case-insensitive filesystems. + const branches = new Set( + stdout + .split("\n") + .filter(Boolean) + .map((name) => name.toLowerCase()), + ); + // A branch nested under a name (`t3-fix/child`) blocks it as surely as one with the name. + const blockedNames = new Set(branches); + for (const branch of branches) { + const segments = branch.split("/"); + for (let index = 1; index < segments.length; index += 1) { + blockedNames.add(segments.slice(0, index).join("/")); + } } + // An ancestor ref blocks every suffix beneath it, so flatten to a sibling. + const segments = requestedBranch.split("/"); + const blockedByParent = segments.some( + (_, index) => index > 0 && branches.has(segments.slice(0, index).join("/").toLowerCase()), + ); const desiredBranch = blockedByParent ? segments.join("-") : requestedBranch; - // A branch nested under the name (`t3-fix/child`) blocks it as surely as one with the name. - const isBranchNameTaken = (name: string) => - Effect.zipWith( - branchExists(cwd, name), - runGitStdout( - "GitVcsDriver.branchExists", - cwd, - ["for-each-ref", "--count=1", "--format=%(refname)", `refs/heads/${name}/`], - true, - ), - (exists, nested) => exists || nested.trim().length > 0, - ); - - const isDesiredTaken = yield* isBranchNameTaken(desiredBranch); - if (!isDesiredTaken) { - return desiredBranch; - } - + if (!blockedNames.has(desiredBranch.toLowerCase())) return desiredBranch; for (let suffix = 1; suffix <= 100; suffix += 1) { const candidate = `${desiredBranch}-${suffix}`; - const isCandidateTaken = yield* isBranchNameTaken(candidate); - if (!isCandidateTaken) { - return candidate; - } + if (!blockedNames.has(candidate.toLowerCase())) return candidate; } return yield* new GitCommandError({ @@ -4284,14 +4284,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* detail: `The worktree location "${options?.worktreesDirectory}" must be an absolute folder on this machine, not a drive root. Change it in Settings → Worktrees.`, }); } - let directoryName = targetBranch.replace(/\//g, "-"); - // Leave room for files beneath the worktree on Windows, regardless of branch length. - if (directoryName.length > 40) { - const hash = yield* digest.digest(Digest.sha256, new TextEncoder().encode(targetBranch)); - // Avoid splitting a surrogate pair, which Git would list back as a different path. - const prefix = directoryName.slice(0, 23).replace(/[\uD800-\uDBFF]$/, ""); - directoryName = `${prefix}-${Hex.encode(hash).slice(0, 16)}`; + const identity = `${yield* readGitCommonDir(input.cwd)}\0${targetBranch}`; + const hash = yield* digest.digest(Digest.sha256, new TextEncoder().encode(identity)); + // UTF-8 bytes bound UTF-16 length too, leaving room for files on Windows. + let prefix = ""; + for (const character of targetBranch.replace(/\//g, "-")) { + if (Buffer.byteLength(prefix + character) > 23) break; + prefix += character; } + const directoryName = `${prefix}-${Hex.encode(hash).slice(0, 16)}`; worktreePath = path.join(parentDir, repoName, directoryName); } const newRefName = input.newRefName; diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index b8f06878422ee..f2af7c0ab18ad 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -10,6 +10,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; import * as Scope from "effect/Scope"; import * as Scheduler from "effect/Scheduler"; import * as Stream from "effect/Stream"; @@ -87,6 +88,9 @@ function layerTestFor(state: { automaticFetchInterval?: Effect.Effect; beforeRemoteStatus?: Effect.Effect; beforeLocalStatus?: Effect.Effect; + beforeCurrentBranch?: Effect.Effect; + beforeInvalidate?: Effect.Effect; + branchRead?: () => Effect.Effect; fileSystem?: FileSystem.FileSystem; pullCurrentBranch?: GitWorkflowService.GitWorkflowService["Service"]["pullCurrentBranch"]; }) { @@ -112,7 +116,12 @@ function layerTestFor(state: { Effect.as(state.currentLocalStatus), ); }), - currentBranch: () => Effect.sync(() => state.currentLocalStatus.refName), + currentBranch: () => + state.branchRead + ? state.branchRead() + : (state.beforeCurrentBranch ?? Effect.void).pipe( + Effect.andThen(Effect.sync(() => state.currentLocalStatus.refName)), + ), remoteStatus: (_input, options) => Effect.suspend(() => { return (state.beforeRemoteStatus ?? Effect.void).pipe( @@ -131,7 +140,7 @@ function layerTestFor(state: { invalidateLocalStatus: () => Effect.sync(() => { state.localInvalidationCalls += 1; - }), + }).pipe(Effect.andThen(state.beforeInvalidate ?? Effect.void)), invalidateRemoteStatus: () => Effect.sync(() => { state.remoteInvalidationCalls += 1; @@ -196,6 +205,135 @@ describe("VcsStatusBroadcaster", () => { }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); }); + it.effect( + "streams fresh branch-only reads, detached HEAD, non-repositories, and detailed demand without mixing results", + () => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + fileSystem: FileSystem.makeNoop({ + realPath: (cwd) => Effect.succeed(cwd === "/alias" ? "/repo" : cwd), + }), + }; + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const branches = yield* Stream.toPull(broadcaster.streamBranchStatus({ cwd: "/repo" })); + assert.deepEqual(yield* branches, [{ refName: baseLocalStatus.refName }]); + assert.equal(state.localStatusCalls, 0); + state.currentLocalStatus = { ...baseLocalStatus, refName: "external" }; + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + assert.deepEqual(yield* branches, [{ refName: "external" }]); + state.currentLocalStatus = { ...baseLocalStatus, refName: null }; + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + assert.deepEqual(yield* branches, [{ refName: null }]); + assert.equal(state.localStatusCalls, 0); + const detailScope = yield* Scope.make(); + const details = yield* Stream.toPull( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + ).pipe(Scope.provide(detailScope)); + assert.deepEqual(yield* details, [ + { _tag: "snapshot", local: state.currentLocalStatus, remote: null }, + ]); + const callsWithDetail = state.localStatusCalls; + const extraBranches = yield* Stream.toPull( + broadcaster.streamBranchStatus({ cwd: "/repo" }), + ); + yield* extraBranches; + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + assert.equal(state.localStatusCalls, callsWithDetail); + state.currentLocalStatus = { + ...baseLocalStatus, + refName: "changed", + workingTree: { files: [], insertions: 12, deletions: 3 }, + }; + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + assert.deepEqual(yield* details, [ + { _tag: "localUpdated", local: state.currentLocalStatus }, + ]); + assert.deepEqual(yield* branches, [{ refName: "changed" }]); + const secondScope = yield* Scope.make(); + const secondDetails = yield* Stream.toPull( + broadcaster.streamStatus({ cwd: "/alias", includeRemote: false }), + ).pipe(Scope.provide(secondScope)); + yield* secondDetails; + yield* Scope.close(detailScope, Exit.void); + state.currentLocalStatus = { + ...state.currentLocalStatus, + workingTree: { files: [], insertions: 20, deletions: 4 }, + }; + yield* broadcaster.refreshLocalStatus("/repo"); + assert.deepEqual(yield* secondDetails, [ + { _tag: "localUpdated", local: state.currentLocalStatus }, + ]); + yield* Scope.close(secondScope, Exit.void); + const callsAfterRelease = state.localStatusCalls; + state.currentLocalStatus = { + ...state.currentLocalStatus, + workingTree: { files: [], insertions: 30, deletions: 5 }, + }; + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + assert.equal(state.localStatusCalls, callsAfterRelease); + const reopened = yield* Stream.toPull( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + ); + assert.deepEqual(yield* reopened, [ + { _tag: "snapshot", local: state.currentLocalStatus, remote: null }, + ]); + state.currentLocalStatus = { + ...baseLocalStatus, + isRepo: false, + refName: null, + }; + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); + assert.deepEqual(yield* reopened, [ + { _tag: "localUpdated", local: state.currentLocalStatus }, + ]); + assert.deepEqual(yield* branches, [{ refName: null }]); + assert.equal(state.remoteStatusCalls, 0); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }, + ); + + it.effect("upgrades an in-flight branch refresh when detailed demand arrives", () => { + const state: Parameters[0] = { + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, + }; + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const reading = yield* Deferred.make(); + const resume = yield* Deferred.make(); + state.beforeCurrentBranch = Deferred.succeed(reading, undefined).pipe( + Effect.andThen(Deferred.await(resume)), + ); + const refresh = yield* broadcaster + .refreshBranchStatus({ cwd: "/repo" }) + .pipe(Effect.forkScoped); + yield* Deferred.await(reading); + const detailsFiber = yield* Stream.runHead( + broadcaster.streamStatus({ cwd: "/repo", includeRemote: false }), + ).pipe(Effect.forkScoped); + state.currentLocalStatus = { + ...baseLocalStatus, + workingTree: { files: [], insertions: 8, deletions: 2 }, + }; + yield* Deferred.succeed(resume, undefined); + yield* Fiber.join(refresh); + assert.deepEqual( + yield* Fiber.join(detailsFiber), + Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }), + ); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }); + it.effect("publishes terminal branch switches and validates cached status reads", () => { const state: Parameters[0] = { currentLocalStatus: baseLocalStatus, @@ -408,6 +546,7 @@ describe("VcsStatusBroadcaster", () => { state.backgroundWorkEnabled = false; state.currentRemoteStatus = { ...remoteStatusWithPr, aheadCount: 7 }; + yield* broadcaster.refreshBranchStatus({ cwd: "/repo" }); const refreshed = yield* broadcaster.refreshPullRequestStatus("/repo"); assert.deepStrictEqual(refreshed, state.currentRemoteStatus); const merged = yield* broadcaster.getStatus({ cwd: "/repo" }); @@ -1353,3 +1492,132 @@ describe("Coder auto-pull policy", () => { }); } }); + +const newState = (): Parameters[0] => ({ + fileSystem: FileSystem.makeNoop({ realPath: (cwd) => Effect.succeed(cwd) }), + currentLocalStatus: baseLocalStatus, + currentRemoteStatus: null, + localStatusCalls: 0, + remoteStatusCalls: 0, + localInvalidationCalls: 0, + remoteInvalidationCalls: 0, +}); +it.effect("detail join during invalidation must get fresh totals", () => { + const state = newState(); + return Effect.gen(function* () { + const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const oldScope = yield* Scope.make(); + const old = yield* Stream.toPull(b.streamStatus({ cwd: "/repo", includeRemote: false })).pipe( + Scope.provide(oldScope), + ); + yield* old; + yield* Scope.close(oldScope, Exit.void); + state.currentLocalStatus = { + ...baseLocalStatus, + workingTree: { files: [], insertions: 42, deletions: 0 }, + }; + const entered = yield* Deferred.make(); + const resume = yield* Deferred.make(); + state.beforeInvalidate = Deferred.succeed(entered, undefined).pipe( + Effect.andThen(Deferred.await(resume)), + ); + const refresh = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped); + yield* Deferred.await(entered); + const snapshotFiber = yield* Stream.runHead( + b.streamStatus({ cwd: "/repo", includeRemote: false }), + ).pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(resume, undefined); + yield* Fiber.join(refresh); + assert.deepEqual( + yield* Fiber.join(snapshotFiber), + Option.some({ _tag: "snapshot" as const, local: state.currentLocalStatus, remote: null }), + ); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); +}); +it.effect("serializes branch reads with detailed refresh publication", () => { + const state = newState(); + return Effect.gen(function* () { + const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const entered = yield* Deferred.make(); + const resume = yield* Deferred.make(); + state.branchRead = () => + Deferred.succeed(entered, undefined).pipe( + Effect.andThen(Deferred.await(resume)), + Effect.as("old"), + ); + const older = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped); + yield* Deferred.await(entered); + state.currentLocalStatus = { ...baseLocalStatus, refName: "new" }; + const newer = yield* b + .refreshLocalStatus("/repo") + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(resume, undefined); + yield* Fiber.join(older); + yield* Fiber.join(newer); + state.branchRead = () => Effect.succeed("new"); + const result = yield* b.getStatus({ cwd: "/repo" }); + assert.equal(result.refName, "new"); + assert.equal(state.localStatusCalls, 1); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); +}); + +it.effect("publishes overlapping branch reads in checkout order", () => { + const state = newState(); + return Effect.gen(function* () { + const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const branches = yield* Stream.toPull(b.streamBranchStatus({ cwd: "/repo" })); + yield* branches; + const entered = yield* Deferred.make(); + const resume = yield* Deferred.make(); + let reads = 0; + state.branchRead = () => + ++reads === 1 + ? Deferred.succeed(entered, undefined).pipe( + Effect.andThen(Deferred.await(resume)), + Effect.as("old"), + ) + : Effect.succeed("new"); + const older = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped); + yield* Deferred.await(entered); + const newer = yield* b + .refreshBranchStatus({ cwd: "/repo" }) + .pipe(Effect.forkScoped({ startImmediately: true })); + yield* Deferred.succeed(resume, undefined); + yield* Fiber.join(older); + yield* Fiber.join(newer); + assert.deepEqual(yield* branches, [{ refName: "old" }, { refName: "new" }]); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); +}); + +it.effect("does not replay older queued branches after a new subscriber snapshot", () => { + const state = newState(); + return Effect.gen(function* () { + const b = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const entered = yield* Deferred.make(); + const resume = yield* Deferred.make(); + const values = yield* Queue.unbounded<{ readonly refName: string | null }>(); + let reads = 0; + state.branchRead = () => + ++reads === 1 + ? Deferred.succeed(entered, undefined).pipe( + Effect.andThen(Deferred.await(resume)), + Effect.as("old"), + ) + : Effect.succeed("new"); + const older = yield* b.refreshBranchStatus({ cwd: "/repo" }).pipe(Effect.forkScoped); + yield* Deferred.await(entered); + const subscriber = yield* b.streamBranchStatus({ cwd: "/repo" }).pipe( + Stream.tap((value) => Queue.offer(values, value)), + Stream.take(2), + Stream.runDrain, + Effect.forkScoped({ startImmediately: true }), + ); + yield* Deferred.succeed(resume, undefined); + yield* Fiber.join(older); + assert.deepEqual(yield* Queue.take(values), { refName: "new" }); + state.branchRead = () => Effect.succeed("latest"); + yield* b.refreshBranchStatus({ cwd: "/repo" }); + assert.deepEqual(yield* Queue.take(values), { refName: "latest" }); + yield* Fiber.join(subscriber); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); +}); diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index 9402d225a61be..83ba243e9d34f 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -19,6 +19,7 @@ import type { // Coder: lightweight sidebar ref status uses the existing Coder RPC contract. VcsRefStatusStreamEvent, VcsStatusInput, + VcsBranchStatus, VcsStatusLocalResult, VcsStatusRemoteResult, VcsStatusResult, @@ -211,6 +212,12 @@ function remoteRefreshFailureDelay( export class VcsStatusBroadcaster extends Context.Service< VcsStatusBroadcaster, { + readonly streamBranchStatus: ( + input: VcsStatusInput, + ) => Stream.Stream; + readonly refreshBranchStatus: ( + input: VcsStatusInput, + ) => Effect.Effect; readonly streamBranchChanges: Stream.Stream<{ readonly cwd: string; readonly refName: string | null; @@ -260,12 +267,32 @@ export const make = Effect.gen(function* () { (pubsub) => PubSub.shutdown(pubsub), ); const branchChangesPubSub = yield* Effect.acquireRelease( - PubSub.unbounded<{ readonly cwd: string; readonly refName: string | null }>(), + PubSub.unbounded<{ + readonly cwd: string; + readonly refName: string | null; + readonly revision: number; + }>(), (pubsub) => PubSub.shutdown(pubsub), ); const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) => Scope.close(scope, Exit.void), ); + const detailedSubscribers = new Map(); + const branches = new Map< + string, + { readonly refName: string | null; readonly revision: number } + >(); + let branchRevision = 0; + const publishBranch = Effect.fn("VcsStatusBroadcaster.publishBranch")(function* ( + cwd: string, + refName: string | null, + ) { + if (branches.get(cwd)?.refName === refName) return; + const revision = ++branchRevision; + branches.set(cwd, { refName, revision }); + yield* PubSub.publish(branchChangesPubSub, { cwd, refName, revision }); + }); + const localRefreshLocks = yield* KeyedLock.make(); const cacheRef = yield* Ref.make(new Map()); // One permit per cwd for remote reads that write the cache. Without it a // periodic poll that started before an agent creates a PR can finish after the @@ -284,21 +311,15 @@ export const make = Effect.gen(function* () { const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")( function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) { const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local }; - const [localChanged, branchChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => { + const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => { const previous = cache.get(cwd) ?? { local: null, remote: null }; const remote = previous.remote?.branch === local.refName ? previous.remote : null; return [ - [ - previous.local?.fingerprint !== nextLocal.fingerprint, - previous.local?.value.refName !== local.refName, - previous.remote !== remote, - ], + [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote], new Map(cache).set(cwd, { local: nextLocal, remote }), ] as const; }); - if (branchChanged && local.isRepo) { - yield* PubSub.publish(branchChangesPubSub, { cwd, refName: local.refName }); - } + yield* publishBranch(cwd, local.refName); if (options?.publish && remoteCleared) { yield* PubSub.publish(changesPubSub, { cwd, @@ -342,24 +363,30 @@ export const make = Effect.gen(function* () { return yield* updateCachedLocalStatus(cwd, local); }); - const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* ( - cwd: string, - ) { - const cached = yield* getCachedStatus(cwd); - if (cached?.local) { - const branch = yield* workflow.currentBranch(cwd); - if (branch === cached.local.value.refName) return cached.local.value; - return yield* refreshLocalStatusCore(cwd); - } - return yield* loadLocalStatus(cwd); - }); + const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")( + function* (cwd: string) { + const cached = yield* getCachedStatus(cwd); + if (cached?.local) { + const branch = yield* workflow.currentBranch(cwd); + if (branch === cached.local.value.refName) return cached.local.value; + yield* workflow.invalidateLocalStatus(cwd); + return yield* updateCachedLocalStatus(cwd, yield* workflow.localStatus({ cwd }), { + publish: true, + }); + } + return yield* loadLocalStatus(cwd); + }, + ); + + const getOrLoadLocalStatus = (cwd: string) => + localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd)); const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) { const cached = yield* getCachedStatus(cwd); if (cached?.local) { return { local: cached.local.value, remote: cached.remote?.value ?? null }; } - return { local: yield* loadLocalStatus(cwd), remote: null }; + return { local: yield* getOrLoadLocalStatus(cwd), remote: null }; }); const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs); @@ -388,7 +415,6 @@ export const make = Effect.gen(function* () { // A refresh that started after a request saw every change that request could mean, so queued // callers share it instead of each running git status again. - const localRefreshLocks = yield* KeyedLock.make(); const localRefreshRequests = new Map(); const localRefreshResults = new Map< string, @@ -566,7 +592,7 @@ export const make = Effect.gen(function* () { cwd, Effect.gen(function* () { const cached = yield* getCachedStatus(cwd); - if (!cached?.local || cached.remote?.value === null) return null; + if (!cached || cached.remote?.value === null) return null; // Turn completion must update divergence even when background polling is paused. const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream: false, @@ -748,6 +774,18 @@ export const make = Effect.gen(function* () { Stream.unwrap( Effect.gen(function* () { const cwd = yield* withFileSystem(normalizeCwd(input.cwd)); + yield* Effect.acquireRelease( + Effect.sync(() => { + const previous = detailedSubscribers.get(cwd) ?? 0; + detailedSubscribers.set(cwd, previous + 1); + }), + () => + Effect.sync(() => { + const remaining = (detailedSubscribers.get(cwd) ?? 1) - 1; + if (remaining === 0) detailedSubscribers.delete(cwd); + else detailedSubscribers.set(cwd, remaining); + }), + ); const subscription = yield* PubSub.subscribe(changesPubSub); const initialLocal = yield* getOrLoadLocalStatus(cwd); const cachedStatus = yield* getCachedStatus(cwd); @@ -810,8 +848,66 @@ export const make = Effect.gen(function* () { }), ); + // Serialize branch publication and cache invalidation with detailed reads and refreshes. + const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")( + (cwd: string) => + localRefreshLocks.withLock( + cwd, + Effect.gen(function* () { + if (detailedSubscribers.has(cwd)) { + const local = yield* getOrLoadLocalStatusUnlocked(cwd); + return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 }; + } + const refName = yield* workflow.currentBranch(cwd); + // HEAD cannot certify working-tree totals, even when it has not moved. + localRefreshResults.delete(cwd); + yield* workflow.invalidateLocalStatus(cwd); + yield* Ref.update(cacheRef, (cache) => { + const previous = cache.get(cwd); + return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache; + }); + if (detailedSubscribers.has(cwd)) { + const local = yield* workflow.localStatus({ cwd }); + yield* updateCachedLocalStatus(cwd, local, { publish: true }); + return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 }; + } + yield* publishBranch(cwd, refName); + return { refName, revision: branches.get(cwd)?.revision ?? 0 }; + }), + ), + ); + + const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn( + "VcsStatusBroadcaster.refreshBranchStatus", + )(function* (input) { + const { refName } = yield* refreshBranchStatusCore( + yield* withFileSystem(normalizeCwd(input.cwd)), + ); + return { refName }; + }); + + const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) => + Stream.unwrap( + Effect.gen(function* () { + const cwd = yield* withFileSystem(normalizeCwd(input.cwd)); + const subscription = yield* PubSub.subscribe(branchChangesPubSub); + const branch = yield* refreshBranchStatusCore(cwd); + return Stream.concat( + Stream.make({ refName: branch.refName }), + Stream.fromSubscription(subscription).pipe( + Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision), + Stream.map(({ refName }) => ({ refName })), + ), + ).pipe(Stream.changesWith((left, right) => left.refName === right.refName)); + }), + ); + return VcsStatusBroadcaster.of({ - streamBranchChanges: Stream.fromPubSub(branchChangesPubSub), + streamBranchStatus, + refreshBranchStatus, + streamBranchChanges: Stream.fromPubSub(branchChangesPubSub).pipe( + Stream.map(({ cwd, refName }) => ({ cwd, refName })), + ), getStatus, refreshLocalStatus, refreshStatus, diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 6410858571684..b1ab7affe2b50 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -554,10 +554,15 @@ it.effect("shell snapshots omit idle children and older settled threads only on // subscribe-before-snapshot order and strips workspace snapshots the same way. Upstream's // failed-publish remote refresh test (#29688) builds the same layer, so it is not carried either. -// Pruned history cannot be replayed: a cursor below the boundary must resync from a snapshot. -it.effect.each(["thread", "shell"] as const)( - "%s resume from a cursor below the pruned boundary loads a snapshot", - (scope) => +// Pruned history cannot be replayed: a cursor below the boundary must resync from a snapshot, +// or, for a shell client that loads it over HTTP, be told to without the server building one. +it.effect.each([ + { scope: "thread", httpSnapshotFallback: false }, + { scope: "shell", httpSnapshotFallback: false }, + { scope: "shell", httpSnapshotFallback: true }, +] as const)( + "$scope resume from a cursor below the pruned boundary (HTTP fallback: $httpSnapshotFallback)", + ({ scope, httpSnapshotFallback }) => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; const now = "2026-10-13T00:00:00.000Z"; @@ -581,11 +586,18 @@ it.effect.each(["thread", "shell"] as const)( ) VALUES (${OrchestrationEventStore.EVENT_LOG_PRUNED_THROUGH}, 2, ${second!.sequence}, ${now}) `; const subscription = Effect.gen(function* () { - const stream = + const items: ReadonlyArray = scope === "thread" - ? yield* subscribeOrchestrationV2Thread({ threadId, afterSequence: first!.sequence }) - : yield* subscribeOrchestrationV2Shell({ afterSequence: first!.sequence }); - return stream; + ? yield* Stream.runCollect( + yield* subscribeOrchestrationV2Thread({ threadId, afterSequence: first!.sequence }), + ) + : yield* Stream.runCollect( + yield* subscribeOrchestrationV2Shell({ + afterSequence: first!.sequence, + ...(httpSnapshotFallback ? { httpSnapshotFallback: true as const } : {}), + }), + ); + return items; }); const exit = yield* subscription.pipe( Effect.provideService(ThreadManagement.ThreadManagementService, { @@ -607,7 +619,10 @@ it.effect.each(["thread", "shell"] as const)( } as ProjectEnrichment.ProjectEnrichmentService["Service"]), Effect.exit, ); - assert.deepEqual(Exit.isFailure(exit) ? Cause.squash(exit.cause) : exit, "snapshot"); + assert.deepEqual( + Exit.isFailure(exit) ? Cause.squash(exit.cause) : Array.from(exit.value), + httpSnapshotFallback ? [{ kind: "snapshot-required" }] : "snapshot", + ); }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index e6d4ee2d33f37..388841db79c63 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -33,6 +33,7 @@ import { type DiscoveredLocalServerList, type OrchestrationProjectShell, type OrchestrationV2ShellSnapshot, + type OrchestrationV2ShellStreamItem, type OrchestrationV2ThreadStreamItem, type ApplicationStoredEvent, type ProjectEntriesFailure, @@ -73,6 +74,7 @@ import * as Keybindings from "./keybindings.ts"; import * as ThreadManagementService from "./orchestration-v2/ThreadManagementService.ts"; import * as CommandOutputHub from "./orchestration-v2/CommandOutputHub.ts"; import * as McpAppRequests from "./mcpApps/McpAppRequests.ts"; +import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; import * as ThreadLaunchService from "./orchestration-v2/ThreadLaunchService.ts"; import * as ThreadMessageIntake from "./orchestration-v2/ThreadMessageIntake.ts"; import * as DocumentText from "./provider/DocumentText.ts"; @@ -671,6 +673,7 @@ export const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subs export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscribeShell")( function* (input: { readonly afterSequence?: number; + readonly httpSnapshotFallback?: true; readonly requestCompletionMarker?: boolean; readonly omitIdleSubagents?: boolean; readonly omitOlderSettled?: boolean; @@ -888,14 +891,20 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc }); } - const fromSnapshot = Effect.gen(function* () { - const loaded = yield* loadSnapshot(); - return composeShellStreamWithEnrichment({ - initial: initialSnapshotItems(loaded), - tail: completionThenLive(loaded.snapshot.snapshotSequence), - enrichment: enrichmentRefreshes, - }); + const snapshotRequired: Stream.Stream = Stream.make({ + kind: "snapshot-required", }); + const fromSnapshot = + input.httpSnapshotFallback === true + ? Effect.succeed(snapshotRequired) + : Effect.gen(function* () { + const loaded = yield* loadSnapshot(); + return composeShellStreamWithEnrichment({ + initial: initialSnapshotItems(loaded), + tail: completionThenLive(loaded.snapshot.snapshotSequence), + enrichment: enrichmentRefreshes, + }); + }); const highWater = yield* applicationEvents.latestApplicationSequence; if (!(yield* canReplayPersistedRange(input.afterSequence, highWater, SHELL_RESUME_MAX_GAP))) { return yield* fromSnapshot; @@ -983,6 +992,7 @@ const layerWsRpc = () => // Coder: helper stdio has no client-origin attribution or analytics. const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; const commandOutputHub = yield* CommandOutputHub.CommandOutputHub; + const providerSessionManager = yield* ProviderSessionManager.ProviderSessionManagerV2; const scheduledTasks = yield* ScheduledTasks.ScheduledTaskService; const secretRequests = yield* SecretRequests.SecretRequests; const pullRequests = yield* PullRequestService.PullRequestService; @@ -1265,6 +1275,7 @@ const layerWsRpc = () => reasoningMessages: true, shellResumeCompletionMarker: true, shellThreadFamilies: true, + threadLinkMetadata: true, shellOlderSettled: true, threadResumeCompletionMarker: true, threadSnapshotPagination: true, @@ -1450,6 +1461,16 @@ const layerWsRpc = () => getOrchestrationV2ArchivedShellSnapshot, [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input) => readOmittableShellRows({ familyOf: input.threadId }, "Failed to load the thread family"), + [ORCHESTRATION_V2_WS_METHODS.getThreadLinkMetadata]: (input) => + threadManagement.getThreadLinkMetadata(input.threadIds).pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed to load thread link metadata", + cause, + }), + ), + ), [ORCHESTRATION_V2_WS_METHODS.getThreadTitles]: (input) => threadManagement.getThreadTitles(input.threadIds).pipe( Effect.mapError( @@ -1596,6 +1617,8 @@ const layerWsRpc = () => Effect.as(commandOutputHub.subscribe(input)), ), ), + [ORCHESTRATION_V2_WS_METHODS.subscribePromptSuggestion]: (input) => + providerSessionManager.subscribePromptSuggestion(input.threadId), // Coder: helper stdio has no session scopes, so every webhook URL is visible. [WS_METHODS.scheduledTasksSubscribe]: (_input) => scheduledTasks.subscribeList(), [WS_METHODS.scheduledTasksUpsert]: (input) => scheduledTasks.upsert(input), @@ -2043,6 +2066,9 @@ const layerWsRpc = () => }); }), // Coder: no assets.persistChatAttachments; composer uploads use the signed upload URL. + [WS_METHODS.subscribeVcsBranch]: (input) => vcsStatusBroadcaster.streamBranchStatus(input), + [WS_METHODS.vcsRefreshBranch]: (input) => + vcsStatusBroadcaster.refreshBranchStatus(input).pipe(Effect.asVoid), [WS_METHODS.subscribeVcsStatus]: (input) => vcsStatusBroadcaster.streamStatus(input), [WS_METHODS.subscribeWorktreeSetup]: (input) => worktreeSetupTracker.stream(input.threadId), [WS_METHODS.worktreeSetupCancel]: (input) => diff --git a/apps/web/package.json b/apps/web/package.json index 5840ecc1551ea..6185d8d66aee4 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -49,7 +49,7 @@ "@tiptap/starter-kit": "^3.31.3", "class-variance-authority": "^0.7.1", "culori": "^4.0.2", - "dompurify": "^3.4.16", + "dompurify": "^3.4.17", "effect": "catalog:", "entities": "8.1.0", "fast-xml-parser": "5.7.3", @@ -59,14 +59,14 @@ "html-url-attributes": "^3.0.1", "jsonc-parser": "3.3.1", "jszip": "3.10.1", - "katex": "^0.16.47", + "katex": "^0.18.2", "lucide": "^0.564.0", "lucide-react": "^0.564.0", "mdast-util-from-markdown": "^2.0.3", "micromark-util-combine-extensions": "^2.0.1", "morphicons": "^1.7.1", "pdfjs-dist": "6.4.299", - "pele": "^1.8.0", + "pele": "catalog:", "react": "catalog:", "react-dom": "catalog:", "react-markdown": "^10.1.0", diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index 812d5242af849..f5fa3787faef7 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -36,7 +36,7 @@ import { environmentShell } from "./state/shell"; import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; import { startWorkspaceFocus } from "./lib/workspaceFocus"; import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands"; -import { environmentThreadShells } from "./state/threads"; +import { environmentThreadShells, threadEnvironment } from "./state/threads"; import { resolveThreadRouteTarget } from "./threadRoutes"; /** Writes appearance settings onto the document, touching only the groups that changed. */ @@ -173,6 +173,7 @@ export function startAppServices(): AppRouter { threadShellAtom: environmentThreadShells.threadShellAtom, threadRefsAtom: environmentThreadShells.threadRefsAtom, shellStateAtom: environmentShell.stateAtom, + pendingThreadIdsAtom: threadEnvironment.pendingThreadIdsAtom, }); startMainAppLocationTracking(router); startWorkspaceFocus(router); diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 14955f7242897..47bc82a04ebac 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -263,7 +263,7 @@ function registerAppShellCommands(router: AnyRouter, shellElement: Element): () }; } -function SidebarControl() { +function SidebarControl({ showSidebar }: { readonly showSidebar: boolean }) { const router = useRouter(); // Coder: there is no usage page. const usagePageOpen = false; @@ -278,6 +278,8 @@ function SidebarControl() { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window keydown listener that toggles the sidebar on its shortcut useEffect(() => { + // A hidden sidebar would still save the toggle, so the shortcut does nothing without one. + if (!showSidebar) return; const onKeyDown = (event: KeyboardEvent) => { if (event.defaultPrevented) return; if ( @@ -311,7 +313,7 @@ function SidebarControl() { return () => { window.removeEventListener("keydown", onKeyDown, true); }; - }, [keybindings, toggleSidebar, usagePageOpen]); + }, [keybindings, showSidebar, toggleSidebar, usagePageOpen]); // The control lives as long as the shell, so it carries the shell's commands. Created // once so re-renders never re-register them. @@ -329,28 +331,36 @@ function SidebarControl() { )} data-sidebar-control="" > - - - } - /> - - Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""} - - + {showSidebar ? ( + + + } + /> + + Toggle main sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""} + + + ) : null} ); } -export function AppSidebarLayout({ children }: { children: ReactNode }) { +export function AppSidebarLayout({ + children, + showSidebar = true, +}: { + children: ReactNode; + showSidebar?: boolean; +}) { const sidebarArea = workspaceAreaProps("sidebar", 0, "Threads"); // Coder: no desktop window bridge (fullscreen insets, menu actions). const [sidebarRouteReveal] = useState(() => ({ @@ -390,30 +400,34 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) { style={sidebarProviderStyle} > {/* Coder: no desktop back/forward buttons or swipe navigation (#27430). */} - - - nextWidth <= currentWidth || - wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH, - storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY, - onResize: setSidebarWidth, - }} - > - - - + {showSidebar ? ( + <> + + + nextWidth <= currentWidth || + wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH, + storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY, + onResize: setSidebarWidth, + }} + > + + + + + ) : null} {children} - + ); diff --git a/apps/web/src/components/BranchPicker.tsx b/apps/web/src/components/BranchPicker.tsx index 0af5fb3d4e94a..963755a4e773c 100644 --- a/apps/web/src/components/BranchPicker.tsx +++ b/apps/web/src/components/BranchPicker.tsx @@ -1,11 +1,10 @@ +import { useLegendListRef } from "~/hooks/useLegendListRef"; import type { VcsRef } from "@t3tools/contracts"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { useId, useRef, useState, type ComponentProps, type ReactNode } from "react"; import { MiddleTruncate } from "./ui/middle-truncate"; -import { observeResize } from "../lib/observeResize"; import { cn } from "../lib/utils"; -import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches"; import { RefreshIcon } from "./ui/refresh-icon"; import { Switch } from "./ui/switch"; import { getVirtualizedScrollFadeClassName } from "./ui/scroll-area"; @@ -62,10 +61,7 @@ export function BranchPicker({ }) { const highlightedValueRef = useRef(null); const startFromOriginSwitchId = useId(); - const branchListScrollElementRef = useRef(null); - const previousBranchListScrollTopRef = useRef(null); const handleOpenChange = (nextOpen: boolean) => { - previousBranchListScrollTopRef.current = null; if (!nextOpen) highlightedValueRef.current = null; onOpenChange(nextOpen); }; @@ -78,59 +74,14 @@ export function BranchPicker({ onLoadNext(); }; - const maybeFetchNextBranchPage = () => { - const scrollElement = branchListScrollElementRef.current; - if (!scrollElement) { - return; - } - - const previousScrollTop = previousBranchListScrollTopRef.current; - previousBranchListScrollTopRef.current = scrollElement.scrollTop; - if ( - !open || - !hasNextPage || - isFetchingNextPage || - !shouldLoadNextBranchPageAfterScroll({ - previousScrollTop, - scrollTop: scrollElement.scrollTop, - scrollHeight: scrollElement.scrollHeight, - clientHeight: scrollElement.clientHeight, - }) - ) { - return; - } - - fetchNextBranchPage(); - }; - const branchListRef = useRef(null); const updateBranchListScrollFades = () => { - const scrollElement = branchListRef.current?.getScrollableNode?.(); - if (!(scrollElement instanceof HTMLElement)) { - return; - } - branchListScrollElementRef.current = scrollElement; - const maxScrollOffset = Math.max(0, scrollElement.scrollHeight - scrollElement.clientHeight); - setShowTopBranchScrollFade(scrollElement.scrollTop > 1); - setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1); - }; - - // The popup mounts the list when it opens. Its content settles over a few - // frames as rows measure, so the fades follow the scroller and its content. - const attachBranchList = (list: LegendListRef | null) => { - branchListRef.current = list; - const scrollElement = list?.getScrollableNode?.(); - if (!(scrollElement instanceof HTMLElement)) return; - const content = scrollElement.firstElementChild; - const stopObserving = observeResize( - content ? [scrollElement, content] : scrollElement, - updateBranchListScrollFades, - ); - return () => { - stopObserving(); - branchListRef.current = null; - }; + const metrics = branchListRef.current?.getState(); + if (!metrics) return; + setShowTopBranchScrollFade(!metrics.isAtStart); + setShowBottomBranchScrollFade(!metrics.isAtEnd); }; + const branchScrollRef = useLegendListRef(branchListRef, updateBranchListScrollFades); return ( - ref={attachBranchList} + ref={branchScrollRef} data={filteredItems} + initialScrollOffset={0} keyExtractor={(item) => item} {...(getItemType ? { getItemType } : {})} renderItem={({ item, index }) => renderItem(item, index)} estimatedItemSize={28} drawDistance={336} - onLayout={() => { - updateBranchListScrollFades(); - previousBranchListScrollTopRef.current = - branchListScrollElementRef.current?.scrollTop ?? null; - }} - onScroll={() => { - updateBranchListScrollFades(); - maybeFetchNextBranchPage(); - }} + onScroll={updateBranchListScrollFades} + onLayout={updateBranchListScrollFades} + onReady={updateBranchListScrollFades} + onEndReached={fetchNextBranchPage} + onEndReachedThreshold={0.5} className={cn( "min-h-0 max-h-56 scrollbar-gutter-stable overflow-x-hidden overscroll-y-contain ps-1 pe-0 py-2", getVirtualizedScrollFadeClassName({ diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 6174fdbf3482b..03758d31e5249 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -802,8 +802,12 @@ const CHAT_MARKDOWN_COMPONENTS = { return
{children}
; }, p: function MarkdownParagraph({ node: _node, children, ...props }) { - const { skills, threadRef } = use(ChatMarkdownRendererContext); - return

{renderSkillInlineMarkdownChildren(children, skills, threadRef)}

; + const { skills, threadRef, environmentId } = use(ChatMarkdownRendererContext); + return ( +

+ {renderSkillInlineMarkdownChildren(children, skills, threadRef, environmentId)} +

+ ); }, blockquote: function MarkdownBlockquote({ node: _node, children, ...props }) { const alert = @@ -838,12 +842,12 @@ const CHAT_MARKDOWN_COMPONENTS = { ); }, li: function MarkdownListItem({ node, children, ...props }) { - const { skills, threadRef } = use(ChatMarkdownRendererContext); + const { skills, threadRef, environmentId } = use(ChatMarkdownRendererContext); // Resolve checkbox markers by offset to avoid rerendering list items on every streamed token. const isTaskItem = String(props.className ?? "").includes("task-list-item"); return (
  • - {renderSkillInlineMarkdownChildren(children, skills, threadRef)} + {renderSkillInlineMarkdownChildren(children, skills, threadRef, environmentId)}
  • ); }, diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 17f87cd245e61..54ccad72fa7a0 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -2,7 +2,6 @@ import { boundAttachmentIds, buildExpiredTerminalContextToastCopy, planComposerTurn, - restorePlanFollowUpComposer, snapshotComposerSend, withMessageContext, deriveAvailableRevertTurnCounts, @@ -1059,60 +1058,6 @@ describe("planComposerTurn", () => { }); }); -describe("restorePlanFollowUpComposer", () => { - // The draft is the failed follow-up's thread; the refs and cursor are whatever thread is on - // screen. - it.each([ - { - name: "puts the follow-up back while its thread is open", - before: { draft: "", refs: "", cursor: null }, - routeIsCurrent: true, - after: { draft: "Tighten step 2", refs: "Tighten step 2", cursor: "Tighten step 2" }, - }, - { - name: "keeps a draft typed while the follow-up was in flight", - before: { draft: "Next idea", refs: "Next idea", cursor: null }, - routeIsCurrent: true, - after: { draft: "Next idea", refs: "Next idea", cursor: null }, - }, - { - name: "leaves another thread's composer alone after navigating away", - before: { draft: "", refs: "Other thread", cursor: null }, - routeIsCurrent: false, - after: { draft: "Tighten step 2", refs: "Other thread", cursor: null }, - }, - ])("$name", ({ before, routeIsCurrent, after }) => { - const composer: { draft: string; refs: string; cursor: string | null } = { ...before }; - restorePlanFollowUpComposer({ - snapshot: { - prompt: "Tighten step 2", - environmentContexts: [], - terminalContexts: [], - reviewComments: [], - // Coder: no preview annotations in the plan follow-up snapshot. - threadContexts: [], - }, - draftHasUserContent: composer.draft.trim().length > 0, - routeIsCurrent, - writeComposerRefs: (snapshot) => { - composer.refs = snapshot.prompt; - }, - writePrompt: (prompt) => { - composer.draft = prompt; - }, - writeTerminalContexts: () => undefined, - writeReviewComments: () => undefined, - writeThreadContexts: () => undefined, - writeEnvironmentContexts: () => undefined, - resetCursor: ({ prompt }) => { - composer.cursor = prompt; - }, - }); - - expect(composer).toEqual(after); - }); -}); - describe("withMessageContext", () => { const context = { records: [] } as unknown as NonNullable< Parameters[0]["context"] diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 5d5a97ab10e7f..39a4c6c2417ba 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -15,11 +15,7 @@ import type { SetStateAction } from "react"; import { applyClaudePromptEffortPrefix, resolvePromptInjectedEffort } from "@t3tools/shared/model"; import { getProviderModelCapabilities } from "../providerModels"; import { sanitizeThreadErrorMessage } from "@t3tools/client-runtime/errors"; -import type { - EnvironmentThread, - ThreadStructure, - EnvironmentThreadShell, -} from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentThread, ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { type AssetCreateUrlInput, type AssetCreateUrlResult, @@ -31,7 +27,6 @@ import { type MessageId, type ModelSelection, type OrchestrationMessageContext, - type ProviderInteractionMode, ProviderDriverKind, type ProviderInstanceId, type ServerProvider, @@ -73,8 +68,7 @@ import { } from "../composerDraftStore"; import * as Schema from "effect/Schema"; import { appAtomRegistry } from "../rpc/atomRegistry"; -import { environmentThreadShells, environmentThreadDetails } from "../state/threads"; -import { waitForAtomValue } from "../state/waitForAtomValue"; +import { environmentThreadDetails } from "../state/threads"; import { filterTerminalContextsWithText, formatTerminalContextLabel, @@ -87,7 +81,7 @@ import { import { reviewCommentContextLabel, terminalContextReference } from "../lib/composerContextRecords"; import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch"; import type { DraftThreadEnvMode } from "../composerDraftStore"; -import { collapseExpandedComposerCursor, type ComposerSubmissionIntent } from "../composer-logic"; +import { type ComposerSubmissionIntent } from "../composer-logic"; import type { ReviewCommentContext } from "../reviewCommentContext"; import { derivePhase, type TimelineEntry } from "../session-logic"; import type { RightPanelSurface } from "../rightPanelStore"; @@ -489,21 +483,6 @@ export function resolveComposerProviderSelection(input: { }; } -export function resolveComposerInteractionMode(input: { - planModeEnabled: boolean; - provider: Pick | null | undefined; - interactionMode: ProviderInteractionMode; -}): { enabled: boolean; interactionMode: ProviderInteractionMode } { - const enabled = - input.planModeEnabled && - input.provider != null && - input.provider.showInteractionModeToggle !== false; - return { - enabled, - interactionMode: enabled ? input.interactionMode : "default", - }; -} - export function reconcileMountedTerminalThreadIds(input: { currentThreadIds: ReadonlyArray; openThreadIds: ReadonlyArray; @@ -739,22 +718,6 @@ export function shouldShowBranchMismatchBanner(input: { return input.composerHasContent || input.wasShownForCurrentMismatch; } -export function shouldShowPlanFollowUpPrompt(input: { - pendingUserInputCount: number; - interactionMode: ProviderInteractionMode; - latestTurnSettled: boolean; - hasActionableProposedPlan: boolean; - hasComposerAttachments: boolean; -}): boolean { - return ( - input.pendingUserInputCount === 0 && - input.interactionMode === "plan" && - input.latestTurnSettled && - input.hasActionableProposedPlan && - !input.hasComposerAttachments - ); -} - const sessionDismissedBranchMismatchKeys = new Set(); export function dismissBranchMismatchForSession(key: string): void { @@ -793,18 +756,6 @@ function threadHasStarted(thread: Thread | null | undefined): boolean { return Boolean(thread && (thread.latestRun !== null || thread.itemCount > 0 || thread.runtime)); } -export function threadShellHasStarted( - shell: - | Pick - | null - | undefined, -): boolean { - return Boolean( - shell && - (shell.latestRun !== null || shell.latestUserMessageAt !== null || shell.runtime !== null), - ); -} - // Imported history lacks a session until its first prompt; resolve its instance before locking the driver. export function deriveLockedProvider(input: { thread: Thread | null | undefined; @@ -859,19 +810,6 @@ export function getStartedThreadModelChangeBlockReason(input: { }; } -export async function waitForStartedServerThread( - threadRef: ScopedThreadRef, - timeoutMs = 1_000, -): Promise { - const threadAtom = environmentThreadShells.threadShellAtom(threadRef); - return waitForAtomValue({ - registry: appAtomRegistry, - atom: threadAtom, - predicate: threadHasStarted, - timeoutMs, - }); -} - export async function waitForRevertedMessage( threadRef: ScopedThreadRef, turnCount: number, @@ -1088,47 +1026,6 @@ export function shouldRefocusComposerOnWindowFocus( ); } -export interface PlanFollowUpComposerSnapshot { - readonly prompt: string; - readonly terminalContexts: ReadonlyArray; - readonly reviewComments: ReadonlyArray; - readonly threadContexts: ReadonlyArray; - readonly environmentContexts: ReadonlyArray; -} - -// A draft typed while the send was in flight is newer and stays. Composer refs and the cursor -// belong to the thread on screen, so they follow only while the follow-up's route is current. -export function restorePlanFollowUpComposer(input: { - readonly snapshot: PlanFollowUpComposerSnapshot; - readonly draftHasUserContent: boolean; - readonly routeIsCurrent: boolean; - readonly writeComposerRefs: (snapshot: PlanFollowUpComposerSnapshot) => void; - readonly writePrompt: (prompt: string) => void; - readonly writeTerminalContexts: (contexts: ReadonlyArray) => void; - readonly writeReviewComments: (comments: ReadonlyArray) => void; - readonly writeThreadContexts: (records: ReadonlyArray) => void; - readonly writeEnvironmentContexts: (records: ReadonlyArray) => void; - readonly resetCursor: (options: { - cursor: number; - prompt: string; - detectTrigger: boolean; - }) => void; -}): void { - if (input.draftHasUserContent) return; - if (input.routeIsCurrent) input.writeComposerRefs(input.snapshot); - input.writePrompt(input.snapshot.prompt); - input.writeTerminalContexts(input.snapshot.terminalContexts); - input.writeReviewComments(input.snapshot.reviewComments); - input.writeThreadContexts(input.snapshot.threadContexts); - input.writeEnvironmentContexts(input.snapshot.environmentContexts); - if (!input.routeIsCurrent) return; - input.resetCursor({ - cursor: collapseExpandedComposerCursor(input.snapshot.prompt, input.snapshot.prompt.length), - prompt: input.snapshot.prompt, - detectTrigger: true, - }); -} - export { isThreadWokeUnseen } from "@t3tools/client-runtime/state/thread-settled"; export function formatOutgoingPrompt(params: { diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index b046301bf6b64..1773f7fff0e08 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -26,7 +26,6 @@ import { useRightPanelActions } from "./chat/useRightPanelActions"; import { type TerminalLaunchContext, useChatTerminalActions } from "./chat/useChatTerminalActions"; import { useComposerSend } from "./chat/useComposerSend"; import { useComposerResume } from "./chat/useComposerResume"; -import { useImplementPlanInNewThread } from "./chat/useProposedPlanSend"; import { ThreadFind, ThreadFindCanvas } from "./chat/ThreadFindProvider"; import { closeThreadFind, openThreadFind, useThreadFindOpen } from "./chat/threadFindStore"; import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar"; @@ -128,9 +127,7 @@ import { derivePhase, deriveActiveWorkStartedAt, deriveCanInterruptRunningThread, - findLatestProposedPlan, findRevertCheckpoint, - hasActionableProposedPlan, isLatestRunSettled, } from "../session-logic"; import { type LegendListRef } from "@legendapp/list/react"; @@ -267,7 +264,7 @@ import { useRightPanelSurfaceClose } from "../hooks/useRightPanelSurfaceClose"; import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; import { ComposerSurface } from "./chat/ComposerSurface"; import { resolveThreadSyncPhase } from "../threadSync"; -import { hasAvailableCompactionProvider } from "./chat/ContextWindowMeter.logic"; +import { hasAvailableCompactionProvider } from "./chat/compaction.logic"; import { deriveLatestContextWindowSnapshot, hasDismissedResumeCompaction, @@ -282,10 +279,8 @@ import { buildLocalDraftThread, deriveCommittedServerUserMessageIds, dismissBranchMismatchForSession, - shouldShowPlanFollowUpPrompt, deriveLockedProvider, resolveFileAttachmentUrl, - resolveComposerInteractionMode, resolveComposerProviderSelection, resolveThreadMetadataUpdateForNextTurn, resolveSendEnvMode, @@ -526,9 +521,6 @@ export default function ChatView(props: ChatViewProps) { const composerRuntimeMode = useComposerDraftStore( (store) => store.getComposerDraft(composerDraftTarget)?.runtimeMode ?? null, ); - const composerInteractionMode = useComposerDraftStore( - (store) => store.getComposerDraft(composerDraftTarget)?.interactionMode ?? null, - ); const composerActiveProvider = useComposerDraftStore( (store) => store.getComposerDraft(composerDraftTarget)?.activeProvider ?? null, ); @@ -538,10 +530,6 @@ export default function ChatView(props: ChatViewProps) { ? (draft.modelSelectionByProvider[draft.activeProvider] ?? null) : null; }); - const composerHasAttachments = useComposerDraftStore((store) => { - const draft = store.getComposerDraft(composerDraftTarget); - return (draft?.images.length ?? 0) > 0 || (draft?.files.length ?? 0) > 0; - }); const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const composerImagesRef = useRef([]); @@ -1162,12 +1150,6 @@ export default function ChatView(props: ChatViewProps) { const selectedProvider = selectedProviderEntry?.driverKind ?? requestedDriverKind; const activeProviderInstanceId = selectedProviderEntry?.instanceId ?? null; const activeProviderStatus = selectedProviderEntry?.snapshot ?? null; - const { enabled: interactionModeEnabled, interactionMode } = resolveComposerInteractionMode({ - planModeEnabled: settings.planModeEnabled, - provider: activeProviderStatus, - interactionMode: - composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE, - }); const conversationProviderStatus = providerStatuses.find((status) => status.instanceId === activeRuntime?.providerInstanceId) ?? activeProviderStatus; @@ -1224,19 +1206,6 @@ export default function ChatView(props: ChatViewProps) { const onHeldRequestIdsChange = useStableCallback((requestIds: ReadonlySet) => { setHeldApprovalRequestIds((current) => (shallow(current, requestIds) ? current : requestIds)); }); - const activeProposedPlan = (() => { - if (!latestRunSettled) { - return null; - } - return findLatestProposedPlan(serverProjection, activeLatestRun?.runId ?? null); - })(); - const showPlanFollowUpPrompt = shouldShowPlanFollowUpPrompt({ - pendingUserInputCount: pendingUserInputs.length, - interactionMode, - latestTurnSettled: latestRunSettled, - hasActionableProposedPlan: hasActionableProposedPlan(activeProposedPlan), - hasComposerAttachments: composerHasAttachments, - }); // Coder: API usage has no subscription quota panel (`/usage-limits`). const { beginLocalDispatch, @@ -1655,7 +1624,7 @@ export default function ChatView(props: ChatViewProps) { threadId: activeThreadId, message: { messageId: newMessageId(), role: "user", text, attachments: [] }, runtimeMode, - interactionMode, + interactionMode: DEFAULT_INTERACTION_MODE, dispatchMode: "queue", }, }); @@ -2234,18 +2203,8 @@ export default function ChatView(props: ChatViewProps) { activeEnvironmentUnavailable || feedbackUploading || pendingApprovals.length > 0 || - pendingUserInputs.length > 0 || - showPlanFollowUpPrompt; + pendingUserInputs.length > 0; const compactDisabled = compactThreadUnavailable; - const compactDisabledReason = compactDisabled - ? !canOperateThread - ? "This connection cannot change threads." - : !activeProject - ? "Choose a project before compacting" - : !manualCompactionProviderAvailable - ? "Compaction is unavailable for this provider" - : "Compacting is unavailable right now" - : null; const resumeCompactionTokens = activeContextWindow && resolveIdleCompaction( @@ -2539,14 +2498,11 @@ export default function ChatView(props: ChatViewProps) { const { getModelDisabledReason, - handleInteractionModeChange, - handleInteractionModeChangeStable, handleRuntimeModeChangeStable, onEnvModeChangeStable, onProviderModelSelectStable, onStartFromOriginChange, openProviderSetupStable, - toggleInteractionModeStable, } = useComposerSelection({ environmentId, composerDraftTarget, @@ -2560,8 +2516,6 @@ export default function ChatView(props: ChatViewProps) { supportsProviderSwitchingViaHandoff, multipleModelSelections, runtimeMode, - interactionMode, - interactionModeEnabled, isLocalDraftThread, canOverrideServerThreadEnvMode, setPendingServerThreadEnvModeEntry, @@ -2580,28 +2534,12 @@ export default function ChatView(props: ChatViewProps) { threadDetailLoading, activeEnvironmentUnavailable, runtimeMode, - interactionMode, localCheckoutBranchMismatch, composerRef, persistThreadSettingsForNextTurn, scrollToEnd, setThreadError, }); - const onImplementPlanInNewThread = useImplementPlanInNewThread({ - environmentId, - routeThreadKey, - activeThread, - activeThreadBranch, - activeProposedPlan, - isServerThread, - isSendBusy, - composerRef, - beginLocalDispatch, - resetLocalDispatch, - activeProject, - activeEnvironmentUnavailable, - defaultRuntimeMode, - }); const { onSend } = useComposerSend({ environmentId, routeThreadKey, @@ -2613,7 +2551,6 @@ export default function ChatView(props: ChatViewProps) { activeThreadBranch, activeProject, activeProjectDefaultModelSelection, - activeProposedPlan, activeMessageCount, isServerThread, isLocalDraftThread, @@ -2642,7 +2579,6 @@ export default function ChatView(props: ChatViewProps) { keepFullHistory, freshSessionAvailable: freshSessionCommandAvailable, resumeCompactionTokens, - showPlanFollowUpPrompt, readPendingEnvironmentChange, pendingApprovals, respondingRequestIds, @@ -2664,13 +2600,11 @@ export default function ChatView(props: ChatViewProps) { setKeepFullHistory, anchorNewTurn, acknowledgeActiveThreadWoke, - handleInteractionModeChange, onSideChat: sideChat.available ? sendSideChatStable : undefined, sideChatDisabledReason, handleNewThreadInActiveProject, persistThreadSettingsForNextTurn, }); - const onImplementPlanInNewThreadStable = useStableCallback(onImplementPlanInNewThread); const onWorktreeSetupWorkLocally = () => { if (!worktreeSetup || worktreeSetup.phase !== "running" || !draftId) { @@ -3226,7 +3160,6 @@ export default function ChatView(props: ChatViewProps) { draftId={draftId} activeThreadId={activeThreadId} activeThread={activeThread} - activeThreadShell={activeThreadShell} promptHistoryEntries={timelineEntries} forceExpandedOnMobile={ forceExpandedMobileComposer && isDraftHeroState @@ -3286,14 +3219,8 @@ export default function ChatView(props: ChatViewProps) { activePendingDraftAnswers={activePendingDraftAnswers} activePendingQuestionIndex={activePendingQuestionIndex} respondingRequestIds={respondingRequestIds} - showPlanFollowUpPrompt={showPlanFollowUpPrompt} - activeProposedPlan={activeProposedPlan} - threadSyncPhase={ - activeEnvironmentUnavailable ? null : threadSyncPhase - } runtimeMode={runtimeMode} defaultRuntimeMode={defaultRuntimeMode} - interactionMode={interactionMode} lockedProvider={modelPickerLockedProvider} providerStatuses={providerStatuses as ServerProvider[]} providerCatalogKnown={serverConfig !== null} @@ -3302,12 +3229,8 @@ export default function ChatView(props: ChatViewProps) { } activeThreadModelSelection={activeThread?.modelSelection} activeProjectId={activeProject?.id ?? null} - contextWindowEntries={serverVisibleTurnItems} - contextWindowLiveUsage={activeThreadLiveTokenUsage} - contextWindowProviderThread={activeProviderThread} compactThreadUnavailable={compactThreadUnavailable} compactDisabled={compactDisabled} - compactDisabledReason={compactDisabledReason} resolvedTheme={resolvedTheme} settings={settings} keybindings={keybindings} @@ -3337,7 +3260,6 @@ export default function ChatView(props: ChatViewProps) { onSend={onComposerSendStable} onResume={onComposerResumeStable} onInterrupt={onInterruptStable} - onImplementPlanInNewThread={onImplementPlanInNewThreadStable} onSelectActivePendingUserInputOption={ onSelectActivePendingUserInputOptionStable } @@ -3354,9 +3276,7 @@ export default function ChatView(props: ChatViewProps) { onProviderModelSelect={onProviderModelSelectStable} onOpenProviderSetup={openProviderSetupStable} getModelDisabledReason={getModelDisabledReason} - toggleInteractionMode={toggleInteractionModeStable} handleRuntimeModeChange={handleRuntimeModeChangeStable} - handleInteractionModeChange={handleInteractionModeChangeStable} focusComposer={focusComposerStable} scheduleComposerFocus={scheduleComposerFocusStable} setThreadError={setThreadError} diff --git a/apps/web/src/components/CommandPalette.browser.test.tsx b/apps/web/src/components/CommandPalette.browser.test.tsx index 78cde080141ae..3f1ab04da99a3 100644 --- a/apps/web/src/components/CommandPalette.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.browser.test.tsx @@ -1,6 +1,6 @@ import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it, vi } from "vite-plus/test"; -import { page } from "vite-plus/test/browser"; +import { page, userEvent } from "vite-plus/test/browser"; import { render } from "../../test/render"; import { openCommandPalette } from "../commandPaletteBus"; @@ -44,6 +44,39 @@ describe("CommandPalette open intents", () => { await expect.element(page.getByPlaceholder("Search...")).toHaveFocus(); }); + it("highlights the first project when New thread in... opens from the root list", async () => { + const environmentId = EnvironmentId.make("local"); + const project = (id: string, title: string): Project => ({ + id: ProjectId.make(id), + environmentId, + title, + workspaceRoot: `/work/${id}`, + repositoryIdentity: null, + defaultModelSelection: null, + createdAt: "2026-03-01T00:00:00.000Z", + updatedAt: "2026-03-01T00:00:00.000Z", + scripts: [], + }); + setup({ + projects: [project("acme", "Acme"), project("beta", "Beta"), project("gamma", "Gamma")], + }); + await using _screen = await render({null}); + + openCommandPalette({}); + await expect + .element(page.getByPlaceholder("Search commands, projects, and threads...")) + .toHaveFocus(); + await userEvent.keyboard("{ArrowDown}"); + await expect + .element(page.getByRole("option", { name: /^New thread in\.\.\./ })) + .toHaveAttribute("data-highlighted"); + await userEvent.keyboard("{Enter}"); + + await expect.element(page.getByPlaceholder("Search...")).toHaveFocus(); + await expect.element(page.getByRole("option").first()).toHaveAttribute("data-highlighted"); + await expect.element(page.getByRole("option").nth(1)).not.toHaveAttribute("data-highlighted"); + }); + it("opens a search intent with its query in the focused input", async () => { setup(); await using _screen = await render({null}); diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index c034c7f4131c1..cc23a79ddddad 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -948,7 +948,7 @@ describe("newThreadNoProjectIndex", () => { }); it("goes after the pinned projects and the first unpinned one", () => { - expect(newThreadNoProjectIndex([entry(true), entry(true), entry(false, true), entry()])).toBe( + expect(newThreadNoProjectIndex([entry(false, true), entry(true), entry(true), entry()])).toBe( 3, ); expect(newThreadNoProjectIndex([entry(false, true), entry(), entry(false, false, true)])).toBe( diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 01ca5696aafbc..a1b812c7590ba 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -772,8 +772,15 @@ function OpenCommandPaletteDialog(props: { (() => { const isScratch = (project: CommandPaletteProject) => isScratchProject(project, scratchWorkspaceRootFor(project.environmentId)); + const currentEntry = + currentProjectId === null + ? undefined + : projectPickerEntries.find((entry) => entry.isPreferred); const projectItems = buildNewThreadInProjectItems({ projects: pickerProjects.filter((project) => !isScratch(project)), + currentProjectKey: currentEntry + ? `${currentEntry.targetProject.environmentId}:${currentEntry.targetProject.id}` + : null, projectGroupByTargetKey, locationByEnvironmentId: projectEnvironmentLocationById, pin: projectPin, diff --git a/apps/web/src/components/CommandPaletteProjectItems.tsx b/apps/web/src/components/CommandPaletteProjectItems.tsx index 2a3d466474d2e..3039ac9e6f261 100644 --- a/apps/web/src/components/CommandPaletteProjectItems.tsx +++ b/apps/web/src/components/CommandPaletteProjectItems.tsx @@ -73,7 +73,9 @@ export function buildProjectSearchItems(input: ProjectItemsInput) { } /** Projects as targets of the "New thread in..." submenu. */ -export function buildNewThreadInProjectItems(input: ProjectItemsInput) { +export function buildNewThreadInProjectItems( + input: ProjectItemsInput & { readonly currentProjectKey: string | null }, +) { return buildProjectActionItems({ projects: input.projects, valuePrefix: "new-thread-in", @@ -89,6 +91,7 @@ export function buildNewThreadInProjectItems(input: ProjectItemsInput) { ), icon: projectFaviconIcon, @@ -100,10 +103,17 @@ export function buildNewThreadInProjectItems(input: ProjectItemsInput) { function ProjectLocationDescription(props: { readonly location: CommandPaletteProjectLocation | undefined; readonly workspaceRoot: string; + readonly current?: boolean; }) { const location = props.location ?? UNKNOWN_PROJECT_LOCATION; return ( + {props.current ? ( + <> + Current + + + ) : null} {location.kind === "remote" ? ( {location.label} - {props.workspaceRoot} + {props.workspaceRoot} ); } diff --git a/apps/web/src/components/CommandPaletteResults.tsx b/apps/web/src/components/CommandPaletteResults.tsx index e3cc3a3791afa..aec99f04b5290 100644 --- a/apps/web/src/components/CommandPaletteResults.tsx +++ b/apps/web/src/components/CommandPaletteResults.tsx @@ -1,3 +1,4 @@ +import { useLegendListRef } from "~/hooks/useLegendListRef"; import { type ResolvedKeybindingsConfig } from "@t3tools/contracts"; import { LegendList, type LegendListRef } from "@legendapp/list/react"; import { ChevronRightIcon } from "lucide-react"; @@ -77,12 +78,11 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) { } export function scrollCommandPaletteRowIntoView(list: LegendListRef | null, rowIndex: number) { - const element = list?.getState?.().elementAtIndex(rowIndex); - if (element instanceof HTMLElement) { - element.scrollIntoView({ block: "nearest" }); - return; - } - void list?.scrollIndexIntoView?.({ index: rowIndex, animated: false }); + void list?.scrollIndexIntoView({ + index: rowIndex, + animated: false, + viewportMargin: { start: 24, end: 24 }, + }); } interface CommandPaletteVirtualizedResultsProps extends Omit { @@ -96,15 +96,15 @@ export function CommandPaletteVirtualizedResults(props: CommandPaletteVirtualize const { listRef } = props; const [scrollFade, setScrollFade] = useState({ top: false, bottom: false }); const updateScrollFade = () => { - const scrollElement = listRef.current?.getScrollableNode?.(); - if (!(scrollElement instanceof HTMLElement)) return; - const top = scrollElement.scrollTop > 1; - const bottom = - scrollElement.scrollHeight - scrollElement.clientHeight - scrollElement.scrollTop > 1; + const metrics = listRef.current?.getState(); + if (!metrics) return; + const top = !metrics.isAtStart; + const bottom = !metrics.isAtEnd; setScrollFade((current) => current.top === top && current.bottom === bottom ? current : { top, bottom }, ); }; + const scrollRef = useLegendListRef(listRef, updateScrollFade); if (props.rows.length === 0) { return ; @@ -113,8 +113,9 @@ export function CommandPaletteVirtualizedResults(props: CommandPaletteVirtualize return ( - ref={listRef} + ref={scrollRef} data={props.rows} + initialScrollOffset={0} keyExtractor={(row) => row.key} getItemType={(row) => row.kind} extraData={props.highlightedItemValue} @@ -139,9 +140,12 @@ export function CommandPaletteVirtualizedResults(props: CommandPaletteVirtualize drawDistance={400} onLayout={updateScrollFade} onScroll={updateScrollFade} + onReady={updateScrollFade} + // Legend counts style padding (not class padding) in its size, end state and row positions. + style={{ paddingTop: 8, paddingBottom: 8 }} contentContainerClassName="px-2" className={cn( - "min-h-0 scroll-py-6 overflow-x-hidden overscroll-y-contain py-2 [&::-webkit-scrollbar-track]:my-2", + "min-h-0 scroll-py-6 overflow-x-hidden overscroll-y-contain [&::-webkit-scrollbar-track]:my-2", getVirtualizedScrollFadeClassName(scrollFade), )} /> diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 8c4698210b1d5..bb8f5a5a2211a 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -1,3 +1,4 @@ +import { useAtomValue } from "@effect/atom-react"; import { documentChipKindForFileName } from "~/pierre-icons"; import { isProviderSkillUserInvocable } from "@t3tools/client-runtime/providerSkills"; import { formatProviderSkillDisplayName } from "@t3tools/shared/inlineSkills"; @@ -46,6 +47,7 @@ import { useRef, useState, type KeyboardEvent as ReactKeyboardEvent, + type ReactNode, type RefObject, } from "react"; import { EditorContent, useEditor } from "@tiptap/react"; @@ -90,6 +92,7 @@ import { skillChipReplacements, splitOrLiftListItem, stepCaretAcrossStyledEdge, + type IsKnownModel, type SkillMeta, } from "~/composer-rich-text-doc"; import { @@ -114,6 +117,7 @@ import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon"; import { FileTagChipContent } from "./chat/FileTagChip"; import { SkillChipPopover, skillPopoverDescription } from "./chat/SkillInlineText"; import { AssistantCitationChip } from "./chat/AssistantCitationChip"; +import { ModelMentionChip, modelMentionKey, modelMentionKeysAtom } from "./chat/ModelMentionChip"; import { getTimelinePageScrollKey } from "./chat/pageScrollController"; import { ContextChip } from "./ContextChip"; import { @@ -161,6 +165,8 @@ export interface ComposerPromptEditorProps { skills: ReadonlyArray; disabled: boolean; placeholder: string; + /** Rendered after the placeholder text, such as a key hint. */ + placeholderSuffix?: ReactNode; ariaLabel?: string | undefined; suggestionListId?: string | undefined; activeSuggestionId?: string | undefined; @@ -324,6 +330,45 @@ const ComposerSkillExtension = Node.create({ }, }); +function ComposerModelNodeView({ node }: NodeViewProps) { + const actions = use(ComposerContextActionsContext); + return ( + + + + ); +} + +/** `model:/` from the `@` menu; `source` is the exact prompt text. */ +const ComposerModelExtension = Node.create({ + name: "composer-model", + group: "inline", + inline: true, + atom: true, + selectable: true, + addAttributes() { + return { + instanceId: { default: "" }, + model: { default: "" }, + source: { default: "" }, + }; + }, + parseHTML() { + return [{ tag: "span[data-composer-model]" }]; + }, + renderHTML({ HTMLAttributes }) { + return ["span", { "data-composer-model": "", ...HTMLAttributes }]; + }, + addNodeView() { + return ReactNodeViewRenderer(ComposerModelNodeView); + }, +}); + /** Chip presentation for `$name`, or null when the provider does not offer it to users. */ function composerSkillMeta( skills: ReadonlyArray, @@ -769,6 +814,7 @@ function createComposerExtensions(richText: boolean) { ComposerTextDirectionExtension, ComposerMentionExtension, ComposerSkillExtension, + ComposerModelExtension, ComposerCitationExtension, ComposerContextReferenceExtension, ComposerChipSelectionExtension, @@ -876,6 +922,7 @@ function ComposerPromptEditorTiptapInner( containerClassName, className, placeholderClassName, + placeholderSuffix, onChange, onVisibleSelectionChange, onCommandKeyDown, @@ -909,8 +956,13 @@ function ComposerPromptEditorTiptapInner( importContextFragment, })); - // Stable so a skills refresh does not rerun the controlled-value effect. + const { environmentId } = use(ComposerContextActionsContext); + const modelKeys = useAtomValue(modelMentionKeysAtom(environmentId ?? "")); + // Stable so a skills or models refresh does not rerun the controlled-value effect. const skillLabelFor = useStableCallback((name: string) => composerSkillMeta(skills, name)); + const isKnownModel = useStableCallback((instanceId: string, model: string) => + modelKeys.has(modelMentionKey(instanceId, model)), + ); const initialCursor = clampEditorCursor(value, cursor); const initialExpandedCursor = Math.max(0, Math.min(value.length, props.initialExpandedCursor)); @@ -1039,6 +1091,7 @@ function ComposerPromptEditorTiptapInner( content: buildDocJson(value, (name) => composerSkillMeta(skills, name), { styling: richText, literalText, + isKnownModel: (instanceId, model) => modelKeys.has(modelMentionKey(instanceId, model)), }), editable: !disabled, editorProps: { @@ -1336,7 +1389,8 @@ function ComposerPromptEditorTiptapInner( const tokens = literalText ? [] : collectComposerPromptInlineTokens(`${text}\n`); const isChip = (token: (typeof tokens)[number] | undefined) => token?.type === "mention" || - (token?.type === "skill" && skillLabelFor(token.value) !== null); + (token?.type === "skill" && skillLabelFor(token.value) !== null) || + (token?.type === "model" && isKnownModel(token.instanceId, token.model)); const lastToken = tokens.at(-1); if (isChip(lastToken) && lastToken?.end === text.length) { text += " "; @@ -1360,7 +1414,7 @@ function ComposerPromptEditorTiptapInner( insertMarkdownParagraphs( text, skillLabelFor, - { styling: richText, blocks: !nested, literalText, literalLength }, + { styling: richText, blocks: !nested, literalText, literalLength, isKnownModel }, (content) => { editorInstance .chain() @@ -1393,11 +1447,13 @@ function ComposerPromptEditorTiptapInner( }, }, onUpdate: ({ editor: updated, transaction }) => { - // Undo can restore a chip for a skill the current provider no longer offers. + // Undo can restore a chip for a skill or model the environment no longer offers. if (!literalText && isHistoryTransaction(transaction)) { - const stale = skillChipReplacements(updated.state.doc, skillLabelFor).filter( - ({ node }) => node.isText, - ); + const stale = skillChipReplacements( + updated.state.doc, + skillLabelFor, + isKnownModel, + ).filter(({ node }) => node.isText); if (stale.length > 0) { replaceSkillChips(updated, stale); return; @@ -1518,7 +1574,7 @@ function ComposerPromptEditorTiptapInner( if (previousSnapshot.value !== value) { saveCitationDraft(editor, previousSnapshot.value); editor.commands.setContent( - buildDocJson(value, skillLabelFor, { styling: richText, literalText }), + buildDocJson(value, skillLabelFor, { styling: richText, literalText, isKnownModel }), { emitUpdate: false, }, @@ -1559,18 +1615,21 @@ function ComposerPromptEditorTiptapInner( literalText, richText, skillLabelFor, + isKnownModel, value, ]); - // Reconcile loaded or switched provider skills without rebuilding citation node views. - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- replaces skill chip nodes in the Tiptap document when the provider skill list loads or changes + // Reconcile loaded or switched provider skills and models without rebuilding citation node views. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- replaces skill and model chip nodes in the Tiptap document when the provider skill or model list loads or changes useEffect(() => { if (!editor || literalText) return; - const replacements = skillChipReplacements(editor.state.doc, (name) => - composerSkillMeta(skills, name), + const replacements = skillChipReplacements( + editor.state.doc, + (name) => composerSkillMeta(skills, name), + (instanceId, model) => modelKeys.has(modelMentionKey(instanceId, model)), ); if (replacements.length > 0) replaceSkillChips(editor, replacements); - }, [editor, literalText, skills]); + }, [editor, literalText, modelKeys, skills]); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown useLayoutEffect(() => { @@ -1786,6 +1845,7 @@ function ComposerPromptEditorTiptapInner( )} > {placeholder} + {placeholderSuffix} ) : null} @@ -1799,7 +1859,13 @@ function ComposerPromptEditorTiptapInner( function insertMarkdownParagraphs( value: string, skillLabelFor: (name: string) => SkillMeta | null, - options: { styling: boolean; blocks?: boolean; literalText?: boolean; literalLength?: number }, + options: { + styling: boolean; + blocks?: boolean; + literalText?: boolean; + literalLength?: number; + isKnownModel?: IsKnownModel; + }, insertContent: (content: JSONContent[] | JSONContent) => void, ): void { const blocks = buildTiptapContent(value, skillLabelFor, options); diff --git a/apps/web/src/components/ContextChip.tsx b/apps/web/src/components/ContextChip.tsx index a536f28ccfb12..13a19167fe929 100644 --- a/apps/web/src/components/ContextChip.tsx +++ b/apps/web/src/components/ContextChip.tsx @@ -26,6 +26,7 @@ const contextChipVariants = cva( "pr-merged": "[--context-chip-accent:var(--context-chip-pr-merged)]", "pr-closed": "[--context-chip-accent:var(--context-chip-pr-closed)]", skill: "[--context-chip-accent:var(--context-chip-skill)]", + model: "[--context-chip-accent:var(--context-chip-model)]", thread: "[--context-chip-accent:var(--context-chip-thread)]", environment: "[--context-chip-accent:var(--context-chip-environment)]", citation: "[--context-chip-accent:var(--context-chip-citation)]", diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 875a2225d70a1..656012ae8a8e5 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -42,7 +42,6 @@ describe("sidebar header new thread", () => { { mode: "boring", count: 2, shift: false, picker: true }, { mode: "boring", count: 2, shift: true, picker: false }, { mode: "boring", count: 1, shift: false, picker: false }, - { mode: "legacy", count: 2, shift: false, picker: false }, ] as const)("$mode sidebar, $count projects, shift=$shift: picker=$picker", async (scenario) => { using stack = new DisposableStack(); const previousSettings = getClientSettings(); @@ -50,7 +49,6 @@ describe("sidebar header new thread", () => { __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, boringSidebarEnabled: scenario.mode === "boring", - legacySidebarEnabled: scenario.mode === "legacy", }); const projects = [project("active"), project("idle")].slice(0, scenario.count); const currentProjectRef = { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 0dfffc116dc06..8e28471392858 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -132,7 +132,7 @@ import { useTerminalFocus } from "../hooks/useTerminalFocus"; import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus"; import { registerSettleAndAdvance } from "../settleAndAdvance"; import { startNewThreadFromContext } from "../lib/chatThreadActions"; -import { useBoringSidebarEnabled, useClientSettings } from "../hooks/useSettings"; +import { useClientSettings } from "../hooks/useSettings"; import { useCopyToClipboard } from "../hooks/useCopyToClipboard"; import { useLocalStorage } from "../hooks/useLocalStorage"; import { useNowMinute } from "../hooks/useNowMinute"; @@ -985,8 +985,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); }, }); - const boringSidebarEnabled = useBoringSidebarEnabled(); - const legacySidebarEnabled = useClientSettings((settings) => settings.legacySidebarEnabled); + const boringSidebarEnabled = useClientSettings((settings) => settings.boringSidebarEnabled); const folderRowsMultiline = useClientSettings((settings) => settings.boringSidebarMultilineRows); const newThreadContext = useHandleNewThread(); // Row callbacks capture only the handler; the rest of the context changes with the route. @@ -1038,6 +1037,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const [renamingTitle, setRenamingTitle] = useState(""); const settlingThreadKeysRef = useRef(new Set()); const threadListRef = useRef(null); + const searchResultsListRef = useRef(null); const sidebarContentRef = useRef(null); const dragLabelOffsetRef = useRef(0); const listMotionRef = useRef | null>(null); @@ -1705,7 +1705,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }; }; - const isContextDrag = dragState?.contextDrag === true || dragState?.activeSection === "working"; + // Folder rows only drag out to the composer; folders own their order, so nothing drops in the list. + const isContextDrag = + projectFolders !== null || + dragState?.contextDrag === true || + dragState?.activeSection === "working"; const dragTargetSection = isContextDrag ? null : (dragState?.targetSection ?? null); const finishThreadDrag = (started: boolean) => { dragSensorRef.current = null; @@ -1734,7 +1738,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }); }; const pointerOutsideThreadList = (point: { x: number; y: number }) => { - const bounds = threadListRef.current?.getBoundingClientRect(); + // Search results replace the thread list, so only one of them is mounted. + const bounds = (threadListRef.current ?? searchResultsListRef.current)?.getBoundingClientRect(); return bounds !== undefined && (point.x < bounds.left || point.x > bounds.right); }; // The path out of the list often crosses dnd-kit's edge zone, which autoscrolls the sidebar. @@ -2069,6 +2074,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ); })(); const handleThreadDragEnd = (event: DragEndEvent) => { + if (projectFolders !== null) return; const activeKey = String(event.active.id); const activeSection = sectionByThreadKey.get(activeKey); const target = @@ -2939,7 +2945,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const handleNewThreadClick = (event?: ReactMouseEvent) => { if ( - legacySidebarEnabled || shouldCreateNewThreadInCurrentProject( event?.shiftKey ?? false, scopeGroups.length, @@ -3186,7 +3191,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve newThreadShortcutLabel={newThreadShortcutLabel} newThreadInProjectShortcutLabel={newThreadInProjectShortcutLabel} showNewThreadInProjectHint={ - !legacySidebarEnabled && !shouldCreateNewThreadInCurrentProject( false, scopeGroups.length, @@ -3217,57 +3221,66 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve closeDelay={0} timeout={400} > - + + ) : (

    ; + projectId?: ProjectId | null; copyMarkdown?: string; unreadable?: boolean; }) { const { environmentId, threadId } = props.record; const shell = useThreadShell({ environmentId, threadId }); - const project = useProject(shell ? scopeProjectRef(environmentId, shell.projectId) : null); - const title = shell?.title?.trim() || props.record.title; + const lookup = useEnvironmentQuery( + shell === null && props.projectId === undefined + ? orchestrationEnvironment.threadLinkMetadata({ + environmentId, + input: { threadIds: [threadId] }, + }) + : null, + ); + const metadata = lookup.data?.[threadId]; + const projectId = shell?.projectId ?? props.projectId ?? metadata?.projectId; + const project = useProject(projectId ? scopeProjectRef(environmentId, projectId) : null); + const title = shell?.title?.trim() || metadata?.title.trim() || props.record.title; return ( {props.unreadable ? "On another machine, so this machine's agent can't read it. Remove it or switch back to send." - : shell - ? "Open thread" - : "Thread no longer available"} + : "Open thread"} ); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index c436fb3c71dd8..6898b77f3971e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -18,7 +18,6 @@ import type { ProjectId, ThreadContextRecord, EnvironmentContextRecord, - ProviderInteractionMode, ResolvedKeybindingsConfig, RuntimeMode, RuntimeRequestId, @@ -38,7 +37,9 @@ import { import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import * as Schema from "effect/Schema"; +import { formatComposerModelMention } from "@t3tools/client-runtime/composer-model-mentions"; import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste"; +import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; import { splitTransferredFiles } from "./workspaceFileDrop"; import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; @@ -69,11 +70,7 @@ import { replaceTextRange, } from "../../composer-logic"; import { DEFAULT_COMPOSER_PLACEHOLDER } from "../../composerPlaceholder"; -import { - deriveComposerSendState, - resolveComposerInteractionMode, - threadShellHasStarted, -} from "../ChatView.logic"; +import { deriveComposerSendState } from "../ChatView.logic"; import { dataTransferHasComposerMention, makeComposerMentionDragHandlers, @@ -104,7 +101,6 @@ import { reconcileAttachmentContextReferences, useRetainedContextPayloads, } from "./composerContextUndo"; -import type { ThreadSyncPhase } from "../../threadSync"; import { ComposerBanner } from "./ComposerBanner"; import { ComposerSurface } from "./ComposerSurface"; import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack"; @@ -189,16 +185,11 @@ import { import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; import { ComposerFooterPrimaryActions } from "./ComposerFooterControls"; import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; -import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner"; import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight"; import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic"; import { getComposerPromptInjectionState, getComposerReasoningStep } from "./composerProviderState"; import { readPromptUltrathink } from "./TraitsPicker"; -import { - providerSupportsManualCompaction, - resolveContextWindowModelDisplayName, - shouldReserveContextWindowMeter, -} from "./ContextWindowMeter.logic"; +import { useApplyThreadModelPick } from "./useApplyThreadModelPick"; import { buildAttachmentVideoPreview, buildExpandedImagePreview, @@ -218,28 +209,22 @@ import { observeResize } from "~/lib/observeResize"; const isThreadTranscriptTooLargeError = Schema.is(OrchestrationThreadTranscriptTooLargeError); import { toastManager } from "../ui/toast"; import { PlayIcon } from "lucide-react"; -import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; import type { UnifiedSettings } from "@t3tools/contracts/settings"; -import { isVideoAttachment, type SessionPhase, type Thread, type ThreadShell } from "../../types"; +import { isVideoAttachment, type SessionPhase, type Thread } from "../../types"; import { type ComposerPromptHistoryPosition } from "./composerPromptHistory"; import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input"; -import type { - LatestProposedPlanState, - PendingApproval, - PendingUserInput, - TimelineEntry, -} from "../../session-logic"; +import type { PendingApproval, PendingUserInput, TimelineEntry } from "../../session-logic"; import { resolveComposerDispatchMode, type ComposerDispatchMode, } from "@t3tools/client-runtime/state/composer-dispatch"; -import { deriveLatestContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window"; import { resolveProviderSkillsForCwd, resolveProviderSlashCommandsForCwd, } from "@t3tools/client-runtime/providerSkills"; import { useMediaQuery } from "../../hooks/useMediaQuery"; +import { Kbd } from "../ui/kbd"; import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen"; import { useStableCallback } from "../../hooks/useStableCallback"; import { usePanelAnimationSettings } from "../../panelAnimations"; @@ -259,6 +244,8 @@ import { } from "./preparingComposerImages"; import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; +import { usePromptSuggestion } from "./usePromptSuggestion"; +import { useFreshSessionArmed } from "./freshSessionArms"; function consumePasteAsTextShortcut(deadline: { current: number }): boolean { const armed = Date.now() <= deadline.current; @@ -316,8 +303,6 @@ export interface ChatComposerHandle { selectedProvider: ProviderDriverKind; selectedModel: string; selectedProviderModels: ReadonlyArray; - interactionMode: ProviderInteractionMode; - interactionModeEnabled: boolean; shownPendingApprovalIds: ReadonlyArray; }; validateProviderInput: (providerInput: string) => boolean; @@ -343,7 +328,6 @@ export interface ChatComposerProps { activeThreadId: ThreadId | null; activeThread: Thread | undefined; - activeThreadShell: ThreadShell | null; promptHistoryEntries: ReadonlyArray; forceExpandedOnMobile: boolean; projectSelectionRequired: boolean; @@ -391,13 +375,8 @@ export interface ChatComposerProps { activePendingQuestionIndex: number; respondingRequestIds: RuntimeRequestId[]; - showPlanFollowUpPrompt: boolean; - activeProposedPlan: LatestProposedPlanState | null; - threadSyncPhase: ThreadSyncPhase | null; - runtimeMode: RuntimeMode; defaultRuntimeMode?: RuntimeMode; - interactionMode: ProviderInteractionMode; lockedProvider: ProviderDriverKind | null; providerStatuses: ServerProvider[]; @@ -407,12 +386,8 @@ export interface ChatComposerProps { reportedModelSelection?: ModelSelection | null; activeProjectId: ProjectId | null; - contextWindowEntries: Parameters[0]; - contextWindowLiveUsage: Parameters[1]; - contextWindowProviderThread: Parameters[2]; compactThreadUnavailable: boolean; compactDisabled: boolean; - compactDisabledReason: string | null; resolvedTheme: "light" | "dark"; settings: UnifiedSettings; @@ -449,7 +424,6 @@ export interface ChatComposerProps { ) => void; onResume: () => void; onInterrupt: () => void; - onImplementPlanInNewThread: () => void; onSelectActivePendingUserInputOption: (questionId: string, optionValue: string) => void; onAdvanceActivePendingUserInput: () => void; onDismissActivePendingUserInput: (requestId: RuntimeRequestId) => void; @@ -469,9 +443,7 @@ export interface ChatComposerProps { ) => void; onOpenProviderSetup: (instanceId: ProviderInstanceId) => void; getModelDisabledReason: (instanceId: ProviderInstanceId, model: string) => string | null; - toggleInteractionMode: () => void; handleRuntimeModeChange: (mode: RuntimeMode) => void; - handleInteractionModeChange: (mode: ProviderInteractionMode) => void; focusComposer: () => void; scheduleComposerFocus: () => void; @@ -522,10 +494,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingDraftAnswers, activePendingQuestionIndex, respondingRequestIds, - showPlanFollowUpPrompt, - activeProposedPlan, runtimeMode, - interactionMode: requestedInteractionMode, lockedProvider, providerStatuses, providerCatalogKnown, @@ -533,12 +502,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activeThreadModelSelection, reportedModelSelection, activeProjectId, - contextWindowEntries, - contextWindowLiveUsage, - contextWindowProviderThread, compactThreadUnavailable, compactDisabled, - compactDisabledReason, resolvedTheme, settings, keybindings, @@ -560,7 +525,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onSend, onResume, onInterrupt, - onImplementPlanInNewThread, onSelectActivePendingUserInputOption, onAdvanceActivePendingUserInput, onDismissActivePendingUserInput, @@ -569,9 +533,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onProviderModelSelect, onOpenProviderSetup, getModelDisabledReason, - toggleInteractionMode, handleRuntimeModeChange, - handleInteractionModeChange, focusComposer, scheduleComposerFocus, setThreadError, @@ -580,11 +542,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) editingQueuedAttachments, onRemoveEditingQueuedAttachment, } = props; - const activeContextWindow = deriveLatestContextWindowSnapshot( - contextWindowEntries, - contextWindowLiveUsage, - contextWindowProviderThread, - ); const composerDraftTargetKey = composerTargetKey(composerDraftTarget); const { heldRequestIds, @@ -613,6 +570,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const activePendingIsResponding = !holdingUserInput && incomingPendingIsResponding; const isLiteralPendingAnswer = activePendingProgress?.activeQuestion?.initialAnswer !== undefined; const isEditingQueuedMessage = editingQueuedAttachments !== null; + const applyThreadModelPick = useApplyThreadModelPick(); const composerDraft = useComposerThreadDraft(composerDraftTarget); const composerDraftTargetKeyRef = useRef(""); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed draft target key to a ref read by async handlers @@ -849,8 +807,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const providerSetupInstanceId = noProviderAvailable ? (unavailableProviderInstanceId ?? undefined) : undefined; - const resolvedCompactDisabledReason = - compactDisabledReason ?? (noProviderAvailable ? "Compacting is unavailable right now" : null); const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } = resolveCompatibleRuntimeMode( runtimeMode, @@ -869,7 +825,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) (multipleModelSelections === null ? providerSendBlockReason : null))); const isSendDisabled = sendDisabledReason !== null; const selectedProviderStatus = selectedProviderEntry?.snapshot ?? null; - const compactCommandAvailable = providerSupportsManualCompaction(selectedProviderEntry); const selectedProviderSkills = selectedProviderStatus ? resolveProviderSkillsForCwd(selectedProviderStatus, gitCwd) : NO_PROVIDER_SKILLS; @@ -885,11 +840,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const selectedPromptEffort = composerProviderState.promptEffort; const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch; - const { enabled: planModeUiEnabled, interactionMode } = resolveComposerInteractionMode({ - planModeEnabled: settings.planModeEnabled, - provider: selectedProviderStatus, - interactionMode: requestedInteractionMode, - }); const selectedModelSelection: ModelSelection = createModelSelection( selectedInstanceId, selectedModel, @@ -915,19 +865,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker); })(); - const activeThreadModelDisplayName = resolveContextWindowModelDisplayName( - activeThreadModelSelection, - modelOptionsByInstance, - ); - const reserveContextWindowMeter = shouldReserveContextWindowMeter({ - meterEnabled: settings.contextWindowMeterEnabled, - detailLoading: props.threadSyncPhase === "loading", - threadStarted: threadShellHasStarted(props.activeThreadShell), - providerReportsContextWindow: selectedProviderStatus - ? selectedProviderStatus.reportsContextWindow === true - : null, - }); - const [composerCursor, setComposerCursor] = useState(() => { const value = isLiteralPendingAnswer ? (activePendingProgress?.customAnswer ?? prompt) : prompt; return collapseExpandedComposerCursor(value, value.length, isLiteralPendingAnswer); @@ -1054,7 +991,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) pullRequestProjectId, pullRequestRepository, threadPullRequests, - planModeUiEnabled, sideChatAvailable: props.sideChatAvailable === true, sideChatDisabledReason: props.sideChatDisabledReason ?? null, freshSessionAvailable: props.onFreshSession !== undefined, @@ -1065,6 +1001,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) showSkillsInSlashMenu: settings.showSkillsInSlashMenu, workspaceSkillsScanning, questionAttachmentTarget, + modelMentions: { instanceEntries: providerInstanceEntries, modelOptionsByInstance }, }); const composerMenuOpen = Boolean(composerTrigger); @@ -1100,16 +1037,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const activePendingUserInput = pendingUserInputs[0] ?? null; const isChoiceOnlyPendingQuestion = activePendingProgress?.activeQuestion?.allowCustomAnswer === false; - const showComposerTopDrawer = - pendingUserInputs.length > 0 || - (!isComposerCollapsedMobile && showPlanFollowUpPrompt && activeProposedPlan !== null); + const showComposerTopDrawer = pendingUserInputs.length > 0; const showCollapsedMobilePromptRow = isComposerCollapsedMobile; const showComposerAttachAction = fileStagingLimit !== null && (!activePendingProgress || (supportsQuestionAttachments && activePendingProgress.activeQuestion?.allowCustomAnswer !== false)); - const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; + const composerFooterHasWideActions = activePendingProgress !== null; const editPromptFromTraits = (edit: (prompt: string) => string) => { const currentPrompt = getComposerDraft(composerDraftTarget)?.prompt ?? ""; @@ -1773,14 +1708,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (applied) setComposerHighlightedItemId(null); return; } - if (!planModeUiEnabled) return; - void handleInteractionModeChange(item.command === "plan" ? "plan" : "default"); - const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { - expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), - }); - if (applied) { - setComposerHighlightedItemId(null); - } return; } if (item.type === "provider-slash-command") { @@ -1862,6 +1789,22 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } return; } + if (item.type === "model") { + if (trigger.kind !== "path") return; + const replacement = `${formatComposerModelMention(item.instanceId, item.model)} `; + const replacementRangeEnd = extendReplacementRangeForTrailingSpace( + snapshot.value, + trigger.rangeEnd, + replacement, + ); + const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { + expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), + }); + if (applied) { + setComposerHighlightedItemId(null); + } + return; + } if (item.type === "environment") { if (trigger.kind !== "path") return; const record = environmentContextRecord(item.environmentId, item.label); @@ -1931,7 +1874,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (activePendingProgress) { return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); } - return showPlanFollowUpPrompt || composerSendState.hasSendableContent; + return composerSendState.hasSendableContent; }; const submitComposer = ( @@ -2069,6 +2012,26 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }; const expandMobileComposerStable = useStableCallback(expandMobileComposer); + // Escape dismisses the suggestion so Tab moves focus again. + const { suggestion: promptSuggestion, dismiss: dismissPromptSuggestion } = usePromptSuggestion( + environmentId, + activeThread, + ); + // After /clear the next message starts a fresh session that cannot see what the suggestion refers to. + const freshSessionArmed = useFreshSessionArmed(scopedThreadKey(routeThreadRef)); + // Offered only where the default placeholder would show, so it never hides a pending question. + const offeredPromptSuggestion = + phase !== "running" && + !isSendBusy && + !freshSessionArmed && + composerContextRecords.size === 0 && + !isComposerApprovalState && + !activePendingProgress && + !projectSelectionRequired && + !showProviderUnavailable + ? promptSuggestion + : null; + const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => composerCommandKeyHandler({ keybindings, @@ -2078,7 +2041,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isCompacting, followUpBehavior, isSoftwareKeyboardOpen, - planModeUiEnabled, isLiteralPendingAnswer, pendingUserInputs, promptHistoryEntries, @@ -2098,13 +2060,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) setComposerTrigger, setComposerHighlightedItemId, dismissComposerTrigger, - toggleInteractionMode, nudgeComposerMenuHighlight, onSelectComposerItem, resolveActiveComposerTrigger, readComposerSnapshot, applyPromptReplacement, submitComposer, + promptSuggestion: offeredPromptSuggestion, + dismissPromptSuggestion, })(key, event, isTaskItem); const { @@ -2194,13 +2157,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) reportedModelSelection={reportedModelSelection} promptUltrathink={promptUltrathink} onPromptEdit={editPromptFromTraitsStable} - planModeEnabled={settings.planModeEnabled} - planModeUiEnabled={planModeUiEnabled} - interactionMode={interactionMode} compatibleRuntimeMode={compatibleRuntimeMode} defaultRuntimeMode={props.defaultRuntimeMode} compatibleRuntimeModeOptions={compatibleRuntimeModeOptions} - toggleInteractionMode={toggleInteractionMode} handleRuntimeModeChange={handleRuntimeModeChange} composerControlsCollapsed={composerControlsCollapsed} effortDisplay={settings.effortDisplay} @@ -2562,12 +2521,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) void onInterrupt(); }; const handleInterruptPrimaryActionStable = useStableCallback(handleInterruptPrimaryAction); - const handleImplementPlanInNewThreadPrimaryAction = () => { - void onImplementPlanInNewThread(); - }; - const handleImplementPlanInNewThreadPrimaryActionStable = useStableCallback( - handleImplementPlanInNewThreadPrimaryAction, - ); const scheduleComposerCollapseCheck = () => { if (!isMobileViewport || mobileComposerExpandInFlightRef.current) { return; @@ -2687,7 +2640,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) reportedModelSelection, prompt: promptRef.current, cursor: readComposerSnapshotStable().expandedCursor, - planModeEnabled: settings.planModeEnabled, direction, }); if (!change) return; @@ -2698,6 +2650,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) model: selectedModel, persistSticky: true, }); + applyThreadModelPick(composerDraftTarget); if (change.prompt !== promptRef.current) { applyPromptReplacementStable(0, promptRef.current.length, change.prompt, { expandedCursorAfterReplace: change.cursor, @@ -2824,8 +2777,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedProvider, selectedModel, selectedProviderModels, - interactionMode, - interactionModeEnabled: planModeUiEnabled, }), setMultipleModelSelections, validateProviderInput: (providerInput: string) => { @@ -2877,7 +2828,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedModel, selectedInstanceId, reportedModelSelection, - settings.planModeEnabled, selectedModelSelection, multipleModelSelections, setMultipleModelSelections, @@ -2887,8 +2837,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedPromptEffort, selectedProvider, selectedProviderModels, - interactionMode, - planModeUiEnabled, compactThreadContextStable, ], ); @@ -3013,11 +2961,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onAdvance={onAdvanceActivePendingUserInput} onDismiss={onDismissActivePendingUserInput} /> - ) : !isComposerCollapsedMobile && showPlanFollowUpPrompt && activeProposedPlan ? ( - ) : null} @@ -3223,13 +3166,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? isChoiceOnlyPendingQuestion ? "Choose an option above" : "Type your own answer, or leave this blank to use the selected option" - : showPlanFollowUpPrompt && activeProposedPlan - ? "Add feedback to refine the plan, or leave this blank to implement it" - : projectSelectionRequired - ? "Choose a project above to start a thread" - : showProviderUnavailable - ? "Enable a provider in Settings to send a message" - : DEFAULT_COMPOSER_PLACEHOLDER + : projectSelectionRequired + ? "Choose a project above to start a thread" + : showProviderUnavailable + ? "Enable a provider in Settings to send a message" + : (offeredPromptSuggestion ?? DEFAULT_COMPOSER_PLACEHOLDER) + } + placeholderSuffix={ + offeredPromptSuggestion !== null ? ( + + ⇥ Tab + + ) : undefined } disabled={ projectSelectionRequired || @@ -3249,8 +3197,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) pendingAction={pendingPrimaryAction} isRunning={false} canInterrupt={false} - showPlanFollowUpPrompt={false} - promptHasText={false} isSendBusy={isSendBusy} sendDisabledReason={sendDisabledReason} isEnvironmentUnavailable={ @@ -3263,7 +3209,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) preserveComposerFocusOnPointerDown onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} onInterrupt={handleInterruptPrimaryActionStable} - onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryActionStable} /> ) : null} @@ -3303,11 +3248,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) 0} isSendBusy={isSendBusy} sendDisabledReason={sendDisabledReason} isEnvironmentUnavailable={ @@ -3348,15 +3284,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onResume={onResume} onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} onInterrupt={handleInterruptPrimaryActionStable} - onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryActionStable} compactBeforeSendTokens={props.resumeCompactionTokens} keepFullHistory={props.keepFullHistory} onToggleKeepFullHistory={props.onToggleKeepFullHistory} - compactDisabled={compactDisabled || noProviderAvailable || isSendBusy} - compactDisabledReason={resolvedCompactDisabledReason} - {...(compactCommandAvailable - ? { onCompactContext: compactThreadContextStable } - : {})} /> diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx index e5fbddf56c769..1472f55bf60b8 100644 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.tsx +++ b/apps/web/src/components/chat/CompactComposerControlsMenu.tsx @@ -1,29 +1,19 @@ -import { ProviderInteractionMode, RuntimeMode } from "@t3tools/contracts"; +import type { RuntimeMode } from "@t3tools/contracts"; import { memo, useRef } from "react"; import { EllipsisIcon } from "lucide-react"; -import { - Menu, - MenuPopup, - MenuRadioGroup, - MenuRadioItem, - MenuSeparator as MenuDivider, - MenuTrigger, -} from "../ui/menu"; +import { Menu, MenuPopup, MenuTrigger } from "../ui/menu"; import { ComposerControl, ComposerControlIcon } from "./ComposerControl"; import { focusRequestedPermission, useComposerMenuProps } from "./composerEventScope"; import { useComposerMenuState } from "./useComposerMenuState"; import { ComposerPermissionsSection, type RuntimeModeOption } from "./ComposerFooterControls"; export const CompactComposerControlsMenu = memo(function CompactComposerControlsMenu(props: { - interactionMode: ProviderInteractionMode; runtimeMode: RuntimeMode; runtimeModeOptions: ReadonlyArray; - showInteractionModeToggle: boolean; - showPermissions?: boolean; + showPermissions: boolean; size?: "sm" | "xs"; /** Close the portaled popup when its trigger hides. */ hidden?: boolean; - onToggleInteractionMode: () => void; onRuntimeModeChange: (mode: RuntimeMode) => void; }) { const composerFloatingLayerProps = useComposerMenuProps(); @@ -44,36 +34,20 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls size={size} className="shrink-0" aria-label="More composer controls" - data-composer-shortcut={props.showPermissions !== false ? "composer.mode" : undefined} + data-composer-shortcut={props.showPermissions ? "composer.mode" : undefined} /> } > - {props.showInteractionModeToggle ? ( - <> -

    Mode
    - { - if (!value || value === props.interactionMode) return; - props.onToggleInteractionMode(); - }} - > - Chat - Plan - - {props.showPermissions !== false ? : null} - - ) : null} - {props.showPermissions === false ? null : ( + {props.showPermissions ? ( - )} + ) : null} ); diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index 434c2c0358d17..ef84d7fd2958d 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -9,6 +9,7 @@ import { type EnvironmentMachineKind, type ProjectEntry, type ProviderDriverKind, + type ProviderInstanceId, type PullRequestContextMetadata, type ScopedThreadRef, type ServerProviderSkill, @@ -31,6 +32,7 @@ import { Badge } from "../ui/badge"; import { Command, CommandGroup, CommandItem, CommandList } from "../ui/command"; import { EnvironmentMachineIcon } from "../EnvironmentMachineIcon"; import { PierreEntryIcon } from "./PierreEntryIcon"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; import { ComposerBanner } from "./ComposerBanner"; import { resolvePullRequestState } from "../pullRequest/pullRequestPresentation"; @@ -88,6 +90,18 @@ export type ComposerCommandItem = machine: EnvironmentMachineKind; label: string; description: string; + } + | { + id: string; + type: "model"; + instanceId: ProviderInstanceId; + model: string; + driverKind: ProviderDriverKind; + providerDisplayName: string; + acpRegistryAgentId: string | undefined; + acpRegistryIconUrl: string | undefined; + label: string; + description: string; }; export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: { @@ -221,6 +235,16 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: { className="size-4 shrink-0 text-secondary-label" /> ) : null} + {props.item.type === "model" ? ( + + ) : null} {pullRequestPresentation ? ( string) => void; - planModeEnabled: boolean; - planModeUiEnabled: boolean; effortDisplay: EffortDisplay; /** The strip under a new thread names the permissions, so the row does not repeat them. */ permissionsShownInStrip: boolean; - interactionMode: ProviderInteractionMode; compatibleRuntimeMode: RuntimeMode; defaultRuntimeMode: RuntimeMode | undefined; compatibleRuntimeModeOptions: ReadonlyArray; - toggleInteractionMode: () => void; handleRuntimeModeChange: (mode: RuntimeMode) => void; composerControlsCollapsed: boolean; composerControlsHidden: boolean; @@ -102,13 +99,9 @@ export function ComposerControlsBar(props: { reportedModelSelection, promptUltrathink, onPromptEdit, - planModeEnabled, - planModeUiEnabled, - interactionMode, compatibleRuntimeMode, defaultRuntimeMode, compatibleRuntimeModeOptions, - toggleInteractionMode, handleRuntimeModeChange, composerControlsCollapsed, composerControlsHidden, @@ -147,15 +140,18 @@ export function ComposerControlsBar(props: { pickerOwnsModeShortcut, } = resolveComposerControlsOwnership({ matchesDefault: accessMatchesDefault || props.permissionsShownInStrip, - planModeUiEnabled, collapsed: composerControlsCollapsed, measuredHiddenBlockCount, }); const controlSize = composerControlsCollapsed ? "xs" : "sm"; + const applyThreadModelPick = useApplyThreadModelPick(); + const applyRouteThreadModelPick = useStableCallback(() => applyThreadModelPick(routeThreadRef)); const traitsInput = resolveComposerTraitsInput({ provider: selectedProvider, instanceId: selectedInstanceId, - ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}), + ...(routeKind === "server" + ? { threadRef: routeThreadRef, onDraftModelOptionsChange: applyRouteThreadModelPick } + : {}), ...(routeKind === "draft" && draftId ? { draftId } : {}), model: selectedModel, models: selectedProviderModels, @@ -163,7 +159,6 @@ export function ComposerControlsBar(props: { reportedModelSelection, promptUltrathink, onPromptEdit, - planModeEnabled, }); const effort = describeComposerEffort(traitsInput, props.effortDisplay, controlSize); const restingBlockDefs = showModeBlock @@ -172,15 +167,12 @@ export function ComposerControlsBar(props: { id: "mode", content: (