From 2fe7febc8d73dda7dcc912e8cca3cd65660a0c9d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:57:07 -0800 Subject: [PATCH 01/65] fix(server): workflow runs are started and changed only by callers at the broadest mode (#41977) Co-authored-by: Claude Fable 5.2 --- .../src/mcp/McpInvocationContext.test.ts | 10 ++ apps/server/src/mcp/McpInvocationContext.ts | 6 +- apps/server/src/mcp/McpToolAccess.test.ts | 24 +++++ apps/server/src/mcp/McpToolAccess.ts | 19 ++++ apps/server/src/mcp/threadAccess.ts | 18 ++++ .../mcp/toolkits/workflow/handlers.test.ts | 101 +++++++++++++++++- .../src/mcp/toolkits/workflow/handlers.ts | 2 +- docs/user/outside-agents.md | 6 +- 8 files changed, 181 insertions(+), 5 deletions(-) diff --git a/apps/server/src/mcp/McpInvocationContext.test.ts b/apps/server/src/mcp/McpInvocationContext.test.ts index 96c71fcd773f9..19769a840a8c8 100644 --- a/apps/server/src/mcp/McpInvocationContext.test.ts +++ b/apps/server/src/mcp/McpInvocationContext.test.ts @@ -94,4 +94,14 @@ it("acts at an administrator's ceiling for a client approved above it", () => { ).toEqual({ runtimeMode: "approval-required", interactionMode: "plan" }); expect(modes(scope("auto-accept-edits"), "auto").runtimeMode).toBe("auto-accept-edits"); expect(modes(scope("full-access")).runtimeMode).toBe("full-access"); + // The scope says what the ceiling is, for a thread caller too. + expect( + McpInvocationContext.withRuntimeModeCeiling(scope("full-access"), "auto").runtimeModeCeiling, + ).toBe("auto"); + expect( + McpInvocationContext.withRuntimeModeCeiling( + { ...scope("full-access"), client: undefined }, + "auto", + ).runtimeModeCeiling, + ).toBe("auto"); }); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 0ba10af2d8c45..9bd2f08f37445 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -126,10 +126,12 @@ export const withRuntimeModeCeiling = ( scope: McpInvocationScope, ceiling: RuntimeMode | undefined, ): McpInvocationScope => { - if (ceiling === undefined || scope.client === undefined) return scope; + if (ceiling === undefined) return scope; + if (scope.client === undefined) return { ...scope, runtimeModeCeiling: ceiling }; const asked = scope.client.narrowedTo; return { ...scope, + runtimeModeCeiling: ceiling, client: { ...scope.client, narrowedTo: { @@ -155,6 +157,8 @@ export interface McpInvocationScope { readonly linkedEnvironments?: boolean; /** The Agent feedback mode here; `/mcp` reads it per request. Unset is off. */ readonly agentFeedback?: AgentFeedbackMode; + /** The broadest runtime mode an administrator lets a thread run in here. Unset is full access. */ + readonly runtimeModeCeiling?: RuntimeMode | undefined; /** True while Labs → Workflows is on here; `/mcp` reads it per request. Unset is off. */ readonly workflows?: boolean; /** diff --git a/apps/server/src/mcp/McpToolAccess.test.ts b/apps/server/src/mcp/McpToolAccess.test.ts index 6cfd86bd3d836..cd1d28d37d4cf 100644 --- a/apps/server/src/mcp/McpToolAccess.test.ts +++ b/apps/server/src/mcp/McpToolAccess.test.ts @@ -137,6 +137,7 @@ const ProbeToolkit = Toolkit.make( }), }), Tool.make("writes_environment", probe), + Tool.make("writes_owner_work", probe), ); const ran = Effect.succeed({ ran: "ran" }); const probeHandlers: McpToolAccess.Handlers = { @@ -155,6 +156,7 @@ const probeHandlers: McpToolAccess.Handlers = { "stamped", ), writes_environment: McpToolAccess.writesEnvironment(() => ran), + writes_owner_work: McpToolAccess.writesOwnerWork("drive owner work", () => ran), }; const layerProbeHandlers = McpToolAccess.toLayer(ProbeToolkit, probeHandlers); @@ -194,6 +196,7 @@ export const refusedAtCompileTime = () => { writes_threads: unchecked, starts_threads: unchecked, writes_environment: unchecked, + writes_owner_work: unchecked, }), ); }; @@ -249,6 +252,15 @@ const fullAccessLinkedClient: McpInvocationContext.McpInvocationScope = { ...fullAccessClient, client: { ...fullAccessClient.client!, linked: true }, }; +// An administrator's ceiling narrows every client to it. +const atCeilingClient: McpInvocationContext.McpInvocationScope = { + ...fullAccessClient, + runtimeModeCeiling: "auto", + client: { + ...fullAccessClient.client!, + narrowedTo: { runtimeMode: "auto", interactionMode: "default" }, + }, +}; const previewOnly = { ...fullAccess, capabilities: new Set(["preview"] as const) }; it.effect.each([ @@ -321,6 +333,18 @@ it.effect.each([ ["writes_environment", plan, {}, "capability_denied"], ["writes_environment", fullAccessClient, {}, "ran"], ["writes_environment", supervisedClient, {}, "capability_denied"], + + ["writes_owner_work", fullAccess, {}, "ran"], + ["writes_owner_work", supervised, {}, "capability_denied"], + ["writes_owner_work", plan, {}, "capability_denied"], + ["writes_owner_work", ended, {}, "parent_not_active"], + ["writes_owner_work", fullAccessClient, {}, "ran"], + ["writes_owner_work", supervisedClient, {}, "capability_denied"], + ["writes_owner_work", readOnlyClient, {}, "capability_denied"], + ["writes_owner_work", linkedClient, {}, "capability_denied"], + ["writes_owner_work", fullAccessLinkedClient, {}, "ran"], + ["writes_owner_work", atCeilingClient, {}, "ran"], + ["writes_environment", atCeilingClient, {}, "capability_denied"], ] as const)("%s from %o with %o: %s", ([tool, scope, args, expected]) => call(tool, scope, args).pipe( Effect.map((outcome) => expect(outcome).toBe(expected)), diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index bbf090809c682..b179882661c3b 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -32,6 +32,7 @@ import { import * as McpInvocationContext from "./McpInvocationContext.ts"; import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts"; import { + assertBroadestAccess, assertFullAccess, assertLiveCaller, assertTargetWithinLimits, @@ -190,6 +191,24 @@ export const writes = ( () => orchestratingCaller, ); +/** + * Drives work that runs for this environment's owner in modes its definition picks, such as a + * workflow run. `what` names it in a refusal, after "can" or "cannot". + */ +export const writesOwnerWork = ( + what: string, + handle: (params: P) => Effect.Effect, +) => { + const check = orchestratingCaller.pipe( + Effect.tap((caller) => assertNotLinked(caller, what)), + Effect.tap((caller) => assertBroadestAccess(caller, what)), + ); + return declare( + (params: P) => check.pipe(Effect.flatMap(() => handle(params))), + () => check, + ); +}; + /** Requires handler capability checks, not thread control; linked work is refused the same way. */ export const writesWithCapability = (handle: (params: P) => Effect.Effect) => declare( diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.ts index d21495f0ff7c7..abcb7fcd29e05 100644 --- a/apps/server/src/mcp/threadAccess.ts +++ b/apps/server/src/mcp/threadAccess.ts @@ -5,6 +5,7 @@ import type { import { CommandId, type EnvironmentId, + isRuntimeModeAbove, OrchestratorMcpFailure, type ProjectId, type ProviderInstanceId, @@ -220,6 +221,23 @@ export const assertFullAccess = (context: Caller, message: string) => ? Effect.void : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message })); +/** + * For work whose definition picks its own modes: the caller must hold the broadest modes a + * thread may run in here, full access or an administrator's ceiling below it. + */ +export const assertBroadestAccess = (context: Caller, what: string) => { + const broadest = context.scope.runtimeModeCeiling ?? "full-access"; + return !isRuntimeModeAbove(broadest, context.limits.runtimeMode) && + context.limits.interactionMode === "default" + ? Effect.void + : Effect.fail( + new OrchestratorMcpFailure({ + code: "capability_denied", + message: `Only a caller with ${broadest}/default access can ${what}, because that work picks its own modes. This caller is limited to ${context.limits.runtimeMode}/${context.limits.interactionMode}.`, + }), + ); +}; + export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) => projectId !== undefined ? Effect.succeed(projectId) diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts index 77b7036681ad6..cc7a7242ddfd6 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -12,7 +12,13 @@ import * as McpToolAccessTestkit from "../../McpToolAccess.testkit.ts"; import * as WorkflowHandlers from "./handlers.ts"; import { WorkflowToolkit } from "./tools.ts"; -const handlersWith = (workflows: Partial) => +const fullAccess = { sessionId: "session-1", label: "t3 CLI", access: "full-access" } as const; +const supervised = { sessionId: "session-2", label: "Bot", access: "approval-required" } as const; + +const handlersWith = ( + workflows: Partial, + scope: Partial = {}, +) => McpToolAccess.HandlersLayer.layer(WorkflowHandlers.layer).pipe( Layer.provideMerge( Layer.mergeAll( @@ -22,9 +28,10 @@ const handlersWith = (workflows: Partial) => environmentId: EnvironmentId.make("environment:workflow"), requestNamespace: "client:workflow", thread: undefined, - client: { sessionId: "session-1", label: "t3 CLI", access: "full-access" }, + client: fullAccess, capabilities: new Set(["orchestration" as const]), issuedAt: 0, + ...scope, }), Layer.mock(Workflows.Workflows)(workflows), ), @@ -100,3 +107,93 @@ it.effect("signal refuses a run destination mixed with a channel destination", ( expect(delivered).toEqual([{ runId: "run-1", wait: "review" }]); }), ); + +const emptyRun = { run: undefined, steps: [], references: [] } as never; +const call = (input: Record) => + Effect.gen(function* () { + const toolkit = yield* WorkflowToolkit; + return yield* toolkit.handle("t3_workflow", input as never).pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((parts) => parts.at(-1)?.result), + ); + }); + +const changes = [ + { action: "start", workflow: "release", idempotencyKey: "trial" }, + { action: "signal", runId: "run-1", wait: "review", value: { choice: "yes" } }, + { action: "resume", runId: "run-1" }, + { action: "cancel", runId: "run-1" }, + { action: "store_set", key: "switch", value: true }, + { action: "store_delete", key: "switch" }, +]; + +it.effect("a caller below the broadest mode reads runs but does not start or change them", () => + Effect.gen(function* () { + const reached: Array = []; + const reach = (name: string) => () => Effect.sync(() => void reached.push(name)); + const results = yield* Effect.forEach( + [...changes, { action: "list" }, { action: "questions" }], + call, + ).pipe( + Effect.provide( + handlersWith( + { + start: () => Effect.sync(() => (reached.push("start"), { runId: "run-1" })), + signal: () => Effect.sync(() => (reached.push("signal"), "delivered" as const)), + resume: reach("resume"), + cancel: reach("cancel"), + storeSet: reach("storeSet"), + storeDelete: reach("storeDelete"), + stored: () => Effect.succeed([]), + get: () => Effect.succeed(emptyRun), + list: () => Effect.succeed([]), + questions: Effect.succeed([]), + }, + { client: supervised }, + ), + ), + ); + for (const result of results.slice(0, changes.length)) { + expect(result).toMatchObject({ code: "capability_denied" }); + } + expect(reached).toEqual([]); + expect(results.slice(changes.length)).toEqual([{ runs: [] }, { questions: [] }]); + }), +); + +it.effect("hook paths go only to a caller at the broadest mode", () => + Effect.gen(function* () { + const hooks = [{ workflow: "release", name: "push", path: "/api/hooks/wf-release.push/token" }]; + const read = (client: McpInvocationContext.McpClientCaller) => + call({ action: "hooks" }).pipe( + Effect.provide(handlersWith({ hooks: Effect.succeed(hooks as never) }, { client })), + ); + expect(yield* read(fullAccess)).toEqual({ hooks }); + const refused = yield* read(supervised); + expect(refused).toMatchObject({ code: "capability_denied" }); + expect(JSON.stringify(refused)).not.toContain("token"); + }), +); + +it.effect("under an administrator's ceiling, a caller at the ceiling starts runs", () => + Effect.gen(function* () { + const start = { action: "start", workflow: "release", idempotencyKey: "trial" }; + const workflows = { + start: () => Effect.succeed({ runId: "run-1" }), + get: () => Effect.succeed(emptyRun), + }; + const narrowedTo = (runtimeMode: "auto" | "approval-required") => ({ + runtimeModeCeiling: "auto" as const, + client: { ...fullAccess, narrowedTo: { runtimeMode, interactionMode: "default" as const } }, + }); + expect( + yield* call(start).pipe(Effect.provide(handlersWith(workflows, narrowedTo("auto")))), + ).not.toMatchObject({ code: "capability_denied" }); + expect( + yield* call(start).pipe( + Effect.provide(handlersWith(workflows, narrowedTo("approval-required"))), + ), + ).toMatchObject({ code: "capability_denied" }); + }), +); diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts index 7ebc6ac0cf7a4..0bc0c97d8e9fa 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts @@ -41,7 +41,7 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, { return yield* workflows.get(runId).pipe(Effect.mapError(refused)); }), ), - McpToolAccess.writes((input) => + McpToolAccess.writesOwnerWork("start or change workflow runs, or read hook paths", (input) => Effect.gen(function* () { const workflows = yield* Workflows.Workflows; // A hook's path holds its secret, and posting to it starts a run. diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index c322becf88531..0ef8c31e78c3f 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -78,7 +78,11 @@ policy. Approving without a code starts at **Read only**: the available providers and models. It cannot change anything. - **Supervised** through **Full access** also let it start, message and stop threads in every project. A thread it starts or steers cannot run with more - permissions than the mode you chose. + permissions than the mode you chose. [Workflow runs](workflows.md) choose + their own modes, so only **Full access** (or the highest mode your + organization's policy allows) can start, answer, resume or cancel them, + change what workflows store, or read webhook paths. Lower modes can still + read runs. ## What outside agents can call From 84a0c0516f53bfa3d0a9d64985f21083d757d93d Mon Sep 17 00:00:00 2001 From: Mick <105170334+mickroplastics@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:12:40 -0500 Subject: [PATCH 02/65] fix(server): an image answered to an async question shows as an attachment, not a file path (#41970) Co-authored-by: Julius Marminge --- .../Adapters/AcpAdapterV2.test.ts | 91 +++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 12 ++- .../ThreadMessageIntake.test.ts | 64 +++++++++++++ .../orchestration-v2/ThreadMessageIntake.ts | 37 ++++++-- .../src/orchestration-v2/runtimeLayer.test.ts | 41 +++++++++ packages/provider-acp/src/server/adapter.ts | 10 +- 6 files changed, 236 insertions(+), 19 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index f4ff952bf888d..90852f89dfa82 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -69,6 +69,7 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import { writeFakeCli } from "@t3tools/provider-testing/fakeCli"; import * as TestProviderHost from "@t3tools/provider-testing/TestProviderHost"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; import { ACP_EMPTY_OPTION_VALUE, @@ -13069,6 +13070,96 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.live("sends an image to an agent without image prompts as a file path", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const host = yield* ProviderHost.ProviderHost; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const sent: Array = []; + const instanceId = ProviderInstanceId.make("acp-test-image-without-image-prompts"); + const threadId = ThreadId.make("thread-acp-image-without-image-prompts"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + prompt: (payload, promptOptions) => + Effect.sync(() => void sent.push(payload.prompt)).pipe( + Effect.andThen(runtime.prompt(payload, promptOptions)), + ), + }), + }), + }, + }); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-image-without-prompts"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const screenshot = { + type: "image", + id: "screenshot-1", + name: "screenshot.png", + mimeType: "image/png", + sizeBytes: 8, + } as const; + const screenshotPath = host.resolveAttachmentPath(screenshot); + if (screenshotPath === null) return assert.fail("expected a screenshot path"); + yield* fileSystem.writeFile( + screenshotPath, + Uint8Array.of(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a), + ); + const base = makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + messageText: "What is in this screenshot?", + }); + + yield* runtime.startTurn({ + ...base, + message: { ...base.message, attachments: [screenshot] }, + }); + const terminal = yield* runtime.events.pipe( + Stream.filter((event) => event.type === "turn.terminal"), + Stream.runHead, + ); + + assert.equal(Option.getOrThrow(terminal).status, "completed"); + const blocks = sent[0] ?? []; + assert.deepEqual( + blocks.filter((block) => block.type !== "text"), + [], + ); + assert.include( + blocks.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n"), + `[Attached image "screenshot.png" is saved at: ${screenshotPath}]`, + ); + }).pipe(Effect.provide(layerTest)), + ); + it.live( "delivers changed appContext on steersWithPrompt and preserves undelivered notes on slash or failed steer", () => diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 10a986269e9bb..ac80a4d957aed 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -11714,15 +11714,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio continue; } const answered = isMessageQuestionAnswer(answer); - // Clients send "" for a skipped optional question, such as an attachment-only answer. - if (!answered && question.required === false) continue; - if (!answered) { + // Clients send "" for a skipped optional question or an attachment-only answer. + if (!answered && !command.attachmentsByQuestionId?.[question.id]?.length) { + if (question.required === false) continue; return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, cause: "Answer each question before sending.", }); } + if (!answered) { + replies.push(question.question); + continue; + } const text = typeof answer === "string" ? answer : answer.join(", "); replies.push(`${question.question}\n${text.trim()}`); } @@ -11920,7 +11924,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio threadId: command.threadId, messageId: MessageId.make(`async-answer:${command.requestId}`), text: replies.join("\n\n"), - attachments: [], + attachments: Object.values(command.attachmentsByQuestionId ?? {}).flat(), createdBy: "user" as const, creationSource: "server" as const, dispatchMode, diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts index 81fc56150d7fd..163d6a0d60b54 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.test.ts @@ -58,9 +58,16 @@ const layerFailingDispatchHandler = ); }; +const noPendingRuntimeRequests: ThreadManagementService.ThreadManagementServiceShape["getThreadRecords"] = + () => + Effect.succeed({ runtimeRequests: [] } as unknown as Effect.Success< + ReturnType + >); + const layerFailingDispatch = (captured: OrchestrationV2ServerCommand[]) => Layer.mock(ThreadManagementService.ThreadManagementService)({ dispatch: layerFailingDispatchHandler(captured), + getThreadRecords: noPendingRuntimeRequests, }); const NOW = DateTime.makeUnsafe("2026-09-13T00:00:00.000Z"); @@ -144,6 +151,60 @@ it.effect("claims question uploads and passes readable paths through the V2 requ }).pipe(Effect.provide(layerIntakeTest)), ); +it.effect("leaves an async answer's text alone so its files travel as message attachments", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const id = ChatAttachmentId.make(createPendingAttachmentId()!); + NodeFS.writeFileSync( + NodePath.join(config.attachmentsDir, `${id}.png`), + new Uint8Array([1, 2, 3]), + ); + const threadId = ThreadId.make("thread-async-answer"); + const requestId = RuntimeRequestId.make("request-async"); + const captured: OrchestrationV2ServerCommand[] = []; + yield* dispatchCommand({ + type: "runtime-request.respond", + commandId: CommandId.make("answer-async"), + threadId, + requestId, + answers: { q: "" }, + attachmentsByQuestionId: { + q: [{ type: "image", id, name: "screen.png", mimeType: "image/png", sizeBytes: 3 }], + }, + }).pipe( + Effect.provide( + Layer.mock(ThreadManagementService.ThreadManagementService)({ + dispatch: layerFailingDispatchHandler(captured), + getThreadRecords: () => + Effect.succeed({ + runtimeRequests: [ + { + id: requestId, + nodeId: null, + providerTurnId: null, + nativeRequestRef: null, + kind: "user_input", + status: "pending", + responseCapability: { type: "message" }, + createdAt: NOW, + resolvedAt: null, + }, + ], + } as unknown as Effect.Success< + ReturnType + >), + }), + ), + Effect.result, + ); + expect(captured).toHaveLength(1); + const command = captured[0]!; + if (command.type !== "runtime-request.respond") throw new Error("expected a response"); + expect(command.answers).toEqual({ q: "" }); + expect(command.attachmentsByQuestionId?.q).toHaveLength(1); + }).pipe(Effect.provide(layerIntakeTest)), +); + it.effect("retains claimed copies when dispatch failure may have been accepted", () => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; @@ -209,6 +270,7 @@ it.effect("releases claimed copies when the command was already rejected", () => }).pipe( Effect.provide( Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: noPendingRuntimeRequests, dispatch: (command) => Effect.fail( new OrchestratorCommandPreviouslyRejectedError({ @@ -276,6 +338,7 @@ it.effect("releases claimed copies when dispatch replays an earlier accepted res }).pipe( Effect.provide( Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: noPendingRuntimeRequests, dispatch: () => Effect.succeed({ sequence: 1, storedEvents }), }), ), @@ -346,6 +409,7 @@ it.effect("a retried response re-claims the preserved pending uploads", () => const retry = yield* dispatchCommand(command).pipe( Effect.provide( Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: noPendingRuntimeRequests, dispatch: (dispatched) => { captured.push(dispatched); return Effect.succeed({ sequence: 1, storedEvents: [] }); diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index 5d9ec263b0b0d..165a92ab4e3b4 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -156,15 +156,34 @@ export const dispatchCommand = Effect.fn("ThreadMessageIntake.dispatchCommand")( enumerable: true, }); } - const answers = yield* appendUserInputAttachmentPaths({ - answers: command.answers ?? {}, - attachmentsByQuestionId, - attachmentsDir: config.attachmentsDir, - }).pipe( - Effect.mapError( - (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }), - ), - ); + // An answer by message carries its files as message attachments, not paths in its text. + const { runtimeRequests } = yield* threads + .getThreadRecords(command.threadId, ["runtimeRequests"], { + runtimeRequestStatuses: ["pending"], + }) + .pipe( + Effect.mapError( + (cause) => + new AttachmentClaims.AttachmentClaimError({ + message: "Failed to read the question.", + cause, + }), + ), + ); + const answersByMessage = + runtimeRequests.find((request) => request.id === command.requestId)?.responseCapability + .type === "message"; + const answers = answersByMessage + ? (command.answers ?? {}) + : yield* appendUserInputAttachmentPaths({ + answers: command.answers ?? {}, + attachmentsByQuestionId, + attachmentsDir: config.attachmentsDir, + }).pipe( + Effect.mapError( + (cause) => new AttachmentClaims.AttachmentClaimError({ message: cause.issue }), + ), + ); return { answers, attachmentsByQuestionId }; }).pipe(Effect.onError(() => AttachmentClaims.releaseClaimedAttachments(claimedPaths))); return yield* threads diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 27091a5027bcd..370fd7deb9ade 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -2771,6 +2771,47 @@ it.layer(layerTest)("OrchestrationV2LayerLive", (it) => { }), ); + it.effect("sends an async answer's files as attachments on the answer message", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadId = ThreadId.make("runtime-async-question-files"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("runtime-async-question-files-create"), + createdBy: "user", + creationSource: "web", + threadId, + projectId: ProjectId.make("runtime-async-question-files-project"), + title: "Async question with files", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + const { requestId } = yield* seedPendingQuestion(threadId, null, { type: "message" }); + const screenshot = { + type: "image" as const, + id: createAttachmentId(threadId)!, + name: "screen.png", + mimeType: "image/png", + sizeBytes: 3, + }; + yield* orchestrator.dispatch({ + type: "runtime-request.respond", + commandId: CommandId.make("runtime-async-question-files-answer"), + threadId, + requestId, + answers: { color: "", sizes: ["Small"], note: "" }, + attachmentsByQuestionId: { color: [screenshot] }, + }); + const answered = yield* orchestrator.getThreadProjection(threadId); + assert.equal(answered.messages.length, 1); + assert.equal(answered.messages[0]?.text, "Which color?\n\nWhich sizes?\nSmall"); + assert.deepEqual(answered.messages[0]?.attachments, [screenshot]); + }), + ); + it.effect("reports an answer that never reaches its provider without reopening it", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index f72c40ed4c363..d4d8b0b54505b 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -9223,13 +9223,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( messageText: string, attachments: ReadonlyArray, ) { - if (!supportsImagePrompts && attachments.some(isProviderNativeImageAttachment)) { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver, - detail: "ACP driver did not negotiate image prompt support", - }); + // Without image prompts the saved path already in the message text is how the agent + // reaches the image; a flavor's own builder checks the capabilities it is handed. + if (!flavor.buildAttachmentPrompt) { + return supportsImagePrompts ? yield* imageAttachmentBlocks(attachments) : []; } - if (!flavor.buildAttachmentPrompt) return yield* imageAttachmentBlocks(attachments); const setup = yield* Ref.get(activeSessionSetup); return yield* flavor .buildAttachmentPrompt({ From a891304c84b75b5349c92787c30eb4e854ae57d5 Mon Sep 17 00:00:00 2001 From: Nawfal Ahmed <111358247+NawfalAhmed@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:27:40 +0500 Subject: [PATCH 03/65] fix(web): keep Codex Ultra off the effort bar scale (#30810) Co-authored-by: Julius Marminge --- .../src/components/chat/EffortGlyph.test.ts | 19 ++++++++++++------- apps/web/src/components/chat/EffortGlyph.tsx | 6 +++--- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/apps/web/src/components/chat/EffortGlyph.test.ts b/apps/web/src/components/chat/EffortGlyph.test.ts index 1c893050e0d41..934d9111feb36 100644 --- a/apps/web/src/components/chat/EffortGlyph.test.ts +++ b/apps/web/src/components/chat/EffortGlyph.test.ts @@ -16,20 +16,25 @@ describe("resolveEffortGlyph", () => { ["ultrathink"], ); + const codex = descriptor(["low", "medium", "high", "xhigh", "max", "ultra"]); + it("fills bars up to the current level and leaves max and workflow levels off the scale", () => { - expect(resolveEffortGlyph(claude, "xhigh")).toEqual({ - count: 4, - filled: 4, - special: null, - label: "Xhigh", - }); + for (const model of [claude, codex]) { + expect(resolveEffortGlyph(model, "xhigh")).toEqual({ + count: 4, + filled: 4, + special: null, + label: "Xhigh", + }); + } }); - it("names Max and Default instead of drawing them", () => { + it("names Max, Default, and Ultra instead of drawing them", () => { expect(resolveEffortGlyph(claude, "max")?.special).toBe("Max"); const reported = descriptor(["default", "low", "medium", "high", "xhigh", "max"]); expect(resolveEffortGlyph(reported, "default")?.special).toBe("Default"); expect(resolveEffortGlyph(reported, "low")).toMatchObject({ count: 4, filled: 1 }); + expect(resolveEffortGlyph(codex, "ultra")?.special).toBe("Ultra"); }); it("names Ultracode and Ultrathink instead of drawing a level", () => { diff --git a/apps/web/src/components/chat/EffortGlyph.tsx b/apps/web/src/components/chat/EffortGlyph.tsx index 8220a2b27272c..2158174405acd 100644 --- a/apps/web/src/components/chat/EffortGlyph.tsx +++ b/apps/web/src/components/chat/EffortGlyph.tsx @@ -11,15 +11,15 @@ const BASELINE_INSET = 2; type SelectDescriptor = Extract; // Older servers offer Ultracode as a level. It changes the workflow, so it keeps its name. -// Max is named too, so the full scale stops short of it. Default leaves the level to the agent. -const NAMED_LEVELS = new Set(["ultracode", "max", "default"]); +// Max and Ultra sit above the bar scale. Default leaves the level to the agent. +const NAMED_LEVELS = new Set(["ultracode", "max", "default", "ultra"]); const OFF_LEVELS = new Set(["off", "none"]); // More bars than this no longer fit the glyph's height in whole pixels. const MAX_BARS = 7; /** * Maps a reasoning select to bars: one per ordinary level, filled up to the current one, with an - * off level as none filled. Max, Default, prompt-injected and workflow levels are named instead. + * off level as none filled. Max, Default, Ultra, prompt-injected and workflow levels keep their names. */ export function resolveEffortGlyph(descriptor: SelectDescriptor, current: string | null) { const special = new Set([...(descriptor.promptInjectedValues ?? []), ...NAMED_LEVELS]); From de8551b05a9e3bc63fe60ca89a1b279dbe770457 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 00:35:44 -0800 Subject: [PATCH 04/65] fix(server): pull_request_review pins the review to the head the agent read (#41981) Co-authored-by: Claude Fable 5.2 --- .../toolkits/pullRequests/handlers.test.ts | 27 +++++++++++++++++++ .../src/mcp/toolkits/pullRequests/handlers.ts | 16 ++++++++++- .../src/mcp/toolkits/pullRequests/tools.ts | 3 ++- .../src/provider/agentContextBudget.json | 2 +- evals/mcp-tool-use/README.md | 2 +- evals/mcp-tool-use/cases/pull-requests.ndjson | 8 +++--- evals/mcp-tool-use/run.test.ts | 21 ++++++++++++++- evals/mcp-tool-use/run.ts | 12 ++++++++- .../src/server/GitLabPullRequestCli.test.ts | 23 ++++++++++++++++ .../src/server/GitLabPullRequestCli.ts | 7 +++++ 10 files changed, 111 insertions(+), 10 deletions(-) diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts index 95f816f151b9d..c031c5f947a10 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.test.ts @@ -1369,6 +1369,33 @@ describe("source control tools", () => { }), ); + it.effect("pins a review to the head the caller read, and approves only with one", () => + Effect.gen(function* () { + const reviews: Array = []; + const harness = yield* makeHarness({ + thread: branchThread, + pullRequests: { + submitReview: (input) => Effect.sync(() => void reviews.push(input)), + }, + }); + yield* harness.call("pull_request_review", { + verdict: "approve", + expectedHeadSha: "abc1234def5678", + }); + expect(reviews).toMatchObject([{ verdict: "approve", expectedHeadSha: "abc1234def5678" }]); + + const error = yield* harness + .call("pull_request_review", { verdict: "approve" }) + .pipe(Effect.flip); + expect(error.message).toContain("expectedHeadSha"); + expect(reviews).toHaveLength(1); + + yield* harness.call("pull_request_review", { verdict: "comment", body: "A question." }); + expect(reviews).toHaveLength(2); + expect(reviews[1]).not.toHaveProperty("expectedHeadSha"); + }), + ); + it.effect("updates labels, requests reviewers by login, and closes the PR", () => Effect.gen(function* () { const calls: Array = []; diff --git a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts index 646f94de8e541..db5fd3b5d5cce 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/handlers.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/handlers.ts @@ -1182,10 +1182,24 @@ const make = Effect.gen(function* () { ), pull_request_review: McpToolAccess.writesWithCapability((input) => Effect.gen(function* () { + if (input.verdict === "approve" && input.expectedHeadSha === undefined) { + return yield* new PullRequestForgeError({ + detail: + "Approving needs expectedHeadSha: the headSha pull_request_read reported for the commits you reviewed.", + }); + } const { target, ref } = yield* locate(input); const comments = yield* reviewComments(ref, input.comments ?? []); yield* pullRequests - .submitReview({ ...ref, verdict: input.verdict, body: input.body ?? "", comments }) + .submitReview({ + ...ref, + verdict: input.verdict, + body: input.body ?? "", + comments, + ...(input.expectedHeadSha === undefined + ? {} + : { expectedHeadSha: input.expectedHeadSha }), + }) .pipe(Effect.mapError(forgeFailure)); return identityOf(target); }), diff --git a/apps/server/src/mcp/toolkits/pullRequests/tools.ts b/apps/server/src/mcp/toolkits/pullRequests/tools.ts index 446b300b9a40b..45edd39081881 100644 --- a/apps/server/src/mcp/toolkits/pullRequests/tools.ts +++ b/apps/server/src/mcp/toolkits/pullRequests/tools.ts @@ -767,10 +767,11 @@ export type ReviewLineComment = typeof ReviewLineComment.Type; const ReviewPullRequestTool = Tool.make("pull_request_review", { description: - "Submit a review: approve, request changes, or comment, with optional line comments.", + "Submit a review: approve, request changes, or comment, with optional line comments. Approving needs expectedHeadSha (headSha in pull_request_read). Refuses if the head moved from it.", parameters: Schema.Struct({ ...ThreadPullRequestInput.fields, verdict: PullRequestReviewVerdict, + expectedHeadSha: Schema.optional(TrimmedNonEmptyString), body: Schema.optional(Schema.String), comments: Schema.optional(Schema.Array(ReviewLineComment).check(Schema.isMaxLength(50))), }), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 26f4f6719e9c4..4089b32f80569 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6245, "codexAdditionalContextBytes": 7639, - "mcpToolListJsonBytes": 61709 + "mcpToolListJsonBytes": 61844 } diff --git a/evals/mcp-tool-use/README.md b/evals/mcp-tool-use/README.md index 32a97d15bc4f8..4d0a5b011b73d 100644 --- a/evals/mcp-tool-use/README.md +++ b/evals/mcp-tool-use/README.md @@ -302,7 +302,7 @@ pnpm mcp-tool-use:compare runs/tools/results.jsonl runs/raw/results.jsonl `compare` regrades every row with this checkout's cases and prints, per case and arm: pass rate, model calls, forge calls (T3 forge tools plus `gh`/`cafe`/`glab`/`src` commands), failed forge calls, forge output in KB, requested sleep, `--help` calls, tokens and cost. Cost charges cache writes as cache reads, so the order the runs went in doesn't decide which arm looks cheaper. -Both arms see the same world. Shell mocks apply to either arm's commands, so an agent in the tools arm that reaches for `gh` hits the same rate limit. Where the real tools refuse, the tools arm is refused too: `world.unpushed` makes `pull_request_create` fail until a `git push`, and `pull_request_merge` compares `expectedHeadSha` with the full head, as `PullRequestService` does. A `{"$error": "..."}` mock fails any T3 tool with that text. `expectRaw` grades the raw arm when its right outcome differs: only T3 can watch a PR, so the raw arm passes `cli-babysit-green` by waiting on the checks. +Both arms see the same world. Shell mocks apply to either arm's commands, so an agent in the tools arm that reaches for `gh` hits the same rate limit. Where the real tools refuse, the tools arm is refused too: `world.unpushed` makes `pull_request_create` fail until a `git push`, `pull_request_merge` and `pull_request_review` compare `expectedHeadSha` with the full head, as `PullRequestService` does, and an approval without one is refused. A `{"$error": "..."}` mock fails any T3 tool with that text. `expectRaw` grades the raw arm when its right outcome differs: only T3 can watch a PR, so the raw arm passes `cli-babysit-green` by waiting on the checks. Some cases are capability cases rather than mistake cases: diff --git a/evals/mcp-tool-use/cases/pull-requests.ndjson b/evals/mcp-tool-use/cases/pull-requests.ndjson index c2b049d3f4724..3fe9f810a33cb 100644 --- a/evals/mcp-tool-use/cases/pull-requests.ndjson +++ b/evals/mcp-tool-use/cases/pull-requests.ndjson @@ -46,10 +46,10 @@ {"id": "pr-checks-through-gh", "area": "pull-requests", "kind": "bad", "pattern": "CI status read with gh pr checks", "experience": "Agents checked a PR's CI with gh pr checks, gh pr view --json statusCheckRollup, or gh run list instead of T3's PR tools.", "rule": "pull_request_read replaces gh and cafe for PR state and checks", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_read": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "title": "feat(config): read the port from the environment", "state": "open", "isDraft": false, "author": "user", "headBranch": "feat/config-const", "baseBranch": "main", "headSha": "abc1234def5678", "mergeability": "mergeable", "behindBy": 0, "autoMergeEnabled": false, "checks": {"passed": 1, "pending": 1, "failed": []}, "unresolvedThreads": 0}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Is CI green on my PR yet?", "expect": {"calls": [{"tool": "pull_request_read"}], "shellMustNot": ["\\bgh (pr (checks|view|status)|run (list|view|watch)|api)\\b", "\\bcafe (pr|ci)\\b"]}, "notes": "Forge usage audit of agent logs on three machines (2026-10-28): agents ran gh and cafe for PR work about 18,000 times in 45 days, which spends the user's own API quota instead of T3's sign-in."} {"id": "pr-list-through-gh", "area": "pull-requests", "kind": "bad", "pattern": "PR lists read with gh pr list", "experience": "Agents listed PRs with gh pr list or gh search prs, often trimming JSON with --jq, instead of T3's PR tools.", "rule": "pull_request_list replaces gh and cafe for listing PRs", "privacy": "commit-safe", "setup": {"role": "top", "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}, {"number": 125, "title": "fix(ws): back off reconnects", "headRefName": "fix/ws-backoff", "checks": []}]}}, "prompt": "Which open PRs in this repo are waiting on my review?", "expect": {"calls": [{"tool": "pull_request_list", "args": {"involvement": "reviewing"}}], "shellMustNot": ["\\bgh (pr list|search prs|api)\\b", "\\bcafe pr list\\b"]}, "notes": "Forge usage audit of agent logs on three machines (2026-10-28): agents ran gh and cafe for PR work about 18,000 times in 45 days, which spends the user's own API quota instead of T3's sign-in."} {"id": "pr-edit-through-gh", "area": "pull-requests", "kind": "bad", "pattern": "PR edited with gh pr edit and gh pr ready", "experience": "Agents retitled PRs and marked them ready with gh pr edit and gh pr ready instead of T3's PR tools.", "rule": "pull_request_update replaces gh and cafe for editing a PR", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_update": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Retitle #124 to \"fix(config): read the port from PORT\" and mark it ready for review.", "expect": {"calls": [{"tool": "pull_request_update", "args": {"number": 124, "title": "~read the port from PORT", "ready": true}}], "shellMustNot": ["\\bgh (pr (edit|ready)|api)\\b", "\\bcafe pr (edit|ready)\\b"]}, "notes": "Forge usage audit of agent logs on three machines (2026-10-28): agents ran gh and cafe for PR work about 18,000 times in 45 days, which spends the user's own API quota instead of T3's sign-in."} -{"id": "pr-approve-through-gh", "area": "pull-requests", "kind": "bad", "pattern": "PR approved with gh pr review", "experience": "Before pull_request_review, approving took gh pr review or cafe pr review, on the user's own API quota.", "rule": "pull_request_review replaces gh and cafe for reviews", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_read": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "title": "feat(config): read the port from the environment", "state": "open", "isDraft": false, "author": "user", "headBranch": "feat/config-const", "baseBranch": "main", "headSha": "abc1234def5678", "mergeability": "mergeable", "behindBy": 0, "autoMergeEnabled": false, "checks": {"passed": 2, "pending": 0, "failed": []}, "unresolvedThreads": 0}, "pull_request_review": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "#124 looks good to me. Approve it.", "expect": {"calls": [{"tool": "pull_request_review", "args": {"number": 124, "verdict": "approve"}}], "shellMustNot": ["\\bgh (pr review|api)\\b", "\\bcafe pr review\\b"]}, "notes": "pull_request_review added 2026-11-12."} -{"id": "pr-request-changes-on-a-line", "area": "pull-requests", "kind": "bad", "pattern": "changes requested with gh pr review or gh api", "experience": "Before pull_request_review, line comments took gh api or cafe pr review, on the user's own API quota.", "rule": "pull_request_review replaces gh and cafe for reviews, line comments included", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_read": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "title": "feat(config): read the port from the environment", "state": "open", "isDraft": false, "author": "user", "headBranch": "feat/config-const", "baseBranch": "main", "headSha": "abc1234def5678", "mergeability": "mergeable", "behindBy": 0, "autoMergeEnabled": false, "checks": {"passed": 2, "pending": 0, "failed": []}, "unresolvedThreads": 0}, "pull_request_review": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Request changes on #124: PORT isn't validated, so a typo gives NaN. Put that on the line in src/config.ts that reads it.", "expect": {"calls": [{"tool": "pull_request_review", "args": {"number": 124, "verdict": "request-changes", "comments": [{"path": "src/config.ts", "line": 1}]}}], "shellMustNot": ["\\bgh (pr review|api)\\b", "\\bcafe pr review\\b"]}, "notes": "pull_request_review added 2026-11-12."} -{"id": "control-review-no-approve", "area": "pull-requests", "kind": "control", "pattern": "asked to review a clean PR", "experience": "Control: reviewing a clean PR. Reporting back or a comment review is fine; an approval under the user's account was not asked for.", "rule": "Approve only when asked", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_read": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "title": "feat(config): read the port from the environment", "state": "open", "isDraft": false, "author": "user", "headBranch": "feat/config-const", "baseBranch": "main", "headSha": "abc1234def5678", "mergeability": "mergeable", "behindBy": 0, "autoMergeEnabled": false, "checks": {"passed": 2, "pending": 0, "failed": []}, "unresolvedThreads": 0}, "pull_request_review": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Review #124.", "expect": {"callsMustNot": [{"tool": "pull_request_review", "args": {"verdict": "approve"}}], "shellMustNot": ["\\bgh pr review\\b[^\\n]*(--approve|-a\\b)", "\\bcafe pr review\\b[^\\n]*approve", "\\bgh api\\b[^\\n]*\\bAPPROVE\\b"]}, "notes": "Control for pr-approve-through-gh. Measures whether the review tool needs an approve-only-when-asked line."} -{"id": "control-feedback-no-review", "area": "pull-requests", "kind": "control", "pattern": "question about open review feedback", "experience": "Control: the user asks what feedback is open. Reading is fine; submitting a review was not asked.", "rule": "Answer questions about reviews without submitting one", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_read": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "title": "feat(config): read the port from the environment", "state": "open", "isDraft": false, "author": "user", "headBranch": "feat/config-const", "baseBranch": "main", "headSha": "abc1234def5678", "mergeability": "mergeable", "behindBy": 0, "autoMergeEnabled": false, "checks": {"passed": 2, "pending": 0, "failed": []}, "unresolvedThreads": 1, "conversation": {"comments": [], "reviewThreads": [{"id": "thread-1", "path": "src/config.ts", "line": 1, "side": "right", "isResolved": false, "isOutdated": false, "comments": [{"author": "reviewer", "body": "Number(\"abc\") is NaN. Validate PORT before using it.", "createdAt": "2026-11-11T09:00:00Z"}], "moreComments": false}], "nextCursor": null, "truncated": false}}, "pull_request_review": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "What feedback is still open on #124?", "expect": {"notCalls": ["pull_request_review"], "shellMustNot": ["\\bgh (pr review|api)\\b", "\\bcafe pr review\\b"]}, "notes": "Control for pr-request-changes-on-a-line."} +{"id": "pr-approve-through-gh", "area": "pull-requests", "kind": "bad", "pattern": "PR approved with gh pr review", "experience": "Before pull_request_review, approving took gh pr review or cafe pr review, on the user's own API quota.", "rule": "pull_request_review replaces gh and cafe for reviews", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_read": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "title": "feat(config): read the port from the environment", "state": "open", "isDraft": false, "author": "user", "headBranch": "feat/config-const", "baseBranch": "main", "headSha": "abc1234def5678", "mergeability": "mergeable", "behindBy": 0, "autoMergeEnabled": false, "checks": {"passed": 2, "pending": 0, "failed": []}, "unresolvedThreads": 0}, "pull_request_review": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "headRefOid": "abc1234def5678", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "#124 looks good to me. Approve it.", "expect": {"calls": [{"tool": "pull_request_review", "args": {"number": 124, "verdict": "approve"}}], "shellMustNot": ["\\bgh (pr review|api)\\b", "\\bcafe pr review\\b"]}, "notes": "pull_request_review added 2026-11-12."} +{"id": "pr-request-changes-on-a-line", "area": "pull-requests", "kind": "bad", "pattern": "changes requested with gh pr review or gh api", "experience": "Before pull_request_review, line comments took gh api or cafe pr review, on the user's own API quota.", "rule": "pull_request_review replaces gh and cafe for reviews, line comments included", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_read": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "title": "feat(config): read the port from the environment", "state": "open", "isDraft": false, "author": "user", "headBranch": "feat/config-const", "baseBranch": "main", "headSha": "abc1234def5678", "mergeability": "mergeable", "behindBy": 0, "autoMergeEnabled": false, "checks": {"passed": 2, "pending": 0, "failed": []}, "unresolvedThreads": 0}, "pull_request_review": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "headRefOid": "abc1234def5678", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Request changes on #124: PORT isn't validated, so a typo gives NaN. Put that on the line in src/config.ts that reads it.", "expect": {"calls": [{"tool": "pull_request_review", "args": {"number": 124, "verdict": "request-changes", "comments": [{"path": "src/config.ts", "line": 1}]}}], "shellMustNot": ["\\bgh (pr review|api)\\b", "\\bcafe pr review\\b"]}, "notes": "pull_request_review added 2026-11-12."} +{"id": "control-review-no-approve", "area": "pull-requests", "kind": "control", "pattern": "asked to review a clean PR", "experience": "Control: reviewing a clean PR. Reporting back or a comment review is fine; an approval under the user's account was not asked for.", "rule": "Approve only when asked", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_read": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "title": "feat(config): read the port from the environment", "state": "open", "isDraft": false, "author": "user", "headBranch": "feat/config-const", "baseBranch": "main", "headSha": "abc1234def5678", "mergeability": "mergeable", "behindBy": 0, "autoMergeEnabled": false, "checks": {"passed": 2, "pending": 0, "failed": []}, "unresolvedThreads": 0}, "pull_request_review": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "headRefOid": "abc1234def5678", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Review #124.", "expect": {"callsMustNot": [{"tool": "pull_request_review", "args": {"verdict": "approve"}}], "shellMustNot": ["\\bgh pr review\\b[^\\n]*(--approve|-a\\b)", "\\bcafe pr review\\b[^\\n]*approve", "\\bgh api\\b[^\\n]*\\bAPPROVE\\b"]}, "notes": "Control for pr-approve-through-gh. Measures whether the review tool needs an approve-only-when-asked line."} +{"id": "control-feedback-no-review", "area": "pull-requests", "kind": "control", "pattern": "question about open review feedback", "experience": "Control: the user asks what feedback is open. Reading is fine; submitting a review was not asked.", "rule": "Answer questions about reviews without submitting one", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_read": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124", "title": "feat(config): read the port from the environment", "state": "open", "isDraft": false, "author": "user", "headBranch": "feat/config-const", "baseBranch": "main", "headSha": "abc1234def5678", "mergeability": "mergeable", "behindBy": 0, "autoMergeEnabled": false, "checks": {"passed": 2, "pending": 0, "failed": []}, "unresolvedThreads": 1, "conversation": {"comments": [], "reviewThreads": [{"id": "thread-1", "path": "src/config.ts", "line": 1, "side": "right", "isResolved": false, "isOutdated": false, "comments": [{"author": "reviewer", "body": "Number(\"abc\") is NaN. Validate PORT before using it.", "createdAt": "2026-11-11T09:00:00Z"}], "moreComments": false}], "nextCursor": null, "truncated": false}}, "pull_request_review": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "headRefOid": "abc1234def5678", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "What feedback is still open on #124?", "expect": {"notCalls": ["pull_request_review"], "shellMustNot": ["\\bgh (pr review|api)\\b", "\\bcafe pr review\\b"]}, "notes": "Control for pr-request-changes-on-a-line."} {"id": "pr-labels-reviewers-through-gh", "area": "pull-requests", "kind": "bad", "pattern": "labels and reviewers set with gh pr edit", "experience": "Before pull_request_update took labels and reviewers, agents needed gh pr edit or cafe pr edit for them.", "rule": "pull_request_update replaces gh and cafe for labels and reviewers", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_update": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Label PR #124 bug and ask octo to review it.", "expect": {"calls": [{"tool": "pull_request_update", "args": {"number": 124, "addLabels": ["bug"], "requestReviewers": ["~octo"]}}], "shellMustNot": ["\\bgh (pr edit|api)\\b", "\\bcafe pr edit\\b"]}, "notes": "Forge usage audit of agent logs on three machines (2026-10-28): agents ran gh and cafe for PR work about 18,000 times in 45 days, which spends the user's own API quota instead of T3's sign-in."} {"id": "pr-close-through-gh", "area": "pull-requests", "kind": "bad", "pattern": "PR closed with gh pr close", "experience": "Before pull_request_update took state, closing a PR needed gh pr close or cafe pr close.", "rule": "pull_request_update replaces gh and cafe for closing and reopening", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"pull_request_update": {"host": "github.com", "repository": "acme/app", "number": 124, "url": "https://github.com/acme/app/pull/124"}}, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}, "prs": [{"number": 124, "title": "feat(config): read the port from the environment", "headRefName": "feat/config-const", "checks": [{"name": "Lint", "state": "pass"}, {"name": "Test", "state": "pass"}]}]}}, "prompt": "Close PR #124, we're going a different way.", "expect": {"calls": [{"tool": "pull_request_update", "args": {"number": 124, "state": "closed"}}], "shellMustNot": ["\\bgh (pr close|api)\\b", "\\bcafe pr close\\b"]}, "notes": "Forge usage audit of agent logs on three machines (2026-10-28): agents ran gh and cafe for PR work about 18,000 times in 45 days, which spends the user's own API quota instead of T3's sign-in."} {"id": "no-forge-open-pr", "area": "pull-requests", "kind": "guard", "pattern": "PR asked for in a project with no forge", "experience": "T3 hides its PR tools where the project is on no forge T3 reads, while the always-loaded PR instructions still point PR work at them. Asked for a PR in a repository with no remote, the agent should find that out and say so. Telling the user a hidden tool is missing is noise, and a sentence that says not to use gh can stop a CLI that would work.", "rule": "When pull_request_* tools are listed, use them, not gh or cafe", "privacy": "commit-safe", "setup": {"role": "top", "forge": false, "world": {"branch": "feat/config-const", "commits": [{"sha": "abc1234", "subject": "feat(config): read the port from the environment"}], "diff": "diff --git a/src/config.ts b/src/config.ts\n--- a/src/config.ts\n+++ b/src/config.ts\n@@ -1,3 +1,3 @@\n-let port = 3000;\n+let port = Number(process.env.PORT ?? 3000);\n export default { port };\n", "files": {"src/config.ts": "let port = Number(process.env.PORT ?? 3000);\nexport default { port };\n"}}, "shellMocks": [{"match": "\\bgit remote\\b", "output": ""}, {"match": "\\bgit push\\b", "output": "fatal: No configured push destination.\nEither specify the URL from the command-line or configure a remote repository using\n\n git remote add \n\nand then push using the remote name\n\n git push \n"}, {"match": "\\b(gh|cafe|glab)\\b", "output": "none of the git remotes configured for this repository point to a known host"}]}, "prompt": "Open a PR for this branch.", "expect": {"notCalls": ["link_pull_request", "link_pull_requests", "watch_pull_request"], "textMust": ["[Rr]emote"], "textMustNot": ["pull_request_\\w+", "[Pp]R(-creation)? tool"]}, "notes": "Added with the no-forge gate on the forge tools (2026-11-12)."} diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.ts index 96891e2920949..2bbb8b426e3bb 100644 --- a/evals/mcp-tool-use/run.test.ts +++ b/evals/mcp-tool-use/run.test.ts @@ -1526,7 +1526,12 @@ it.effect("the raw arm drops T3's forge tools and text; both arms meet T3's refu const mocks = { ci_rerun: { $error: "GitHub API rate limit exceeded." } }; const setup = { ...childCase.setup, role: "top" as const, priorTurns: [], world, mocks }; const sample = makeSample({ ...childCase, setup }, tools); - for (const name of ["pull_request_create", "pull_request_merge", "ci_rerun"]) { + for (const name of [ + "pull_request_create", + "pull_request_merge", + "pull_request_review", + "ci_rerun", + ]) { sample.tools.push({ name: `mcp__t3-code__${name}` }); } const config = { @@ -1572,6 +1577,20 @@ it.effect("the raw arm drops T3's forge tools and text; both arms meet T3's refu const full = yield* call("d", "pull_request_merge", { number: 7, expectedHeadSha: head }); assert.isNotTrue(full.is_error); + const unpinned = yield* call("e", "pull_request_review", { number: 7, verdict: "approve" }); + assert.include(String(unpinned.content), "Approving needs expectedHeadSha"); + const stale = { number: 7, verdict: "approve", expectedHeadSha: "c3a91f2" }; + assert.isTrue((yield* call("f", "pull_request_review", stale)).is_error); + const pinned = { number: 7, verdict: "approve", expectedHeadSha: head }; + assert.isNotTrue((yield* call("g", "pull_request_review", pinned)).is_error); + assert.isNotTrue( + (yield* call("h", "pull_request_review", { + number: 7, + verdict: "comment", + body: "A question.", + })).is_error, + ); + // Without headRefOid, the branch's own PR is at the checkout's latest commit, as reads say. const ownSetup = { ...setup, diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index 817b916ebe1a6..f54f6e520c43d 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -2203,7 +2203,17 @@ const productRefusal = (sample: Sample, name: string, input: Readonly Number(candidate.number) === number); diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts index 634e771b86ec4..9bb56dd58f5e9 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts @@ -1804,6 +1804,29 @@ layer("GitLabPullRequestCli.layer", (it) => { }), ); + it.effect("approves at the head the caller reviewed", () => + Effect.gen(function* () { + mockedExecute.mockReturnValue(Effect.succeed(output("{}"))); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + const approval = { + cwd: "/w", + repository: "acme/web", + number: 7, + verdict: "approve" as const, + body: "", + comments: [], + }; + + yield* cli.submitReview({ ...approval, expectedHeadSha: "0a1b2c3d4e5f" }); + expect(argsOfCall(0)[1]).toContain("merge_requests/7/approve"); + expect(JSON.parse(callAt(0).stdin ?? "{}")).toEqual({ sha: "0a1b2c3d4e5f" }); + + yield* cli.submitReview(approval); + expect(argsOfCall(1)[1]).toContain("merge_requests/7/approve"); + expect(callAt(1).stdin).toBeUndefined(); + }), + ); + it.effect("requests changes as a reviewer and reports what GitLab refused", () => Effect.gen(function* () { mockedExecute diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts index b14557bf9934e..c23f7ebdc9049 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts @@ -645,6 +645,8 @@ export class GitLabPullRequestCli extends Context.Service< readonly verdict: PullRequestReviewVerdict; readonly body: string; readonly comments: ReadonlyArray; + /** The head the caller reviewed; an approval refuses any other. */ + readonly expectedHeadSha?: string; }) => Effect.Effect; readonly replyToDiscussion: (input: { @@ -3037,6 +3039,11 @@ export const make = Effect.gen(function* () { host: input.host, path: `${mergeRequest}/approve`, method: "POST", + // GitLab answers 409 when `sha` is no longer the merge request's head. + ...(input.expectedHeadSha === undefined + ? {} + : // @effect-diagnostics-next-line globalJsonInEffect:off + { stdin: JSON.stringify({ sha: input.expectedHeadSha }) }), }); } }), From 60682f7b01bc37e45785f606be5c76e6467d6be9 Mon Sep 17 00:00:00 2001 From: Joseph Vidal <135430578+josephv123@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:40:04 -0500 Subject: [PATCH 05/65] fix(server): a Claude background sleep timer wakes the agent after a restart (#37875) Co-authored-by: Julius Marminge --- .../Adapters/ClaudeAdapterV2.test.ts | 62 +++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 76 +++++++++++++++++-- docs/user/thread-sidebar.md | 4 +- docs/user/updating.md | 2 +- 4 files changed, 136 insertions(+), 8 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index faa96e3720645..f5bb3d4bd9c39 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -13856,6 +13856,57 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); + // A sleep is a timer the agent ends its turn on, so a restart must wake it. + const sleeps = [ + ["timer", "sleep 1740; date", true], + ["computed_timer", "sleep $((29 * 60)); date", true], + ["quoted_timer", 'sleep "60" && date', true], + ["single_quoted_timer", "sleep '60'; date", true], + ["quoted_computed_timer", 'sleep "$((29 * 60))"; date', true], + ["expanded_timer", 'sleep "${DELAY:-60}"; date', true], + ["unit_timer", 'sleep 5m && echo "Time to check the build"', true], + ["quoted_note_timer", 'sleep 60 && echo "Timer finished; check build"', true], + ["endless_sleep", "sleep infinity", false], + ["delayed_server", "sleep 5 && npm run dev", false], + ["substituted_server", 'sleep 60; echo "$(npm run dev)"', false], + ] as const; + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "assistant", + message: { + model: "claude-sonnet-4-6", + id: "msg_background_timer", + type: "message", + role: "assistant", + content: sleeps.map(([taskId, command]) => ({ + type: "tool_use", + id: `toolu_${taskId}`, + name: "Bash", + input: { command, run_in_background: true }, + })), + }, + parent_tool_use_id: null, + uuid: "background-timer-launch", + session_id: WAKE_NATIVE_SESSION, + }), + ); + for (const [index, [taskId]] of sleeps.entries()) { + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: taskId, + tool_use_id: `toolu_${taskId}`, + description: "Wait before the next check", + is_backgrounded: true, + task_type: "local_bash", + uuid: `00000000-0000-4000-8000-00000000021${index}`, + session_id: WAKE_NATIVE_SESSION, + }), + ); + } yield* Queue.offer(harness.sdkMessages, turnOneResult); yield* harness.awaitTerminal(1); @@ -13866,6 +13917,17 @@ describe("ClaudeAdapterV2 background wake turns", () => { const started = (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? [])[0]; assert.equal(started?.taskId, WAKE_TASK_ID); assert.equal(started?.nativeItemId, WAKE_TOOL_USE_ID); + assert.deepEqual( + (afterStart.at(-1)?.providerThread.pendingBackgroundTasks ?? []).map((task) => [ + task.taskId, + task.awaited === true, + ]), + [ + [WAKE_TASK_ID, false], + ["moved-build", false], + ...sleeps.map(([taskId, , awaited]) => [taskId, awaited]), + ], + ); const command = harness.events.find( (event) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index a4cb16c51d948..88a4d995b2b1b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2433,6 +2433,67 @@ function parseClaudeInteger(text: string): number { return Number.parseInt(value, 10); } +const CLAUDE_SLEEP_DURATION = String.raw`(?:\d[\w.]*|\$\(\([\d\s+*/%-]+\)\)|\$\{\w+(?::?[-=]\d[\w.]*)?\}|\$\w+)`; +const CLAUDE_SLEEP_TIMER_START = new RegExp( + String.raw`^[ \t\n]*sleep[ \t]+(?:${CLAUDE_SLEEP_DURATION}|"${CLAUDE_SLEEP_DURATION}"|'\d[\w.]*')[ \t]*(?:$|;|&&|\n)`, +); +// Bash separates words only with spaces and tabs, so `\s` would read `true\rnpm` as `true`. +const CLAUDE_SLEEP_TIMER_REPORT = /^[ \t]*(?:$|(?:date|echo|printf|true|:)(?:[ \t]|$))/; + +// A background command that only sleeps for a finite time, then at most prints the time or a +// note, is a timer the agent set to check back, which Claude wakes it for when it ends. Any other +// step (`sleep 5 && npm run dev`) may never end, so that command is not a timer. +function isClaudeSleepTimer(command: string | undefined): boolean { + const start = command === undefined ? null : CLAUDE_SLEEP_TIMER_START.exec(command); + if (command === undefined || start === null) return false; + const steps = splitClaudeSleepTimerSteps(command.slice(start[0].length)); + return steps !== undefined && steps.every((step) => CLAUDE_SLEEP_TIMER_REPORT.test(step)); +} + +// Splits at unquoted `;`, `&&` and newlines. Gives up on anything a report never needs that could +// run or hide another command: pipes, `||`, a lone `&`, subshells, heredocs, substitutions, `${…}`, +// `$'…'`, comments, and unbalanced quotes or escapes. +function splitClaudeSleepTimerSteps(tail: string): string[] | undefined { + const steps: string[] = []; + let step = ""; + let quote: string | undefined; + for (let index = 0; index < tail.length; index++) { + const char = tail[index] ?? ""; + const next = tail[index + 1] ?? ""; + if (quote === "'") { + if (char === "'") quote = undefined; + step += char; + continue; + } + if (char === "\\") { + if (next === "") return undefined; + step += char + next; + index++; + continue; + } + if (char === "`" || (char === "$" && "({'\"".includes(next) && next !== "")) return undefined; + if (quote === '"') { + if (char === '"') quote = undefined; + step += char; + continue; + } + if (char === "'" || char === '"') { + quote = char; + } else if (char === ";" || char === "\n" || (char === "&" && next === "&")) { + steps.push(step); + step = ""; + if (char === "&") index++; + continue; + } else if (char === "&" ? next !== ">" && tail[index - 1] !== ">" : "|()<#".includes(char)) { + return undefined; + } + step += char; + } + if (quote !== undefined) return undefined; + steps.push(step); + return steps; +} + // Claude Code defers MCP tools behind ToolSearch, so the agent only finds // t3_background_wait when the system prompt says when to reach for it. const CLAUDE_BACKGROUND_WAIT_INSTRUCTIONS = ` @@ -7205,17 +7266,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId: string, task: OrchestrationV2PendingBackgroundTask, ) { - const startedMonitor = yield* Ref.modify( + const startedWait = yield* Ref.modify( pendingBackgroundTasksByNativeThread, (current) => { const roster = new Map(rosterForNativeThread(current, nativeThreadId)); - const startedMonitor = - task.kind === "monitor" && roster.get(task.taskId)?.kind !== "monitor"; + const previous = roster.get(task.taskId); + const startedWait = + task.kind === "monitor" + ? previous?.kind !== "monitor" + : task.kind === "command" && + previous?.command === undefined && + isClaudeSleepTimer(task.command); roster.set(task.taskId, task); - return [startedMonitor, new Map(current).set(nativeThreadId, roster)] as const; + return [startedWait, new Map(current).set(nativeThreadId, roster)] as const; }, ); - if (startedMonitor) { + if (startedWait) { yield* addTaskIdsToNativeThreadSet( awaitedBackgroundTasksByNativeThread, nativeThreadId, diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index fdf30614421ec..61c2b8e21bce7 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -138,8 +138,8 @@ open. Threads that are working or waiting on work they will resume from move into a collapsed **Working** section below the active list. -That includes subagents, watched pull requests with checks still running, Claude monitors, -and background commands or other monitors the agent says it is waiting on. A dev server or other process an agent leaves running does not keep a thread +That includes subagents, watched pull requests with checks still running, Claude monitors and +`sleep` timers, and background commands or other monitors the agent says it is waiting on. A dev server or other process an agent leaves running does not keep a thread there. A thread returns to the top of the active list when it finishes, fails, or needs an approval or answer. The Working section lists the thread you last sent work to first. Pinned threads stay in the pinned section. diff --git a/docs/user/updating.md b/docs/user/updating.md index 388e9035ca770..cbb25110857b8 100644 --- a/docs/user/updating.md +++ b/docs/user/updating.md @@ -73,7 +73,7 @@ T3 Code must start again on that machine; the setting does not enable automatic startup. Terminal commands may still be interrupted, and threads without saved provider resume state need a new message. A thread that finished its turn to wait on a subagent, a background task, a Claude -monitor, or a command or other monitor the agent said it was waiting on is woken and told that this work +monitor or `sleep` timer, or a command or other monitor the agent said it was waiting on is woken and told that this work stopped. Other background shells and monitors, such as a dev server and its watchdog, do not wake it; the thread learns about them with your next message. A thread is not resumed while it waits for your approval, answer, or secret, or From 9d3195b49dfb0098e9fa592fe0ada5464206d1c2 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 02:41:04 -0600 Subject: [PATCH 06/65] fix(web): IME keys no longer cancel or send a diff comment (#42000) Co-authored-by: Julius Marminge --- .../DiffCommentAnnotation.browser.test.tsx | 58 +++++++++++++++++++ .../diffs/DiffCommentAnnotation.tsx | 5 ++ 2 files changed, 63 insertions(+) create mode 100644 apps/web/src/components/diffs/DiffCommentAnnotation.browser.test.tsx diff --git a/apps/web/src/components/diffs/DiffCommentAnnotation.browser.test.tsx b/apps/web/src/components/diffs/DiffCommentAnnotation.browser.test.tsx new file mode 100644 index 0000000000000..60c3759ae22e9 --- /dev/null +++ b/apps/web/src/components/diffs/DiffCommentAnnotation.browser.test.tsx @@ -0,0 +1,58 @@ +import { expect, it, vi } from "vite-plus/test"; +import { userEvent } from "vite-plus/test/browser"; + +import { registerCommands } from "~/shortcuts/dispatcher"; +import { act, render } from "../../../test/render"; +import { DiffCommentAnnotation } from "./DiffCommentAnnotation"; + +it("leaves IME keys in a diff comment to the composition", async () => { + const onCancel = vi.fn(); + const onComment = vi.fn(); + await using screen = await render( + , + ); + const heard: Array<{ key: string; consumed: boolean }> = []; + using _observer = { + [Symbol.dispose]: registerCommands( + {}, + { observe: (event, consumed) => heard.push({ key: event.key, consumed }) }, + ), + }; + const draft = screen.getByRole("textbox", { name: "Comment on lines 3" }); + await draft.fill("Draft"); + + for (const composing of [{ isComposing: true }, { keyCode: 229 }]) { + for (const keys of [ + { key: "Escape" }, + { key: "Enter", ctrlKey: true }, + { key: "Enter", metaKey: true }, + ]) { + const label = JSON.stringify({ ...keys, ...composing }); + const event = new KeyboardEvent("keydown", { + ...keys, + ...composing, + bubbles: true, + cancelable: true, + }); + await act(() => draft.element().dispatchEvent(event)); + expect(event.defaultPrevented, label).toBe(false); + // The right panel sheet and pull requests page close on an Escape that reaches them. + expect(heard, label).toEqual([]); + } + } + expect(onCancel).not.toHaveBeenCalled(); + expect(onComment).not.toHaveBeenCalled(); + + await userEvent.keyboard("{Escape}"); + expect(onCancel).toHaveBeenCalledOnce(); + expect(heard).toEqual([{ key: "Escape", consumed: true }]); + + await userEvent.keyboard("{Control>}{Enter}{/Control}"); + expect(onComment).toHaveBeenCalledExactlyOnceWith("Draft"); +}); diff --git a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx b/apps/web/src/components/diffs/DiffCommentAnnotation.tsx index a814af092c806..73a92e21d0c41 100644 --- a/apps/web/src/components/diffs/DiffCommentAnnotation.tsx +++ b/apps/web/src/components/diffs/DiffCommentAnnotation.tsx @@ -149,6 +149,11 @@ export function DiffCommentAnnotation({ event.currentTarget.setSelectionRange(end, end); }} onKeyDown={(event) => { + // Unclaimed, an IME Escape would close the right panel sheet or leave the pull requests page. + if (event.nativeEvent.isComposing || event.keyCode === 229) { + event.stopPropagation(); + return; + } if (event.key === "Escape") { event.preventDefault(); if (speech && speech.state.phase !== "idle") speech.cancel(); From 110ed776c96a17e36d207d95ff89d7fcf124e1ed Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 00:46:26 -0800 Subject: [PATCH 07/65] fix(server): a GitLab review posts no line comments once the head has moved (#42016) Co-authored-by: Claude Fable 5.2 --- .../mcp/toolkits/workflow/handlers.test.ts | 7 +++- docs/internals/04_environment-auth.md | 5 ++- .../src/server/GitLabPullRequestCli.test.ts | 39 +++++++++++++++++++ .../src/server/GitLabPullRequestCli.ts | 9 +++++ 4 files changed, 57 insertions(+), 3 deletions(-) diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts index cc7a7242ddfd6..ea758e6f62c53 100644 --- a/apps/server/src/mcp/toolkits/workflow/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/workflow/handlers.test.ts @@ -179,8 +179,9 @@ it.effect("hook paths go only to a caller at the broadest mode", () => it.effect("under an administrator's ceiling, a caller at the ceiling starts runs", () => Effect.gen(function* () { const start = { action: "start", workflow: "release", idempotencyKey: "trial" }; + const started: Array = []; const workflows = { - start: () => Effect.succeed({ runId: "run-1" }), + start: (name: string) => Effect.sync(() => (started.push(name), { runId: "run-1" })), get: () => Effect.succeed(emptyRun), }; const narrowedTo = (runtimeMode: "auto" | "approval-required") => ({ @@ -189,11 +190,13 @@ it.effect("under an administrator's ceiling, a caller at the ceiling starts runs }); expect( yield* call(start).pipe(Effect.provide(handlersWith(workflows, narrowedTo("auto")))), - ).not.toMatchObject({ code: "capability_denied" }); + ).toEqual({ steps: [], references: [] }); + expect(started).toEqual(["release"]); expect( yield* call(start).pipe( Effect.provide(handlersWith(workflows, narrowedTo("approval-required"))), ), ).toMatchObject({ code: "capability_denied" }); + expect(started).toEqual(["release"]); }), ); diff --git a/docs/internals/04_environment-auth.md b/docs/internals/04_environment-auth.md index cc67e5522de1a..a3496da612c63 100644 --- a/docs/internals/04_environment-auth.md +++ b/docs/internals/04_environment-auth.md @@ -55,7 +55,10 @@ model. `mcp-client` sessions (except the read-only thread relay and client-pairing routes restricted to [peer links](./05_remote.md#peer-links)). Every MCP tool must statically declare its access level in [`McpToolAccess.ts`](../../apps/server/src/mcp/McpToolAccess.ts), and thread-only tools must still - refuse outside callers in handlers—hiding from tool listings is only discovery. + refuse outside callers in handlers—hiding from tool listings is only discovery. A workflow run + picks its own modes, so only a caller at the broadest mode a thread may run in here (full access, + or an administrator's ceiling below it) can start or change runs, change what workflows store, or + read webhook paths. Narrower callers can still read runs. - **Peer-link client pairing.** Only a full-access peer link may mint a one-time client pairing on the linked environment (since full-access agents can already run `t3 auth pairing create`). The linked side enforces this itself, and the operation stays a human-triggered RPC/HTTP route rather diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts index 9bb56dd58f5e9..ad6d57ad1258b 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.test.ts @@ -1827,6 +1827,45 @@ layer("GitLabPullRequestCli.layer", (it) => { }), ); + it.effect("posts no line comment when the head is no longer the one the caller reviewed", () => + Effect.gen(function* () { + mockedExecute.mockReturnValueOnce( + Effect.succeed( + output( + JSON.stringify({ + iid: 7, + title: "t", + web_url: "https://gitlab.com/acme/web/-/merge_requests/7", + source_branch: "feat", + target_branch: "main", + created_at: "2026-07-01T00:00:00Z", + updated_at: "2026-07-01T00:00:00Z", + diff_refs: { base_sha: "base", head_sha: "newer-head", start_sha: "start" }, + }), + ), + ), + ); + mockedExecute.mockReturnValue(Effect.succeed(output("{}"))); + const cli = yield* GitLabPullRequestCli.GitLabPullRequestCli; + + const refused = yield* Effect.flip( + cli.submitReview({ + cwd: "/w", + repository: "acme/web", + number: 7, + verdict: "approve", + body: "Looks right.", + expectedHeadSha: "reviewed-head", + comments: [{ path: "src/b.ts", position: { kind: "added", newLine: 12 }, body: "nit" }], + }), + ); + + expect(refused.message).toContain("the head is now newer-head, not reviewed-head"); + expect(mockedExecute).toHaveBeenCalledTimes(1); + expect(argsOfCall(0)[1]).toContain("merge_requests/7"); + }), + ); + it.effect("requests changes as a reviewer and reports what GitLab refused", () => Effect.gen(function* () { mockedExecute diff --git a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts index c23f7ebdc9049..a2f4c4f38ddf9 100644 --- a/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabPullRequestCli.ts @@ -2980,6 +2980,15 @@ export const make = Effect.gen(function* () { } if (input.comments.length > 0) { const refs = yield* getDiffRefs(input); + // Line comments are placed on the head read here, so it must be the one reviewed. + if (input.expectedHeadSha !== undefined && refs.headSha !== input.expectedHeadSha) { + return yield* new GitLabMutationRefusedError({ + command: "glab", + cwd: input.cwd, + operation: "submitReview", + reasons: [`the head is now ${refs.headSha}, not ${input.expectedHeadSha}`], + }); + } const rangedFileHeaders = input.comments.flatMap((comment) => comment.startPosition !== undefined && (comment.startPosition.kind !== "context" || comment.position.kind !== "context") From 6f15610d5be1bb1e55842aab7a8b0fe1d180e2b9 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 03:24:08 -0600 Subject: [PATCH 08/65] fix(server): resolve a later local project favicon when an earlier icon link is not a local file (#42023) Co-authored-by: Julius Marminge --- .../project/ProjectFaviconResolver.test.ts | 24 ++++++++++++- .../src/project/ProjectFaviconResolver.ts | 35 ++++++++++++------- 2 files changed, 45 insertions(+), 14 deletions(-) diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index 7c0207eed557d..00ac4e5d17ef3 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -194,8 +194,20 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { Effect.gen(function* () { const resolver = yield* ProjectFaviconResolver.ProjectFaviconResolver; const cwd = yield* makeTempDir; - yield* writeTextFile(cwd, "index.html", ''); + yield* writeTextFile( + cwd, + "index.html", + ` + + + + + +`, + ); yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); + yield* writeTextFile(cwd, "public/brand/late.svg", "late"); + yield* writeTextFile(cwd, "public/cdn.example.com/icon.svg", "cdn"); yield* writeTextFile(cwd, "web/favicon.png", "flutter"); const resolved = yield* resolver.resolvePath(cwd); @@ -203,6 +215,15 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { expect(resolved).not.toBeNull(); expect(resolved).toBe((yield* Path.Path).join(cwd, "public", "brand", "logo.svg")); + // A cached icon whose `public` folder became a file falls back instead of failing. + yield* (yield* FileSystem.FileSystem).remove((yield* Path.Path).join(cwd, "public"), { + recursive: true, + }); + yield* writeTextFile(cwd, "public", "not a folder"); + expect(yield* resolver.resolvePath(cwd)).toBe( + (yield* Path.Path).join(cwd, "web", "favicon.png"), + ); + const flutterCwd = yield* makeTempDir; yield* writeTextFile(flutterCwd, "web/favicon.png", "flutter"); expect(yield* resolver.resolvePath(flutterCwd)).toBe( @@ -284,6 +305,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { head: () => ({ links: [ { rel: "stylesheet", href: "/app.css" }, + { rel: "icon", href: "https://cdn.example.com/icon.svg" }, { rel: "icon shortcut", href: "/brand/logo.svg" }, ], }), diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index 12c8e2fc63ea2..b2df7e0f53eb3 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -122,7 +122,7 @@ export class ProjectFaviconResolver extends Context.Service< } >()("t3/project/ProjectFaviconResolver") {} -function extractIconHref(source: string): string | null { +function* extractIconHrefs(source: string): Generator { for (const [tag] of source.matchAll(HTML_LINK_RE)) { const attributes = new Map(); for (const [, name, doubleQuoted, singleQuoted, unquoted] of tag @@ -145,14 +145,13 @@ function extractIconHref(source: string): string | null { // An unquoted `{...}` is a JSX expression, not a path. if (!href || (!href.quoted && href.value.startsWith("{"))) continue; const path = href.value.split("?")[0]; - if (path) return path; + if (path) yield path; } for (const run of source.split("}")) { if (!ICON_REL_RE.test(run)) continue; const hrefMatch = run.match(ICON_HREF_RE); - if (hrefMatch?.[1]) return hrefMatch[1]; + if (hrefMatch?.[1]) yield hrefMatch[1]; } - return null; } export const optionOnNotFound = ( @@ -166,6 +165,17 @@ export const optionOnNotFound = ( }), ); +// A path through a file (ENOTDIR) or a symlink loop names no file either. +const optionOnMissing = ( + effect: Effect.Effect, +): Effect.Effect, PlatformError.PlatformError, R> => + optionOnNotFound(effect).pipe( + Effect.catchIf( + (error) => error.reason._tag === "BadResource", + () => Effect.succeedNone, + ), + ); + export const make = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -173,6 +183,8 @@ export const make = Effect.gen(function* () { const projectFileLoader = yield* T3ProjectFileLoader.T3ProjectFileLoader; const resolveIconHref = (href: string): ReadonlyArray => { + // `data:`, `https:` and `//host` icons name no project file, and a long data URL fails `stat`. + if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(href.trim())) return []; // Browsers strip surrounding whitespace from URL attributes; file paths keep theirs. const clean = href.trim().replace(/^\//, ""); return [path.join("public", clean), clean]; @@ -203,7 +215,7 @@ export const make = Effect.gen(function* () { if (Option.isNone(candidate)) { continue; } - const stats = yield* optionOnNotFound(fileSystem.stat(candidate.value.absolutePath)).pipe( + const stats = yield* optionOnMissing(fileSystem.stat(candidate.value.absolutePath)).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ @@ -242,7 +254,7 @@ export const make = Effect.gen(function* () { }), ), ); - const stats = yield* optionOnNotFound(fileSystem.stat(sourcePath.absolutePath)).pipe( + const stats = yield* optionOnMissing(fileSystem.stat(sourcePath.absolutePath)).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ @@ -257,7 +269,7 @@ export const make = Effect.gen(function* () { if (Option.isNone(stats) || stats.value.type !== "File") { return null; } - const source = yield* optionOnNotFound( + const source = yield* optionOnMissing( fileSystem.open(sourcePath.absolutePath, { flag: "r" }).pipe( Effect.flatMap((file) => file.readAlloc(ICON_SOURCE_SCAN_BYTES)), Effect.scoped, @@ -277,11 +289,8 @@ export const make = Effect.gen(function* () { if (Option.isNone(source) || Option.isNone(source.value)) { return null; } - const href = extractIconHref(new TextDecoder().decode(source.value.value)); - if (!href) { - return null; - } - return yield* findExistingFile(projectCwd, resolveIconHref(href), "workspace"); + const hrefs = Array.from(extractIconHrefs(new TextDecoder().decode(source.value.value))); + return yield* findExistingFile(projectCwd, hrefs.flatMap(resolveIconHref), "workspace"); }); // Probe concurrently but join in list order so lower-ranked probes cannot delay a hit. @@ -377,7 +386,7 @@ export const make = Effect.gen(function* () { return null; } - const stats = yield* optionOnNotFound(fileSystem.stat(cached)).pipe( + const stats = yield* optionOnMissing(fileSystem.stat(cached)).pipe( Effect.mapError( (cause) => new ProjectFaviconResolutionError({ From 9010d7d5a1fb17b4cbaa4299596bcbaba0171cbf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 01:29:29 -0800 Subject: [PATCH 09/65] fix(server): session import no longer offers T3 sandbox chats behind a symlinked base or a Codex project (#42036) --- .../src/project/AgentSessionScanner.test.ts | 177 ++++++++++++++++++ .../server/src/project/AgentSessionScanner.ts | 52 +++-- 2 files changed, 212 insertions(+), 17 deletions(-) diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index 09a7a396a294f..0fcab0d7ad4c3 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1345,6 +1345,60 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect("excludes sandboxes recorded by their real path when the base dir is a symlink", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const realBaseDir = yield* fileSystem.realPath(yield* makeTempDir("t3code-scanner-base-")); + const linkParent = yield* makeTempDir("t3code-scanner-links-"); + const configBaseDir = path.join(linkParent, "t3-home"); + yield* fileSystem.symlink(realBaseDir, configBaseDir); + + const worktreeCwd = path.join(realBaseDir, "worktrees", "t3code", "wt-4"); + yield* fileSystem.makeDirectory(worktreeCwd, { recursive: true }); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"), + contents: claudeSessionLine(worktreeCwd), + mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }); + + expect(result.candidates).toEqual([]); + }), + ); + + it.effect("offers an outside project reached through a link inside a symlinked base dir", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const projectDir = yield* fileSystem.realPath( + yield* makeTempDir("t3code-scanner-project-"), + ); + const realBaseDir = yield* fileSystem.realPath(yield* makeTempDir("t3code-scanner-base-")); + const linkParent = yield* makeTempDir("t3code-scanner-links-"); + const configBaseDir = path.join(linkParent, "t3-home"); + yield* fileSystem.symlink(realBaseDir, configBaseDir); + const projectLink = path.join(realBaseDir, "project-link"); + yield* fileSystem.symlink(projectDir, projectLink); + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"), + contents: claudeSessionLine(projectLink), + mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"), + }); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }); + + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([ + { path: projectLink, threadCount: 1 }, + ]); + }), + ); + it.effect("finds the cwd on a later line when the first records carry none", () => Effect.gen(function* () { const path = yield* Path.Path; @@ -1937,6 +1991,129 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }), ); + it.effect.each([{ layout: "plain" }, { layout: "symlinked into Downloads" }] as const)( + "does not file T3 sandbox chats under the Codex project they were moved into ($layout base dir)", + ({ layout }) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const nowMs = Date.parse("2026-11-08T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-"); + const homeDir = yield* makeTempDir("t3code-home-"); + let configBaseDir = yield* makeTempDir("t3code-scanner-base-"); + let realBaseDir = configBaseDir; + if (layout === "symlinked into Downloads") { + // A Downloads folder is scratch, so only the base's real spelling tells the sandbox apart. + realBaseDir = path.join(homeDir, "Downloads", "t3-data"); + yield* fileSystem.makeDirectory(realBaseDir, { recursive: true }); + configBaseDir = path.join(homeDir, "t3-link"); + yield* fileSystem.symlink(realBaseDir, configBaseDir); + } + const projectDir = path.join(homeDir, "code", "my-project"); + const sandboxDir = path.join(realBaseDir, "worktrees", "my-project", "wt-1"); + yield* fileSystem.makeDirectory(projectDir, { recursive: true }); + yield* fileSystem.makeDirectory(sandboxDir, { recursive: true }); + + const projectId = "019a5f00-0000-7000-8000-000000000101"; + const chats = [ + { + id: "019a5f00-0000-7000-8000-00000000010a", + cwd: projectDir, + message: "Started in the project", + }, + { + id: "019a5f00-0000-7000-8000-00000000010b", + cwd: sandboxDir, + message: "Started in a T3 worktree", + }, + ]; + const rolloutPaths: Array = []; + for (const [index, chat] of chats.entries()) { + const filePath = path.join( + codexHomePath, + "sessions", + "2026", + "11", + "08", + `rollout-2026-11-08T08-0${index}-00-${chat.id}.jsonl`, + ); + rolloutPaths.push(filePath); + yield* writeTranscript({ + filePath, + contents: [ + encodeTranscriptRecord({ + type: "session_meta", + payload: { id: chat.id, cwd: chat.cwd }, + }), + encodeTranscriptRecord({ type: "turn_context", payload: { cwd: chat.cwd } }), + encodeTranscriptRecord({ + type: "event_msg", + payload: { type: "user_message", message: chat.message }, + }), + ].join("\n"), + mtimeMs: nowMs - 60_000 + index, + }); + } + yield* Effect.sync(() => { + const db = new NodeSqlite.DatabaseSync(path.join(codexHomePath, "state_5.sqlite")); + try { + db.exec(` + CREATE TABLE projects ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + metadata TEXT NOT NULL DEFAULT '{}', + position INTEGER NOT NULL, + created_at_ms INTEGER NOT NULL, + updated_at_ms INTEGER NOT NULL + ); + CREATE TABLE project_roots ( + project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + position INTEGER NOT NULL, + path TEXT NOT NULL, + PRIMARY KEY (project_id, position) + ); + CREATE TABLE threads ( + id TEXT PRIMARY KEY, + rollout_path TEXT NOT NULL, + cwd TEXT NOT NULL, + project_id TEXT REFERENCES projects(id) ON DELETE SET NULL + ); + `); + db.prepare("INSERT INTO projects VALUES (?, ?, '{}', 0, ?, ?)").run( + projectId, + "my-project", + nowMs, + nowMs, + ); + db.prepare("INSERT INTO project_roots VALUES (?, 0, ?)").run(projectId, projectDir); + const insertThread = db.prepare("INSERT INTO threads VALUES (?, ?, ?, ?)"); + for (const [index, chat] of chats.entries()) { + insertThread.run(chat.id, rolloutPaths[index]!, chat.cwd, projectId); + } + } finally { + db.close(); + } + }); + + const threads = yield* runRecentThreads({ + claudeHomePath, + codexHomePath, + configBaseDir, + workspaceRoot: projectDir, + }).pipe(Effect.provideService(HostProcess.HomeDirectory, homeDir)); + expect(threads.map((thread) => thread.title)).toEqual(["Started in the project"]); + + const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir }).pipe( + Effect.provideService(HostProcess.HomeDirectory, homeDir), + ); + expect(result.candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual( + [{ path: projectDir, threadCount: 1 }], + ); + }), + ); + it.effect("imports a rewound Codex thread with the history its new rollout inherits", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index b9029b8746b46..745d60e6f2c26 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -921,8 +921,17 @@ export const make = Effect.gen(function* () { const serverSettings = yield* ServerSettings.ServerSettingsService; const projectStore = yield* ProjectStore.ProjectStoreV2; const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; - const baseDir = path.resolve(serverConfig.baseDir); - const worktreesDir = path.resolve(serverConfig.worktreesDir); + const configuredT3Dirs = { + baseDir: path.resolve(serverConfig.baseDir), + worktreesDir: path.resolve(serverConfig.worktreesDir), + }; + // Resolved candidates are compared with T3's folders as resolved too, so a symlinked base still matches. + const realPathOf = (directory: string) => + fileSystem.realPath(directory).pipe(Effect.orElseSucceed(() => directory)); + const realT3Dirs = { + baseDir: yield* realPathOf(configuredT3Dirs.baseDir), + worktreesDir: yield* realPathOf(configuredT3Dirs.worktreesDir), + }; const platform = yield* HostProcess.Platform; const isWindows = platform === "win32"; const foldWorktreeCase = isWindows; @@ -939,17 +948,19 @@ export const make = Effect.gen(function* () { path.join(homeDir, "Documents", "Codex"), ]; - const isExcludedProjectPath = (candidatePath: string) => + const isScratchPath = (candidatePath: string) => excludedProjectRoots.has(normalizeProjectPathForComparison(candidatePath)) || excludedProjectAncestors.some((ancestor) => normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( normalizeForWorktreeMatch(ancestor, foldWorktreeCase), ), - ) || + ); + const isT3OwnedPath = (candidatePath: string, t3Dirs = configuredT3Dirs) => normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( - normalizeForWorktreeMatch(baseDir, foldWorktreeCase), - ) || - isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase); + normalizeForWorktreeMatch(t3Dirs.baseDir, foldWorktreeCase), + ) || isT3ManagedWorktree(candidatePath, t3Dirs.worktreesDir, foldWorktreeCase); + const isExcludedProjectPath = (candidatePath: string, t3Dirs = configuredT3Dirs) => + isScratchPath(candidatePath) || isT3OwnedPath(candidatePath, t3Dirs); const listDirectory = (directory: string) => fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); @@ -1010,7 +1021,7 @@ export const make = Effect.gen(function* () { .realPath(directory) .pipe(Effect.orElseSucceed(() => directory)); // Symlinks can disguise excluded worktree paths; re-check their targets. - return isExcludedProjectPath(realPath) ? Option.none() : stats; + return isExcludedProjectPath(realPath, realT3Dirs) ? Option.none() : stats; }); // Paths whose own read outlived the deadline, mapped to when they may be read @@ -1614,12 +1625,17 @@ export const make = Effect.gen(function* () { }).pipe(Effect.orElseSucceed((): ReadonlyMap> => new Map())); }); - // Only chats left in an excluded folder, such as Codex's scratch folder, take their project's root. - const projectCwd = (cwd: string, projectRoots: ReadonlyArray | undefined) => - projectRoots !== undefined && - isExcludedProjectPath(path.resolve(expandHomePath(cwd.trim(), homeDir))) - ? projectRoots[0]! - : cwd; + // Only chats left in a scratch folder, such as Codex's, take their project's root; T3's own stay excluded. + const projectCwd = Effect.fnUntraced(function* ( + cwd: string, + projectRoots: ReadonlyArray | undefined, + ) { + if (projectRoots === undefined) return cwd; + const resolved = path.resolve(expandHomePath(cwd.trim(), homeDir)); + if (!isScratchPath(resolved) || isT3OwnedPath(resolved)) return cwd; + const realCwd = yield* realPathOf(resolved); + return isT3OwnedPath(realCwd, realT3Dirs) ? cwd : projectRoots[0]!; + }); const discoverCodexTranscripts = Effect.fn("AgentSessionScanner.discoverCodexTranscripts")( function* (homePath: string, providerInstanceId: ProviderInstanceId, operationBudget: number) { @@ -1788,7 +1804,7 @@ export const make = Effect.gen(function* () { sameTranscriptIdentity(imported.source, transcript.identity), )?.cwd ?? (yield* readCwd(source, transcript, budget)); if (rolloutCwd === null || rolloutCwd === false) continue; - const cwd = projectCwd(rolloutCwd, transcript.projectRoots); + const cwd = yield* projectCwd(rolloutCwd, transcript.projectRoots); const key = `${transcript.providerInstanceId}\0${cwd}`; const existing = byOwnerAndCwd.get(key); if (existing) { @@ -2097,7 +2113,9 @@ export const make = Effect.gen(function* () { ) { const root = path.resolve(expandHomePath(workspaceRoot, homeDir)); const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root)); - if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot)) return Stream.empty; + if (isExcludedProjectPath(root) || isExcludedProjectPath(realRoot, realT3Dirs)) { + return Stream.empty; + } const rootIdentity = yield* directoryIdentity(root); const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS; @@ -2283,7 +2301,7 @@ export const make = Effect.gen(function* () { return Option.some({ _tag: "Skipped" }); } const expandedCwd = expandHomePath( - projectCwd(snapshot.cwd.value, transcript.projectRoots).trim(), + (yield* projectCwd(snapshot.cwd.value, transcript.projectRoots)).trim(), homeDir, ); if (!path.isAbsolute(expandedCwd) || !(yield* belongsToRoot(path.resolve(expandedCwd)))) { From 2ced06ef4acb3b013232faad5bcd0b66bcddecb2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 01:32:55 -0800 Subject: [PATCH 10/65] fix(web): model picker search finds a model by its ID (#42041) --- apps/web/src/components/chat/ModelPickerContent.tsx | 1 + packages/client-runtime/src/modelSearch.test.ts | 13 +++++++++++++ packages/client-runtime/src/modelSearch.ts | 2 ++ 3 files changed, 16 insertions(+) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index e536bbeea44c7..59b67580a4b16 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -707,6 +707,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { lockedProvider !== null ? result.filter((m) => matchesLockedProvider(m)) : result; return rankModelPickerSearch(candidates, searchQuery, (model) => ({ name: model.name, + slug: model.slug, ...(model.shortName ? { shortName: model.shortName } : {}), ...(model.subProvider ? { subProvider: model.subProvider } : {}), driverKind: model.driverKind, diff --git a/packages/client-runtime/src/modelSearch.test.ts b/packages/client-runtime/src/modelSearch.test.ts index 3e6be15d89cf4..57697d0cb15e7 100644 --- a/packages/client-runtime/src/modelSearch.test.ts +++ b/packages/client-runtime/src/modelSearch.test.ts @@ -57,6 +57,7 @@ type CatalogModel = { driverKind: string; providerDisplayName: string; name: string; + slug?: string; subProvider?: string; isFavorite?: boolean; }; @@ -127,6 +128,13 @@ const catalog: CatalogModel[] = [ name: "Kimi K2", subProvider: "Moonshot", }, + { + driverKind: "opencode", + providerDisplayName: "OpenCode", + name: "DeepSeek V4.1 Flash 1017", + slug: "opencode-go/deepseek-v4.1-flash", + subProvider: "OpenCode Go", + }, ]; function search(query: string, models: ReadonlyArray = catalog): string[] { @@ -155,6 +163,11 @@ describe("rankModelPickerSearch", () => { expect(search("moonshot")).toEqual(["Kimi K3", "Kimi K2.5", "Kimi K2"]); }); + it("finds a model by its full or bare ID when the name is written differently", () => { + expect(search("opencode-go/deepseek-v4.1-flash")).toEqual(["DeepSeek V4.1 Flash 1017"]); + expect(search("deepseek-v4.1-flash")).toEqual(["DeepSeek V4.1 Flash 1017"]); + }); + it("ranks a favorite above newer models in the same family", () => { const models = catalog.map((model) => model.name === "Claude Opus 4.5" ? { ...model, isFavorite: true } : model, diff --git a/packages/client-runtime/src/modelSearch.ts b/packages/client-runtime/src/modelSearch.ts index bf1a278c87ad8..832f26cde1398 100644 --- a/packages/client-runtime/src/modelSearch.ts +++ b/packages/client-runtime/src/modelSearch.ts @@ -4,6 +4,7 @@ export type ModelPickerSearchableModel = { driverKind: string; providerDisplayName: string; name: string; + slug?: string; shortName?: string; subProvider?: string; isFavorite?: boolean; @@ -20,6 +21,7 @@ function getModelPickerSearchFields(model: ModelPickerSearchableModel): string[] normalizeSearchQuery(model.driverKind), normalizeSearchQuery(model.providerDisplayName), buildModelPickerSearchText(model), + ...(model.slug ? [normalizeSearchQuery(model.slug)] : []), ]; } From f15d908759b7953c4471bf50ab00bc14382de7ee Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 03:34:34 -0600 Subject: [PATCH 11/65] fix(web): Esc in voice alias input cancels it without closing Settings (#42027) Co-authored-by: Julius Marminge --- .../VoiceSettingsPanel.browser.test.tsx | 38 +++++++++++++++++++ .../settings/VoiceSettingsPanel.tsx | 8 +++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx index 5c918f9430086..6ddfee2ace198 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.browser.test.tsx @@ -22,6 +22,7 @@ import { } from "../../speech/useEnvironmentSpeechInput"; import { chooseAudioDestination, chooseTranscriptCleanup } from "../../speech/voiceConsent"; import { useEnvironmentScope } from "../../state/session"; +import { AppRouteModal } from "../AppRouteModal"; import { toastManager } from "../ui/toast"; import { SettingsScopeProvider } from "./SettingsScopeContext"; import { SpeechLanguageSelect } from "./SpeechLanguageSelect"; @@ -700,6 +701,43 @@ it("keeps a dictionary term and alias draft on the Enter that confirms an IME ca await expect.element(alias).toHaveValue("にほん"); }); +it("cancels an alias draft on Esc without closing Settings", async () => { + const previous = getClientSettings(); + using cleanup = new DisposableStack(); + cleanup.defer(() => __setClientSettingsForTests(previous)); + __setClientSettingsForTests({ + ...previous, + speechCustomWords: [{ term: "Kubernetes", aliases: [] }], + }); + await using screen = await render( + + {}}> + + + , + { router: "/settings/voice" }, + ); + const settings = screen.getByRole("dialog", { name: "Settings" }); + const addAlias = screen.getByRole("button", { name: "Add an alias for Kubernetes" }); + await expect.element(addAlias).toBeVisible(); + (addAlias.element() as HTMLElement).focus(); + await userEvent.keyboard("{Enter}"); + const alias = screen.getByRole("textbox", { name: "Alias for Kubernetes" }); + await expect.element(alias).toHaveFocus(); + await userEvent.keyboard("cooper"); + + await userEvent.keyboard("{Escape}"); + + await expect.element(alias).not.toBeInTheDocument(); + await expect.element(settings).toHaveAttribute("data-open"); + await expect.element(settings).toHaveFocus(); + expect(getClientSettings().speechCustomWords).toEqual([{ term: "Kubernetes", aliases: [] }]); + + await userEvent.keyboard("{Escape}"); + + await expect.element(settings).not.toBeInTheDocument(); +}); + it("records from the first connected microphone in the saved order", async () => { const previous = getClientSettings(); using cleanup = new DisposableStack(); diff --git a/apps/web/src/components/settings/VoiceSettingsPanel.tsx b/apps/web/src/components/settings/VoiceSettingsPanel.tsx index 84a76f373c8be..e045d0e8d5282 100644 --- a/apps/web/src/components/settings/VoiceSettingsPanel.tsx +++ b/apps/web/src/components/settings/VoiceSettingsPanel.tsx @@ -479,7 +479,13 @@ function DictionaryEditor(props: { onBlur={() => setAliasDraft(null)} onKeyDown={(event) => { if (event.nativeEvent.isComposing || event.keyCode === 229) return; - if (event.key === "Escape") setAliasDraft(null); + if (event.key === "Escape") { + event.stopPropagation(); + // Unmounting the focused input lets the dialog move focus to a control whose + // tooltip would swallow the next Esc; the surface keeps Esc closing Settings. + event.currentTarget.closest("[data-app-modal]")?.focus(); + setAliasDraft(null); + } if (event.key !== "Enter") return; event.preventDefault(); addAlias(); From 548a61d711ca3b97e59d590f07f14847a8a0a3d9 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 01:43:19 -0800 Subject: [PATCH 12/65] fix(desktop): an update whose downloaded file was deleted downloads again before installing (#42035) --- .../src/updates/DesktopUpdates.test.ts | 33 +++++++++++++ apps/desktop/src/updates/DesktopUpdates.ts | 48 +++++++++++++++++-- apps/desktop/src/updates/updateMachine.ts | 16 +++++++ .../desktop/src/updates/updatesTestHarness.ts | 4 ++ 4 files changed, 96 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/updates/DesktopUpdates.test.ts b/apps/desktop/src/updates/DesktopUpdates.test.ts index 535e1123d2911..c1115f314e015 100644 --- a/apps/desktop/src/updates/DesktopUpdates.test.ts +++ b/apps/desktop/src/updates/DesktopUpdates.test.ts @@ -647,6 +647,39 @@ describe("DesktopUpdates", () => { ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); }); + it.effect("downloads again when the downloaded update file was deleted before install", () => { + const downloadedFile = "/cache/pending/T3-Code-1.2.4-arm64.zip"; + let installedFileExists: boolean | undefined; + const harness = makeHarness({ + checkForUpdates: Effect.sync(() => harness.emit("update-available", { version: "1.2.4" })), + downloadUpdate: Effect.sync(() => { + harness.deletedFiles.delete(downloadedFile); + harness.emit("update-downloaded", { version: "1.2.4", downloadedFile }); + }), + quitAndInstall: Effect.sync(() => { + installedFileExists = !harness.deletedFiles.has(downloadedFile); + }), + }); + + return Effect.scoped( + Effect.gen(function* () { + const updates = yield* DesktopUpdates.DesktopUpdates; + yield* updates.configure; + yield* updates.check("poll"); + yield* updates.download; + yield* flushCallbacks; + assert.equal(harness.downloadCount(), 1); + + harness.deletedFiles.add(downloadedFile); + const result = yield* updates.installPrepared("1.2.4"); + assert.isTrue(result.accepted); + assert.equal(harness.downloadCount(), 2); + assert.equal(harness.quitAndInstalls(), 1); + assert.isTrue(installedFileExists); + }), + ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer))); + }); + it.effect("restores download state and permits retry after interruption", () => Effect.gen(function* () { const actionStarted = yield* Deferred.make(); diff --git a/apps/desktop/src/updates/DesktopUpdates.ts b/apps/desktop/src/updates/DesktopUpdates.ts index 7976503d9e761..32e64502d9333 100644 --- a/apps/desktop/src/updates/DesktopUpdates.ts +++ b/apps/desktop/src/updates/DesktopUpdates.ts @@ -51,6 +51,7 @@ import { reduceDesktopUpdateStateOnCheckStart, reduceDesktopUpdateStateOnDownloadComplete, reduceDesktopUpdateStateOnDownloadFailure, + reduceDesktopUpdateStateOnDownloadLost, reduceDesktopUpdateStateOnDownloadProgress, reduceDesktopUpdateStateOnDownloadStart, reduceDesktopUpdateStateOnInstallFailure, @@ -80,6 +81,7 @@ const UpdateInfo = Schema.Struct({ releaseNotes: Schema.optional(Schema.Unknown), releaseName: Schema.optional(Schema.NullOr(Schema.String)), releaseDate: Schema.optional(Schema.String), + downloadedFile: Schema.optional(Schema.String), }); const DownloadProgressInfo = Schema.Struct({ @@ -403,6 +405,7 @@ export const make = Effect.gen(function* () { const updaterConfiguredRef = yield* Ref.make(false); const lastLoggedDownloadMilestoneRef = yield* Ref.make(-1); const notAppliedVersionRef = yield* Ref.make(Option.none()); + const downloadedFileRef = yield* Ref.make(Option.none()); // The release a track switch's database check cleared. A build crosses to another track only // through such a switch, and never below that release: version order alone cannot tell whether // a Stable knows a Nightly's migrations. @@ -995,6 +998,19 @@ export const make = Effect.gen(function* () { }), ).pipe(Effect.withSpan("desktop.updates.installDownloadedUpdate")); + const downloadedFileMissing = Ref.get(downloadedFileRef).pipe( + Effect.flatMap( + Option.match({ + onNone: () => Effect.succeed(false), + onSome: (path) => + fileSystem.exists(path).pipe( + Effect.map((exists) => !exists), + Effect.orElseSucceed(() => false), + ), + }), + ), + ); + const installWithExpectedVersion = Effect.fn("desktop.updates.install")(function* ( expectedVersion?: string, ) { @@ -1007,11 +1023,32 @@ export const make = Effect.gen(function* () { }; } let installVersion = expectedVersion; - // A download can be hours old: a release published since replaces it before restarting. const retained = yield* Ref.get(updateStateRef); - if ( - retained.downloadedVersion !== null && - (expectedVersion === undefined || retained.downloadedVersion === expectedVersion) && + const retainedVersion = retained.downloadedVersion; + const retainsExpectedDownload = + retainedVersion !== null && + (expectedVersion === undefined || retainedVersion === expectedVersion); + // A cache cleaner can delete the archive; Squirrel.Mac would then fail every install attempt. + if (retainsExpectedDownload && (yield* downloadedFileMissing)) { + yield* logUpdaterWarning("the downloaded update file is gone; downloading it again", { + version: retainedVersion, + }); + yield* updateState(reduceDesktopUpdateStateOnDownloadLost); + const download = yield* downloadAvailableUpdate(true); + if (!download.completed) { + return { + accepted: download.accepted, + completed: false, + failed: download.accepted, + state: yield* Ref.get(updateStateRef), + }; + } + if (expectedVersion !== undefined) { + installVersion = (yield* Ref.get(updateStateRef)).downloadedVersion ?? expectedVersion; + } + } else if ( + // A download can be hours old: a release published since replaces it before restarting. + retainsExpectedDownload && (yield* checkForUpdates( "install", "acquire", @@ -1023,7 +1060,7 @@ export const make = Effect.gen(function* () { // electron-updater compares a stale feed with the running build, not the retained download. if ( refreshed.availableVersion === null || - compareSemverVersions(refreshed.availableVersion, retained.downloadedVersion) <= 0 + compareSemverVersions(refreshed.availableVersion, retainedVersion) <= 0 ) { yield* setState(retained); } else { @@ -1244,6 +1281,7 @@ export const make = Effect.gen(function* () { } return; } + yield* Ref.set(downloadedFileRef, Option.fromNullishOr(info.downloadedFile)); yield* setState(reduceDesktopUpdateStateOnDownloadComplete(state, info.version)); yield* logUpdaterInfo("update downloaded", { version: info.version }); }), diff --git a/apps/desktop/src/updates/updateMachine.ts b/apps/desktop/src/updates/updateMachine.ts index 80751315657c0..53785a6a57a34 100644 --- a/apps/desktop/src/updates/updateMachine.ts +++ b/apps/desktop/src/updates/updateMachine.ts @@ -209,6 +209,22 @@ export function reduceDesktopUpdateStateOnDownloadComplete( }; } +export function reduceDesktopUpdateStateOnDownloadLost( + state: DesktopUpdateState, +): DesktopUpdateState { + if (state.downloadedVersion === null) return state; + return { + ...withoutTrackMismatch(state), + status: "available", + availableVersion: state.downloadedVersion, + downloadedVersion: null, + downloadPercent: null, + message: null, + errorContext: null, + canRetry: false, + }; +} + export function reduceDesktopUpdateStateOnInstallFailure( state: DesktopUpdateState, message: string, diff --git a/apps/desktop/src/updates/updatesTestHarness.ts b/apps/desktop/src/updates/updatesTestHarness.ts index b118d15ced674..9b8f78e19000c 100644 --- a/apps/desktop/src/updates/updatesTestHarness.ts +++ b/apps/desktop/src/updates/updatesTestHarness.ts @@ -246,6 +246,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { const updateRestartMarkers = new Set(); const updateMarkerContents = new Map(); const installRecords = new Map(); + const deletedFiles = new Set(); let previousInstallRecord = options.installRecord; const isInstallRecord = (path: string) => path.endsWith(DesktopUpdates.DESKTOP_UPDATE_INSTALL_RECORD_FILE); @@ -266,6 +267,7 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { }), ); }, + exists: (path) => Effect.succeed(!deletedFiles.has(path)), makeDirectory: () => Effect.void, writeFileString: (path, data) => Effect.sync(() => { @@ -320,6 +322,8 @@ export function makeHarness(options: UpdatesHarnessOptions = {}) { updateInProgressMarker: () => [...updateMarkerContents].find(([path]) => path.endsWith("/desktop-update-in-progress"))?.[1], installRecords, + /** Paths removed behind the app's back, as by a cache cleaner. */ + deletedFiles, previousInstallRecord: () => previousInstallRecord, downloadCount: () => downloadCount, feedUrls: (): ElectronUpdater.ElectronUpdaterFeedUrl[] => feedUrls, From 4cff209428f8451182c482b88d4aa1ee11503706 Mon Sep 17 00:00:00 2001 From: Solomon Botchway <62394255+snnbotchway@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:48:47 +0000 Subject: [PATCH 13/65] fix(server): preview browser downloads Chrome 158.0.8127.88 with its security fix (#42043) Co-authored-by: Julius Marminge --- apps/server/src/preview/PreviewBrowser.ts | 26 +++++++++++------------ 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/apps/server/src/preview/PreviewBrowser.ts b/apps/server/src/preview/PreviewBrowser.ts index 3f0de9b0af346..306a0bf1f1e8c 100644 --- a/apps/server/src/preview/PreviewBrowser.ts +++ b/apps/server/src/preview/PreviewBrowser.ts @@ -25,31 +25,31 @@ import { openZipArchive } from "../zipArchive.ts"; // https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json // Never pin below 156.0.8078.70: the shell has no CRLSet and older SPKI blocklists trust // compromised eMudhra intermediates (crrev.com/c/8627687). -export const VERSION = "158.0.8127.36"; +export const VERSION = "158.0.8127.88"; const ARCHIVES = { linux64: { - bytes: 132_087_165, - sha256: "2d3a23017323c54fd457a678e4351f895c4076d8050e39d5aa6247f93448b73a", + bytes: 132_091_593, + sha256: "63401333cc587645bfaeea7f0c90958b327d249251e23954a47f30112ca23d5b", }, "linux-arm64": { - bytes: 129_938_239, - sha256: "176ee5c55486c22de43128871189061365ea28e881fc96016fd18e7cb59437c8", + bytes: 129_942_265, + sha256: "9f89b7ef6574e4bbf6ddda9f17f1fab5626e93d6f7d852653232d0d3554df975", }, "mac-arm64": { - bytes: 105_057_133, - sha256: "c24d40a3786322ff3a5e3ac6eed162226cbaf07ebe468715407827226b0f8897", + bytes: 105_060_087, + sha256: "69320f6869c4defbbdac8b8fa83aef65dc63975e83bbd06899b75dbea5c464b3", }, "mac-x64": { - bytes: 112_306_247, - sha256: "e0c5d07d8f5bcc5bdd5ef370e7daf3770856b585fcc9eecf441c7e3bb2e3d1cf", + bytes: 112_314_759, + sha256: "dc1ac31965cb2ec7794aed8c66127aceea304ae15353cd56fc4b8bde44091548", }, win32: { - bytes: 122_509_290, - sha256: "c1fc009622363bccbc1e5f60be654b90fa7b70ad83e642875da1fcb147ae430d", + bytes: 122_509_314, + sha256: "936ad5e7f530bdd66b7261d0a2ceed76b057d429cf31b770a95fd903a7969856", }, win64: { - bytes: 127_876_264, - sha256: "9655950dfeddf565561cd64cfe8ee716ccd6482fa3798503b632219efc65a71e", + bytes: 127_879_225, + sha256: "e935ea2d4633495b5e9ab7bc66bcd982806329c0ee9ecbafc1ac9596a3b34cdb", }, } as const; From 147384f61aae7613ab084a20ac8f963b599bc155 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 01:50:17 -0800 Subject: [PATCH 14/65] fix(server): storage cleanup removes worktrees that take over 30 s to walk (#42034) --- apps/server/src/storageCleanup.test.ts | 32 ++++++++++++++++++++++++++ apps/server/src/storageCleanup.ts | 24 +++++++++++++------ 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index c62d74f186553..61565f3a5e0a1 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -3411,6 +3411,38 @@ describe("storage cleanup reports and local file policies", () => { }), ), ); + it.effect("removes an eligible worktree whose ignored files take over 30 seconds to walk", () => + runCleanupTest( + Effect.gen(function* () { + yield* TestClock.setTime(NOW_MS); + const fs = yield* FileSystem.FileSystem; + const walking = yield* Deferred.make(); + let slowPath: string | undefined; + // Stands in for a flat Bun or npm node_modules with hundreds of thousands of files. + const fixture = yield* cleanupFixture().pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + lstat: (target) => + Effect.gen(function* () { + if (target === slowPath) { + yield* Deferred.succeed(walking, undefined); + yield* Effect.sleep("31 seconds"); + } + return yield* fs.lstat(target); + }), + }), + ); + yield* fs.makeDirectory(`${fixture.worktree}/node_modules/pkg`, { recursive: true }); + yield* fs.writeFileString(`${fixture.worktree}/node_modules/pkg/index.js`, "export {};\n"); + slowPath = `${yield* fs.realPath(fixture.worktree)}/node_modules`; + const run = yield* fixture.service.runNow.pipe(Effect.forkChild); + yield* Deferred.await(walking); + yield* TestClock.adjust("31 seconds"); + expect((yield* Fiber.join(run)).entries[0]).toMatchObject({ outcome: "removed" }); + expect(yield* fs.exists(fixture.worktree)).toBe(false); + }), + ), + ); it.effect("removes a worktree owned by a repository other than the project root", () => runCleanupTest( Effect.gen(function* () { diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index 451df614f8184..d091c9d11228d 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -515,9 +515,19 @@ const make = Effect.gen(function* () { } return { bytes, reason: null }; }, - Effect.timeout("30 seconds"), + // No time limit: the entry cap bounds the walk, and a removal that timed out would + // repeat the whole walk on every sweep without ever deleting the worktree. Effect.orElseSucceed(() => ({ bytes: null, reason: "worktree could not be fully inspected" })), ); + // For walks under a workspace lease, which provider startup waits on, or repeated under one. + const measureWorktreeBounded = (...args: Parameters) => + measureWorktree(...args).pipe( + Effect.timeoutOrElse({ + duration: "30 seconds", + orElse: () => + Effect.succeed({ bytes: null, reason: "worktree could not be fully inspected" }), + }), + ); // Large snapshots take seconds; use the reader worker instead of blocking the event loop. const readThreads = Effect.fn("StorageCleanup.readThreads")(function* () { @@ -682,9 +692,9 @@ const make = Effect.gen(function* () { if (orphanSizes.has(key)) continue; const remaining = measurementDeadline - (yield* Clock.currentTimeMillis); if (!firstMeasurement && remaining <= 0) break; - const measured = yield* measureWorktree(path).pipe( - firstMeasurement ? Effect.asSome : Effect.timeoutOption(remaining), - ); + const measured = yield* firstMeasurement + ? measureWorktreeBounded(path).pipe(Effect.asSome) + : measureWorktree(path).pipe(Effect.timeoutOption(remaining)); firstMeasurement = false; if (Option.isSome(measured)) orphanSizes.set(key, measured.value.bytes); } @@ -1282,7 +1292,7 @@ const make = Effect.gen(function* () { ((yield* branchChanged(checkoutPath, branch)) ? "repository or branch changed" : null) ?? (yield* localChangesReason(checkoutPath, rules)); if (reason !== null) return { keep: reason, force: false, bytes: null }; - const { bytes, reason: measureReason } = yield* measureWorktree(checkoutPath, true); + const { bytes, reason: measureReason } = yield* measureWorktreeBounded(checkoutPath, true); if (measureReason !== null) return { keep: measureReason, force: false, bytes }; // Measuring takes time, and what follows deletes ignored files under these rules. if (yield* settingsChanged) @@ -1616,13 +1626,13 @@ const make = Effect.gen(function* () { (yield* scratchKeepReason(worktreePath, threadIds, settings)) ?? (yield* blockedSinceCheck()); if (blocked !== null) return keep(blocked); - const inspection = yield* measureWorktree(worktreePath, "plain-folder"); + const inspection = yield* measureWorktreeBounded(worktreePath, "plain-folder"); if (inspection.reason !== null) return keep(inspection.reason); return yield* withWorkspaceLease( worktreePath, Effect.gen(function* () { // Walked again under the lease: a repository deleted with the folder is gone for good. - const finalInspection = yield* measureWorktree(worktreePath, "plain-folder"); + const finalInspection = yield* measureWorktreeBounded(worktreePath, "plain-folder"); if (finalInspection.reason !== null) return keep(finalInspection.reason); // The walk takes time, so the cheap checks run last, right before removal. const blockedWhileMeasuring = From fc91bfdf6ce2010007843ecdcfa37ec93ffb6e31 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 03:54:09 -0600 Subject: [PATCH 15/65] fix(cli): keep the triage picker open after an invalid numbered choice (#42046) Co-authored-by: Julius Marminge --- apps/server/src/cli/triage.test.ts | 13 +++++++++++++ apps/server/src/cli/triage.ts | 23 +++++++++++++++-------- 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts index 41f4241fade68..a0bf8597431dc 100644 --- a/apps/server/src/cli/triage.test.ts +++ b/apps/server/src/cli/triage.test.ts @@ -21,6 +21,7 @@ import { expect, vi } from "vite-plus/test"; import { cli } from "../binCli.ts"; import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts"; +import { matchAgentAnswer } from "./triage.ts"; const cliPath = NodeURL.fileURLToPath(new URL("../bin.ts", import.meta.url)); @@ -108,6 +109,18 @@ it.live.each([ }), ); +it.each([ + { answer: "2", picked: "codex" }, + { answer: " 1 ", picked: "claude" }, + { answer: "CLAUDE", picked: "claude" }, + { answer: "1.5", picked: undefined }, + { answer: "1x", picked: undefined }, + { answer: "2codex", picked: undefined }, + { answer: "3", picked: undefined }, +])("the agent picker reads $answer as $picked", ({ answer, picked }) => { + expect(matchAgentAnswer([{ id: "claude" }, { id: "codex" }], answer)?.id).toBe(picked); +}); + it.live( "requires an explicit choice when Codex and Antigravity are installed without a terminal", () => diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index df73347cd9fe4..a4c7da2a91e49 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -86,6 +86,17 @@ export class TriageAgentSpawnError extends Schema.TaggedError( + agents: ReadonlyArray, + answer: string, +) => { + const trimmed = answer.trim(); + return ( + agents.find((_, index) => String(index + 1) === trimmed) ?? + agents.find((agent) => agent.id === trimmed.toLowerCase()) + ); +}; + const pickAgent = (agents: ReadonlyArray) => Effect.promise(async () => { const readline = NodeReadlinePromises.createInterface({ @@ -97,14 +108,10 @@ const pickAgent = (agents: ReadonlyArray) => .map((agent, index) => ` [${String(index + 1)}] ${agent.label}`) .join("\n"); for (;;) { - const answer = (await readline.question(`Run triage with:\n${menu}\n> `)).trim(); - const byNumber = agents[Number.parseInt(answer, 10) - 1]; - if (byNumber !== undefined) { - return byNumber; - } - const byId = agents.find((agent) => agent.id === answer.toLowerCase()); - if (byId !== undefined) { - return byId; + const answer = await readline.question(`Run triage with:\n${menu}\n> `); + const picked = matchAgentAnswer(agents, answer); + if (picked !== undefined) { + return picked; } } } finally { From 139af501b6781183b82341a8a76bee01e7109974 Mon Sep 17 00:00:00 2001 From: hanmin6 Date: Tue, 24 Nov 2026 17:56:01 +0800 Subject: [PATCH 16/65] fix(usage): skip elapsed resets in pooled refill summaries (#42037) Co-authored-by: hanmin6 <226948540+hanmin6@users.noreply.github.com> Co-authored-by: Julius Marminge --- .../src/features/usage/UsageLimitsPooled.tsx | 2 +- .../usage/UsageLimitsPooled.browser.test.tsx | 39 +++++++++++++++++++ .../components/usage/UsageLimitsPooled.tsx | 2 +- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx index 50a987787b4e4..9942754660b8e 100644 --- a/apps/mobile/src/features/usage/UsageLimitsPooled.tsx +++ b/apps/mobile/src/features/usage/UsageLimitsPooled.tsx @@ -195,7 +195,7 @@ function PoolWindowCard({ const inlineLabels = wide && segmentWidth >= 96; const inlineReset = wide && segmentWidth >= 150; const inlineName = wide && segmentWidth >= 220; - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0); const openAccount = (account: LimitAccount) => navigation.navigate("SettingsUsageAccount", { accountKey: account.key, diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index ab114fbbd6f21..b6fe3e50c9d37 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -7,6 +7,8 @@ import { import { CHATGPT_USAGE_URL } from "@t3tools/shared/usageLimits"; import { describe, expect, it } from "vite-plus/test"; +import "~/index.css"; + import { render } from "../../../test/render"; import { UsageLimitsPooled } from "./UsageLimitsPooled"; @@ -63,3 +65,40 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { .toBeVisible(); }); }); + +describe("UsageLimitsPooled next refill", () => { + it("skips elapsed resets while waiting for refreshed account data", async () => { + function account(instanceId: string, usedPercent: number, resetsAt: string): ServerProvider { + return { + ...managedChatGpt(instanceId, instanceId), + usageLimits: { + checkedAt, + windows: [{ id: "weekly", label: "Weekly", kind: "weekly", usedPercent, resetsAt }], + }, + }; + } + const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [ + account("Work", 20, "2026-10-25T17:00:00.000Z"), + account("Personal", 60, "2026-10-25T18:00:00.000Z"), + ], + }, + }, + ], + ]); + await using screen = await render( + , + ); + await expect.element(screen.getByText("↻ +30%", { exact: true })).toBeVisible(); + + await screen.rerender( + , + ); + await expect.element(screen.getByText(/^↻ \+\d+%$/)).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index c3932252691e5..d45ca4c0b6b15 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -604,7 +604,7 @@ function PoolWindowCard({ readonly label?: string | null | undefined; readonly description?: string | undefined; }) { - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const nextRefill = pool.resets.find((reset) => reset.at > now && reset.restoresPercent > 0); return (
From 28d8a63d7f8e5b1c0e70d479a315885a425fae32 Mon Sep 17 00:00:00 2001 From: pepsi <120768686+pepsile@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:56:14 +0800 Subject: [PATCH 17/65] fix(web): sidebar search times no longer wrap in translated languages (#42011) Co-authored-by: pepsi Co-authored-by: Julius Marminge --- apps/web/src/components/sidebar/SidebarThreadRow.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 2aa9be4c244a6..1811f17afac97 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -1932,7 +1932,7 @@ export const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props settled={props.isSettled} /> - + From a326dea2f9dd1ef80daf591c7ee90ccbde9ac094 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 02:02:20 -0800 Subject: [PATCH 18/65] fix(ci): a newer push to a PR is no longer cancelled by the older push's label job (#42061) --- .github/workflows/pr-size.yml | 10 +++++++--- .github/workflows/pr-vouch.yml | 14 +++++++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/.github/workflows/pr-size.yml b/.github/workflows/pr-size.yml index 45f5c9b9f7760..41e4ccecb024d 100644 --- a/.github/workflows/pr-size.yml +++ b/.github/workflows/pr-size.yml @@ -7,6 +7,13 @@ on: permissions: contents: read +# Run-level, not job-level: runs join the group when their event arrives, so a newer push +# always supersedes an older one. A job-level group is joined when the job starts, which +# let an older run's slower job cancel the newer head's job and label from a stale diff. +concurrency: + group: pr-size-${{ github.event.pull_request.number }} + cancel-in-progress: true + jobs: prepare-config: name: Prepare PR size config @@ -120,9 +127,6 @@ jobs: contents: read issues: read pull-requests: write - concurrency: - group: pr-size-${{ github.event.pull_request.number }} - cancel-in-progress: true steps: # This pull_request_target job may fetch untrusted PR commits only as passive # git data. Do not add dependency installs, build/test scripts, or cache diff --git a/.github/workflows/pr-vouch.yml b/.github/workflows/pr-vouch.yml index a81f877e69ddd..c8b067e7637dd 100644 --- a/.github/workflows/pr-vouch.yml +++ b/.github/workflows/pr-vouch.yml @@ -15,6 +15,17 @@ on: permissions: contents: read +# Per-PR events supersede each other at the run level, in arrival order (a job-level group +# is joined when the job starts, so an older run's slower job could cancel the newer one). +# Other comments and pushes get a unique group so they never cancel a PR's run. +concurrency: + group: >- + ${{ (github.event_name == 'pull_request_target' || + (github.event_name == 'issue_comment' && contains(github.event.comment.body, '/recheck-vouch'))) + && format('pr-vouch-run-{0}', github.event.pull_request.number || github.event.issue.number) + || format('pr-vouch-run-{0}', github.run_id) }} + cancel-in-progress: true + jobs: collect-targets: name: Collect PR targets @@ -74,9 +85,6 @@ jobs: permissions: contents: read pull-requests: write - concurrency: - group: pr-vouch-${{ matrix.target.number }} - cancel-in-progress: true strategy: fail-fast: false matrix: From 38634aa6a5414baa3a00df5554c8c8a42dacabb5 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 04:24:09 -0600 Subject: [PATCH 19/65] fix(cli): find the worktree's project when a Git hook sets GIT_DIR (#42063) Co-authored-by: Julius Marminge --- apps/server/src/cli/thread.test.ts | 5 +++++ apps/server/src/cli/thread.ts | 9 ++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index eafda7f3e9b69..41632c169d03f 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -767,5 +767,10 @@ it.live("resolves a path inside a git worktree of the project's repository to th assert.strictEqual(ambiguous._tag, "ThreadUsageError"); assert.include(ambiguous.message, "sample (project-sample)"); assert.include(ambiguous.message, "feature (project-feature)"); + + // An inherited relative GIT_DIR resolves against Git's cwd, where no repository is. + vi.stubEnv("GIT_DIR", ".git"); + yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs())); + assert.deepStrictEqual(yield* resolveFrom([sample], path.join(worktree, "pkg")), sample); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index fc3476739d1b0..ce74ce4eb2815 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -34,6 +34,7 @@ import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts import { expandHomePath } from "../os-jank.ts"; import * as ProcessRunner from "../processRunner.ts"; import { readLiveServerRuntimeState } from "../serverRuntimeState.ts"; +import { unsetInheritedRepositoryEnv } from "../vcs/VcsProcess.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -327,9 +328,15 @@ const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools /** The checkouts of the git repository at `directory`, or none outside a repository. */ const listGitCheckouts = Effect.fn("cli.thread.listGitCheckouts")(function* (directory: string) { const processRunner = yield* ProcessRunner.ProcessRunner; + const env = unsetInheritedRepositoryEnv(process.env, yield* HostProcess.Platform); const list = (args: ReadonlyArray) => processRunner - .run({ command: "git", args: ["worktree", "list", "--porcelain", ...args], cwd: directory }) + .run({ + command: "git", + args: ["worktree", "list", "--porcelain", ...args], + cwd: directory, + env, + }) .pipe( Effect.option, Effect.map((result) => From 42068f543e529006197275122f6d29d7fa4fdee4 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Tue, 24 Nov 2026 12:31:02 +0200 Subject: [PATCH 20/65] fix(shared): a Markdown piece held open for a wrapper is cut before it passes 128 KB (#42040) Co-authored-by: Julius Marminge --- packages/shared/src/markdownChunks.test.ts | 10 +++++++++- packages/shared/src/markdownChunks.ts | 16 +++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts index 8b4801ad7594f..d57885b73fbf8 100644 --- a/packages/shared/src/markdownChunks.test.ts +++ b/packages/shared/src/markdownChunks.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { splitMarkdown } from "./markdownChunks.ts"; +import { LARGE_MARKDOWN_CHUNK_MAX_CHARS, splitMarkdown } from "./markdownChunks.ts"; const splitLargeMarkdown = (text: string, targetChars?: number) => splitMarkdown(text, targetChars).chunks; @@ -119,6 +119,14 @@ describe("splitMarkdown", () => { expect(starts(multiline)).toEqual(["", "", "x".repeat(32 * 1024), "", "after"].join("\n"); expect(starts(unclosed)).toEqual(["
", "after"]); + const head = ["
", "", "a".repeat(8 * 1024), "", ""].join("\n"); + const longLine = "x".repeat(LARGE_MARKDOWN_CHUNK_MAX_CHARS - head.length); + expect(starts(head + longLine)).toEqual(["
"]); + expect(starts(`${head}${longLine}x`)).toEqual(["
", `${longLine}x`]); + expect(starts(`${head}\`\`\`json\n${longLine}\n\`\`\`\n\n
`)).toEqual([ + "
", + "```json", + ]); }); it("treats an autolink line as a paragraph, so a following fence still opens", () => { diff --git a/packages/shared/src/markdownChunks.ts b/packages/shared/src/markdownChunks.ts index e714e8ed5ed76..ee01ed535a94a 100644 --- a/packages/shared/src/markdownChunks.ts +++ b/packages/shared/src/markdownChunks.ts @@ -114,10 +114,12 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S let afterHeading = false; let definitionChars = 0; let openWrappers = 0; + let heldCut = 0; const flush = () => { chunks.push({ text: lines.join("\n"), lines: lines.length }); lines = []; chars = 0; + heldCut = 0; }; for (const line of text.split("\n")) { if (closes !== null) { @@ -127,12 +129,12 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES; } else { if (chars >= WRAPPED_MAX_CHARS) openWrappers = 0; - const cut = + const cutPoint = chars >= targetChars && - openWrappers === 0 && (ATX_HEADING.test(line) || (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line))); - if (cut) flush(); + if (cutPoint && openWrappers === 0) flush(); + else if (cutPoint) heldCut = lines.length; closes = blockCloser(line); // A definition cannot interrupt a paragraph, so it follows a blank line, a heading or // another definition. @@ -149,6 +151,14 @@ export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): S first = false; lines.push(line); chars += line.length + 1; + // A piece too large to render goes back to the last cut a wrapper held. + if (heldCut > 0 && chars - 1 > LARGE_MARKDOWN_CHUNK_MAX_CHARS) { + const rest = lines.splice(heldCut); + flush(); + lines = rest; + chars = rest.reduce((sum, kept) => sum + kept.length + 1, 0); + openWrappers = 0; + } afterBlankLine = line.trim() === ""; afterHeading = closes === null && (ATX_HEADING.test(line) || THEMATIC_BREAK.test(line)); } From dc326236ea21531d1bb931b7e0ba94fac5cfbd1d Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali Date: Tue, 24 Nov 2026 12:33:26 +0200 Subject: [PATCH 21/65] fix(web): raw HTML paragraphs and list items keep their lines when line breaks are on (#42055) Co-authored-by: Julius Marminge --- apps/web/src/markdown/wordsHast.test.ts | 5 +++++ apps/web/src/markdown/wordsHast.ts | 6 ++++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/apps/web/src/markdown/wordsHast.test.ts b/apps/web/src/markdown/wordsHast.test.ts index 78478c06cc195..516fa71bee722 100644 --- a/apps/web/src/markdown/wordsHast.test.ts +++ b/apps/web/src/markdown/wordsHast.test.ts @@ -168,6 +168,11 @@ describe("wordsHast", () => { expect(wordsHtml(markdown, { breaks: true })).toBe( '

one
\ntwo three
\nfour

\n
    \n
  • item
    \nnext\n
      \n
    • sub
    • \n
    \n
  • \n
\n
kept\nlines\n
', ); + const rawHtml = + '

\n \n

\n\n
    \n
  • \none\ntwo\n
  • \n
'; + expect(wordsHtml(rawHtml, { breaks: true })).toBe( + '

\n \n

\n
    \n
  • \none\ntwo\n
  • \n
', + ); }); it("keeps the composer's tildes and list numbers in user messages", () => { diff --git a/apps/web/src/markdown/wordsHast.ts b/apps/web/src/markdown/wordsHast.ts index 4a3397dd062b8..16de1be79fcc2 100644 --- a/apps/web/src/markdown/wordsHast.ts +++ b/apps/web/src/markdown/wordsHast.ts @@ -702,8 +702,10 @@ function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: bo checkbox.properties = { type: "checkbox", checked, disabled: true }; if (node.type === "element") node.properties.className = ["contains-task-list"]; } - breakLines(child, walk.options.breaks); - } else if (tagName === "p") { + if (child.position) breakLines(child, walk.options.breaks); + } else if (tagName === "p" && Object.keys(child.properties).length === 0) { + // Words writes a Markdown paragraph bare; one with attributes is raw HTML, which keeps its + // lines as written, as remark-breaks never touched raw HTML. breakLines(child, walk.options.breaks); } else if (tagName === "blockquote") { // remarkGithubAlerts From 47329274bc3d06f8ea1e7c40ae42696060c85a8e Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 04:33:44 -0600 Subject: [PATCH 22/65] fix(client-runtime): local repository clone folders keep # and ? in their name (#42062) Co-authored-by: Julius Marminge --- .../client-runtime/src/operations/projects.test.ts | 5 +++++ packages/client-runtime/src/operations/projects.ts | 13 +++++++++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/operations/projects.test.ts b/packages/client-runtime/src/operations/projects.test.ts index 5975f9c0dfdf9..fc55dccf4256a 100644 --- a/packages/client-runtime/src/operations/projects.test.ts +++ b/packages/client-runtime/src/operations/projects.test.ts @@ -143,6 +143,11 @@ describe("add project shared logic", () => { expect(getCloneDirectoryName("C:\\src\\repo.git")).toBe("repo"); expect(getCloneDirectoryName("git@github.com:repo.git")).toBe("repo"); expect(getCloneDirectoryName(" https://github.com/owner/repo.git ")).toBe("repo"); + expect(getCloneDirectoryName("/srv/git/firmware#2.git")).toBe("firmware#2"); + expect(getCloneDirectoryName("~/git/what?.git")).toBe("what?"); + expect(getCloneDirectoryName("../firmware#2.git")).toBe("firmware#2"); + expect(getCloneDirectoryName("C:\\src\\firmware#2.git")).toBe("firmware#2"); + expect(getCloneDirectoryName("github.com:owner/repo.git?ref=main")).toBe("repo"); }); it("lays clone folders out like ghq only when asked, and only when the URL is safe", () => { diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index 3808a3667286e..9f65f63e44a4a 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -12,7 +12,12 @@ import type { } from "@t3tools/contracts"; import { SourceControlProviderKind } from "@t3tools/contracts"; import { cloneUrlRepositoryPath } from "@t3tools/shared/cloneUrl"; -import { isAbsolutePath, isExplicitRelativePath, newProjectFolderName } from "@t3tools/shared/path"; +import { + isAbsolutePath, + isExplicitRelativePath, + isHostPath, + newProjectFolderName, +} from "@t3tools/shared/path"; import * as Arr from "effect/Array"; import * as Option from "effect/Option"; import * as Order from "effect/Order"; @@ -234,7 +239,11 @@ export function getAddProjectInitialQuery(baseDirectory: string | null | undefin } export function getCloneDirectoryName(repositoryOrRemoteUrl: string | null | undefined): string { - const withoutQuery = (repositoryOrRemoteUrl ?? "").split(/[?#]/)[0]?.trim() ?? ""; + const trimmed = (repositoryOrRemoteUrl ?? "").trim(); + // A local path keeps `#` and `?` in its name; in a URL they start a query or fragment. + const isLocalPath = + !trimmed.includes("://") && (isHostPath(trimmed) || isExplicitRelativePath(trimmed)); + const withoutQuery = isLocalPath ? trimmed : (trimmed.split(/[?#]/)[0] ?? ""); const schemeIndex = withoutQuery.indexOf("://"); const hasHost = schemeIndex >= 0 || /^[^/\\:]+@[^/\\:]+:/.test(withoutQuery); const pathPart = schemeIndex >= 0 ? withoutQuery.slice(schemeIndex + "://".length) : withoutQuery; From 60c9cb927e36df49dde83b4ebcb19d4a6fc6a7b0 Mon Sep 17 00:00:00 2001 From: Dang Date: Tue, 24 Nov 2026 18:40:54 +0800 Subject: [PATCH 23/65] fix(server): report CI passing during watch registration (#42049) Co-authored-by: Julius Marminge --- .../orchestration-v2/pullRequestWatch.test.ts | 36 +++++++++++++++++++ .../src/orchestration-v2/pullRequestWatch.ts | 4 ++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts index 7eb1868cbb1f5..506c3d203b453 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.test.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.test.ts @@ -170,6 +170,42 @@ describe("evaluatePullRequestWatch", () => { ); }); + it.each([false, true])( + "reports CI that passes during registration once (required: %s)", + (required) => { + const green = detail({ checks: [{ ...check("test", "success"), required }] }); + for (const awaitingBaseline of ["all", "checks"] as const) { + const first = evaluatePullRequestWatch( + watch({ awaitingBaseline, checksPending: true }), + green, + noRemarks, + ); + assert.deepEqual(first.changes, [{ kind: "checks-passed", count: 1, required }]); + assert.isFalse(first.next.checksPending); + assert.deepEqual(evaluatePullRequestWatch(first.next, green, noRemarks).changes, []); + } + }, + ); + + it("does not announce an unchanged required gate while optional CI still runs", () => { + const pending = detail({ + checks: [{ ...check("test", "success"), required: true }, check("advisory", "pending")], + }); + const first = evaluatePullRequestWatch( + watch({ awaitingBaseline: "all", checksPending: true }), + pending, + noRemarks, + ); + assert.deepEqual(first.changes, []); + const green = { + ...pending, + checks: pending.checks.map((check) => ({ ...check, status: "success" as const })), + }; + const finished = evaluatePullRequestWatch(first.next, green, noRemarks); + assert.deepEqual(finished.changes, [{ kind: "checks-passed", count: 2, required: false }]); + assert.deepEqual(evaluatePullRequestWatch(finished.next, green, noRemarks).changes, []); + }); + it("baselines existing failures and conflicts, then reports new ones", () => { const broken = detail({ checks: [check("lint", "failure"), check("test", "pending")], diff --git a/apps/server/src/orchestration-v2/pullRequestWatch.ts b/apps/server/src/orchestration-v2/pullRequestWatch.ts index e6e0be0f20310..284949f96c510 100644 --- a/apps/server/src/orchestration-v2/pullRequestWatch.ts +++ b/apps/server/src/orchestration-v2/pullRequestWatch.ts @@ -163,7 +163,9 @@ export function evaluatePullRequestWatch( checks.every((check) => check.status !== "pending"); owedChecks = owed; if (passedNow && (!passed || gateGrew)) { - if (!checksBaseline) { + // CI running at the start that has since settled green is news. The start rollup can be + // pending only on optional checks, so a passed gate alone is not. + if (!checksBaseline || (watch.checksPending === true && settled)) { changes.push({ kind: "checks-passed", count: gate.length, required: required.length > 0 }); } owedChecks = From 74d73ac23fc183ddd6bf65ede469e9b261891bf2 Mon Sep 17 00:00:00 2001 From: karstennilsen Date: Tue, 24 Nov 2026 11:47:53 +0100 Subject: [PATCH 24/65] fix(web): a thread link to an unconnected environment shows why instead of a blank pane (#42048) Co-authored-by: Karsten Nilsen <8917480+karstennilsen@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/web/src/components/ThreadRouteView.tsx | 32 ++++++++++++++++++++- apps/web/src/i18n/translations/de.json | 2 ++ apps/web/src/i18n/translations/en.json | 2 ++ apps/web/src/i18n/translations/es.json | 2 ++ apps/web/src/i18n/translations/fr.json | 2 ++ apps/web/src/i18n/translations/ja.json | 2 ++ apps/web/src/i18n/translations/ko.json | 2 ++ apps/web/src/i18n/translations/pt-BR.json | 2 ++ apps/web/src/i18n/translations/ru.json | 2 ++ apps/web/src/i18n/translations/sv.json | 2 ++ apps/web/src/i18n/translations/zh.json | 2 ++ apps/web/src/state/presentation.ts | 21 ++++++++++++++ apps/web/src/state/shell.test.ts | 23 +++++++++++++++ apps/web/src/threadRoutes.test.ts | 11 +++++++ apps/web/src/threadRoutes.ts | 7 ++++- 15 files changed, 112 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/ThreadRouteView.tsx b/apps/web/src/components/ThreadRouteView.tsx index 48b86b8ddfe56..f9a1aca77daa6 100644 --- a/apps/web/src/components/ThreadRouteView.tsx +++ b/apps/web/src/components/ThreadRouteView.tsx @@ -4,11 +4,14 @@ import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entitie import { visibilityParentKey } from "@t3tools/client-runtime/state/threads"; import type { ScopedThreadRef } from "@t3tools/contracts"; import * as Option from "effect/Option"; -import { Navigate, useNavigate } from "@tanstack/react-router"; +import { Link, Navigate, useNavigate } from "@tanstack/react-router"; +import { T } from "gt-react"; import { useEffect, useState } from "react"; import ChatView from "./ChatView"; import { BackgroundThreadContext, HiddenThreadContext } from "./chat/backgroundThread"; +import { Button } from "./ui/button"; +import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty"; import { SidebarInset } from "./ui/sidebar"; import { useComposerDraftStore } from "../composerDraftStore"; import { useSidebarPendingFileDropStore } from "../sidebarPendingFileDropStore"; @@ -17,6 +20,7 @@ import { useAnyEnvironmentHiding, useQuietThreadShell, } from "../state/entities"; +import { environmentUnreachableAtom } from "../state/presentation"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { useEnvironmentShellStatus } from "../state/shell"; import { environmentThreadShells, threadFamilies, useEnvironmentThread } from "../state/threads"; @@ -70,6 +74,9 @@ export function ThreadRouteView({ const serverThreadShell = useQuietThreadShell(serverThreadRef); const shellStatus = useEnvironmentShellStatus(serverThreadRef?.environmentId ?? null); const environmentThreadRefs = useEnvironmentThreadRefs(serverThreadRef?.environmentId ?? null); + const environmentUnreachable = useAtomValue( + environmentUnreachableAtom(serverThreadRef?.environmentId ?? null), + ); const bootstrapComplete = isThreadRouteSnapshotAuthoritative(shellStatus); const draftThread = useComposerDraftStore((store) => serverThreadRef ? store.getDraftThreadByRef(serverThreadRef) : null, @@ -137,6 +144,7 @@ export function ThreadRouteView({ serverThreadDeleted: serverThreadShell?.deletedAt != null, unlistedThreadDetail, draftThreadExists: draftThread !== null, + environmentUnreachable, }); const environmentHasAnyThreads = environmentThreadRefs.length > 0 || environmentHasDraftThreads; @@ -208,6 +216,8 @@ export function ThreadRouteView({ } else { redirect = ; } + } else if (renderState === "unreachable") { + view = ; } else if (hiddenByTagFilter) { redirect = ; } else if (offShellBlocked) { @@ -236,3 +246,23 @@ export function ThreadRouteView({ ); } + +function UnreachableEnvironmentState() { + return ( + + + + Thread unavailable + + + This thread is on an environment this app is not connected to. + + + + + + + ); +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 9bffdc0b7b720..967c314fd18fe 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -2630,6 +2630,8 @@ "89b5e8f3887812da": "Gastanfrage", "62e626804919b294": "Eingabe nötig", "c6196d99000642b4": "Thread öffnen", + "70bdebaa3d291d3b": "Thread nicht verfügbar", + "a351ebbdcf1a3f7a": "Dieser Thread liegt in einer Umgebung, mit der diese App nicht verbunden ist.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index d62730f5addeb..1b8e2d7620338 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Guest request", "62e626804919b294": "Input needed", "c6196d99000642b4": "Open thread", + "70bdebaa3d291d3b": "Thread unavailable", + "a351ebbdcf1a3f7a": "This thread is on an environment this app is not connected to.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "You:", "a1fbf2422c588292": "Agent:", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 4ded558e58454..65966981e964d 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Solicitud de invitado", "62e626804919b294": "Se necesita una respuesta", "c6196d99000642b4": "Abrir hilo", + "70bdebaa3d291d3b": "Hilo no disponible", + "a351ebbdcf1a3f7a": "Este hilo está en un entorno al que esta app no está conectada.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Tú:", "a1fbf2422c588292": "Agente:", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 60dae1d830451..24c38c1ece801 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Demande d’invité", "62e626804919b294": "Réponse requise", "c6196d99000642b4": "Ouvrir le fil", + "70bdebaa3d291d3b": "Fil indisponible", + "a351ebbdcf1a3f7a": "Ce fil se trouve dans un environnement auquel cette app n’est pas connectée.", "826cb862b4a11fb3": "{label} :", "3e597ec938e7551b": "Vous :", "a1fbf2422c588292": "Agent :", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 8f3380f194613..cb90e296f2ff6 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -2627,6 +2627,8 @@ "89b5e8f3887812da": "ゲストのリクエスト", "62e626804919b294": "入力が必要です", "c6196d99000642b4": "スレッドを開く", + "70bdebaa3d291d3b": "スレッドを利用できません", + "a351ebbdcf1a3f7a": "このスレッドは、このアプリが接続していない環境にあります。", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "あなた:", "a1fbf2422c588292": "エージェント:", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index f2f266662eb74..70a655f4c9e09 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -2628,6 +2628,8 @@ "89b5e8f3887812da": "게스트 요청", "62e626804919b294": "입력 필요", "c6196d99000642b4": "스레드 열기", + "70bdebaa3d291d3b": "스레드를 사용할 수 없음", + "a351ebbdcf1a3f7a": "이 스레드는 이 앱이 연결되어 있지 않은 환경에 있습니다.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "나:", "a1fbf2422c588292": "에이전트:", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 7348253aa8980..32bae390ab0cf 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Pedido de convidado", "62e626804919b294": "Resposta necessária", "c6196d99000642b4": "Abrir thread", + "70bdebaa3d291d3b": "Thread indisponível", + "a351ebbdcf1a3f7a": "Esta thread está em um ambiente ao qual este app não está conectado.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Você:", "a1fbf2422c588292": "Agente:", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 4b428ec6a1751..dc38cf4289dce 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Запрос гостя", "62e626804919b294": "Нужен ввод", "c6196d99000642b4": "Открыть тред", + "70bdebaa3d291d3b": "Тред недоступен", + "a351ebbdcf1a3f7a": "Этот тред находится в окружении, к которому это приложение не подключено.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Вы:", "a1fbf2422c588292": "Агент:", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 353f3554e31e9..7a1eb406e1a19 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -2629,6 +2629,8 @@ "89b5e8f3887812da": "Gästbegäran", "62e626804919b294": "Input behövs", "c6196d99000642b4": "Öppna tråd", + "70bdebaa3d291d3b": "Tråden är inte tillgänglig", + "a351ebbdcf1a3f7a": "Den här tråden finns i en miljö som den här appen inte är ansluten till.", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 1b72edb0ab4d4..4e904ee3add84 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -2633,6 +2633,8 @@ "89b5e8f3887812da": "访客请求", "62e626804919b294": "需要输入", "c6196d99000642b4": "打开会话", + "70bdebaa3d291d3b": "会话不可用", + "a351ebbdcf1a3f7a": "此会话位于本应用未连接的环境中。", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "你:", "a1fbf2422c588292": "智能体:", diff --git a/apps/web/src/state/presentation.ts b/apps/web/src/state/presentation.ts index e970c64f23c7e..36ba359fb8678 100644 --- a/apps/web/src/state/presentation.ts +++ b/apps/web/src/state/presentation.ts @@ -9,6 +9,7 @@ import { Atom } from "effect/reactivity"; import { environmentCatalog } from "../connection/catalog"; import { serverEnvironment } from "./server"; +import { expectsPrimaryEnvironment } from "./shell"; export const environmentPresentations = createEnvironmentPresentationAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, @@ -25,6 +26,26 @@ const EMPTY_ENVIRONMENT_PRESENTATION_ATOM = Atom.make + Atom.make((get) => { + if (environmentId === null) return false; + const catalog = get(environmentCatalog.catalogValueAtom); + if (!catalog.isReady) return false; + // The catalog is ready before primary discovery lands; until then it cannot prove absence. + if ( + expectsPrimaryEnvironment() && + !Array.from(catalog.entries.values()).some( + (entry) => entry.target._tag === "PrimaryConnectionTarget", + ) + ) { + return false; + } + const entry = catalog.entries.get(environmentId); + return !entry?.enabled || entry.unsupportedReason !== undefined; + }), +); + export function useEnvironmentPresentation(environmentId: EnvironmentId | null) { const catalog = useAtomValue(environmentCatalog.catalogValueAtom); const presentation = useAtomValue( diff --git a/apps/web/src/state/shell.test.ts b/apps/web/src/state/shell.test.ts index 530c96b9c8d29..6b6434e283590 100644 --- a/apps/web/src/state/shell.test.ts +++ b/apps/web/src/state/shell.test.ts @@ -16,6 +16,7 @@ import { environmentShell, } from "./shell"; import { environmentCatalog } from "../connection/catalog"; +import { environmentUnreachableAtom } from "./presentation"; import { defaultProjectFallbackReadyAtom } from "./projects"; const LOCAL = EnvironmentId.make("local"); @@ -143,6 +144,28 @@ describe("project snapshot readiness", () => { }); }); +it("calls an environment unreachable only once primary discovery can prove it absent", () => { + const UNKNOWN = EnvironmentId.make("unknown"); + const unreachable = (catalog: EnvironmentCatalogState, environmentId: EnvironmentId) => { + const registry = AtomRegistry.make({ + initialValues: [[environmentCatalog.catalogValueAtom, catalog]], + }); + try { + return registry.get(environmentUnreachableAtom(environmentId)); + } finally { + registry.dispose(); + } + }; + vi.stubGlobal("window", { desktopBridge: { getLocalEnvironmentEnabled: () => true } }); + try { + expect(unreachable(catalogState([REMOTE]), LOCAL)).toBe(false); + expect(unreachable(catalogState([LOCAL, REMOTE]), UNKNOWN)).toBe(true); + expect(unreachable(catalogState([LOCAL, REMOTE]), REMOTE)).toBe(false); + } finally { + vi.unstubAllGlobals(); + } +}); + it("expects a primary environment only on desktops with the local environment enabled", () => { const desktop = (enabled: boolean) => { vi.stubGlobal("window", { desktopBridge: { getLocalEnvironmentEnabled: () => enabled } }); diff --git a/apps/web/src/threadRoutes.test.ts b/apps/web/src/threadRoutes.test.ts index c4fef5897c5f4..fd8e7c1b157d6 100644 --- a/apps/web/src/threadRoutes.test.ts +++ b/apps/web/src/threadRoutes.test.ts @@ -153,6 +153,17 @@ describe("threadRoutes", () => { draftThreadExists: false, }), ).toBe("missing"); + // A link to an environment this app has no connection to never bootstraps. + expect( + resolveThreadRouteRenderState({ + bootstrapComplete: false, + serverThreadExists: false, + serverThreadDeleted: false, + unlistedThreadDetail: EMPTY_ENVIRONMENT_THREAD_STATE, + draftThreadExists: false, + environmentUnreachable: true, + }), + ).toBe("unreachable"); }); it("opens an unlisted server thread once its detail arrives, without waiting for the shell", () => { diff --git a/apps/web/src/threadRoutes.ts b/apps/web/src/threadRoutes.ts index a2047d4fe2e14..49192f75cf56d 100644 --- a/apps/web/src/threadRoutes.ts +++ b/apps/web/src/threadRoutes.ts @@ -21,7 +21,7 @@ type DraftThreadRouteState = { promotedTo?: ScopedThreadRef | null; }; -export type ThreadRouteRenderState = "loading" | "ready" | "missing"; +export type ThreadRouteRenderState = "loading" | "ready" | "missing" | "unreachable"; export function isThreadRouteSnapshotAuthoritative( status: EnvironmentShellStatus | null | undefined, @@ -35,10 +35,15 @@ export function resolveThreadRouteRenderState(input: { serverThreadDeleted: boolean; unlistedThreadDetail: EnvironmentThreadState; draftThreadExists: boolean; + /** The app has no enabled connection to the thread's environment, so its shell never goes live. */ + environmentUnreachable?: boolean; }): ThreadRouteRenderState { if (input.draftThreadExists || (input.serverThreadExists && !input.serverThreadDeleted)) { return "ready"; } + if (input.environmentUnreachable) { + return "unreachable"; + } if (!input.bootstrapComplete) { return "loading"; } From 8fcd0a8f76a911b175eadc82c94fdff7eaa26822 Mon Sep 17 00:00:00 2001 From: Gourango Sutradhar Date: Tue, 24 Nov 2026 16:56:14 +0600 Subject: [PATCH 25/65] fix(server): hide Android emulator consoles on Windows (#41971) Co-authored-by: Julius Marminge --- apps/server/src/device/LocalDeviceHost.ts | 3 +- .../src/device/deviceHubNodeArgs.test.ts | 59 +++++++++++++++++++ apps/server/src/device/deviceHubNodeArgs.ts | 25 ++++++++ 3 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 apps/server/src/device/deviceHubNodeArgs.test.ts create mode 100644 apps/server/src/device/deviceHubNodeArgs.ts diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index 7fd2816e3c17c..0c9912aadd034 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -40,6 +40,7 @@ import * as ProcessRunner from "../processRunner.ts"; import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts"; import * as DeviceHost from "./DeviceHost.ts"; import { makeDeviceHubOperations } from "./DeviceHubOperations.ts"; +import { deviceHubNodeArgs } from "./deviceHubNodeArgs.ts"; import { agentDeviceStateDir, type DeviceToolPaths, @@ -455,7 +456,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { ChildProcess.make( nodePath, [ - hubTool.entryPath, + ...deviceHubNodeArgs(hubTool.entryPath, hostPlatform), "--port", String(port), "--host", diff --git a/apps/server/src/device/deviceHubNodeArgs.test.ts b/apps/server/src/device/deviceHubNodeArgs.test.ts new file mode 100644 index 0000000000000..efe434862d46d --- /dev/null +++ b/apps/server/src/device/deviceHubNodeArgs.test.ts @@ -0,0 +1,59 @@ +// @effect-diagnostics nodeBuiltinImport:off - exercises the standalone Node preload in a subprocess. +import { describe, expect, it } from "@effect/vitest"; +import * as NodeChildProcess from "node:child_process"; +import * as NodeUtil from "node:util"; + +import { deviceHubNodeArgs } from "./deviceHubNodeArgs.ts"; + +const exec = NodeUtil.promisify(NodeChildProcess.execFile); + +describe("deviceHubNodeArgs", () => { + it("hides emulator consoles without changing other hub children or arguments", async () => { + const capture = ` +import childProcess from "node:child_process"; +import { syncBuiltinESMExports } from "node:module"; +childProcess.spawn = (...args) => console.log(JSON.stringify(args)); +syncBuiltinESMExports(); +`; + const fixture = ` +import { spawn } from "node:child_process"; +import { join } from "node:path"; +spawn(join("sdk with spaces", "emulator", "Emulator.exe"), ["-avd", "Pixel"], { + detached: true, stdio: "ignore", env: { TEST: "preserved" } +}); +spawn("ffmpeg", ["-encoders"], { detached: true, stdio: "pipe" }); +spawn("emulator.exe", { detached: true, cwd: "sdk" }); +console.log(JSON.stringify(process.argv.slice(1))); +`; + const args = deviceHubNodeArgs("unused-entry.mjs", "win32"); + const { stdout } = await exec( + process.execPath, + [ + "--import", + `data:text/javascript,${encodeURIComponent(capture)}`, + ...args.slice(0, -1), + "--input-type=module", + "-e", + fixture, + "--", + "--port", + "12345", + ], + { encoding: "utf8", windowsHide: true }, + ); + const [emulator, ffmpeg, withoutArgs, argv] = stdout + .trim() + .split(/\r?\n/) + .map((line) => JSON.parse(line)); + expect(emulator.slice(1)).toEqual([ + ["-avd", "Pixel"], + { detached: false, stdio: "ignore", env: { TEST: "preserved" }, windowsHide: true }, + ]); + expect(ffmpeg).toEqual(["ffmpeg", ["-encoders"], { detached: true, stdio: "pipe" }]); + expect(withoutArgs).toEqual([ + "emulator.exe", + { detached: false, cwd: "sdk", windowsHide: true }, + ]); + expect(argv).toEqual(["--port", "12345"]); + }); +}); diff --git a/apps/server/src/device/deviceHubNodeArgs.ts b/apps/server/src/device/deviceHubNodeArgs.ts new file mode 100644 index 0000000000000..5cd3c3629c63b --- /dev/null +++ b/apps/server/src/device/deviceHubNodeArgs.ts @@ -0,0 +1,25 @@ +// expo-device-hub detaches emulators without hiding their Windows console. Closing that +// console terminates the emulator; keep the workaround scoped to the hub process. +const WINDOWS_EMULATOR_PRELOAD = ` +import childProcess from "node:child_process"; +import { syncBuiltinESMExports } from "node:module"; +import { basename } from "node:path"; +const spawn = childProcess.spawn; +childProcess.spawn = function(command, ...args) { + if (typeof command === "string" && basename(command).toLowerCase() === "emulator.exe") { + const index = Array.isArray(args[0]) ? 1 : 0; + args[index] = { ...args[index], detached: false, windowsHide: true }; + } + return Reflect.apply(spawn, this, [command, ...args]); +}; +syncBuiltinESMExports(); +`; + +export const deviceHubNodeArgs = (entryPath: string, platform: NodeJS.Platform): string[] => + platform === "win32" + ? [ + "--import", + `data:text/javascript,${encodeURIComponent(WINDOWS_EMULATOR_PRELOAD)}`, + entryPath, + ] + : [entryPath]; From 26f4c7550e7ac954f63b9583a1905373aa07039c Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 04:57:43 -0600 Subject: [PATCH 26/65] fix(web): Esc in provider model filter clears it without closing Settings (#42076) Co-authored-by: Julius Marminge --- .../ProviderModelsSection.browser.test.tsx | 43 +++++++++++++++++++ .../settings/ProviderModelsSection.tsx | 7 +++ 2 files changed, 50 insertions(+) diff --git a/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx b/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx index 4c0f25762fef3..375026245065f 100644 --- a/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx +++ b/apps/web/src/components/settings/ProviderModelsSection.browser.test.tsx @@ -179,3 +179,46 @@ it("cancels adding or editing a custom model on Escape without closing Settings" await userEvent.keyboard("{Escape}"); await expect.element(settings).not.toBeInTheDocument(); }); + +it("clears the model filter on Escape without closing Settings", async () => { + const manyModels = Array.from({ length: 9 }, (_, index) => ({ + slug: `gpt-${index}`, + name: `GPT ${index}`, + isCustom: false, + capabilities: null, + })); + await using _screen = await render( + {section({ models: manyModels })}, + { router: "/settings/providers" }, + ); + const settings = page.getByRole("dialog", { name: "Settings" }); + const filter = page.getByRole("textbox", { name: "Filter models" }); + await userEvent.type(filter, "gpt 1"); + for (const composition of [ + { key: "Escape", isComposing: true, keyCode: 27 }, + { key: "Escape", isComposing: false, keyCode: 229 }, + ]) { + // Safari ends the composition just before the Escape keydown. + await act(() => { + filter.element().dispatchEvent(new CompositionEvent("compositionend", { bubbles: true })); + filter + .element() + .dispatchEvent(new KeyboardEvent("keydown", { ...composition, bubbles: true })); + }); + await expect.element(filter).toHaveValue("gpt 1"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(filter).toHaveValue(""); + await expect.element(filter).toHaveFocus(); + // Holding Escape repeats the keydown, which must not also close Settings. + await act(() => { + filter + .element() + .dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", repeat: true, bubbles: true })); + }); + await expect.element(settings).toHaveAttribute("data-open"); + + await userEvent.keyboard("{Escape}"); + await expect.element(settings).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/settings/ProviderModelsSection.tsx b/apps/web/src/components/settings/ProviderModelsSection.tsx index 921955c29dc9f..fb9bd2df702ea 100644 --- a/apps/web/src/components/settings/ProviderModelsSection.tsx +++ b/apps/web/src/components/settings/ProviderModelsSection.tsx @@ -355,6 +355,13 @@ export function ProviderModelsSection({ setFilter(event.target.value)} + onKeyDown={(event) => { + if (event.key !== "Escape" || event.nativeEvent.isComposing || event.keyCode === 229) + return; + if (!filter && !event.repeat) return; + event.stopPropagation(); + setFilter(""); + }} placeholder={gt("Filter models")} size="sm" className="w-56 max-w-full" From fa9f154e1b4e3b678e19a9d867b65dc4d0d6f0ef Mon Sep 17 00:00:00 2001 From: nikalezah <67012982+nikalezah@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:02:37 +0500 Subject: [PATCH 27/65] fix(web): the Cite button appears when a selection ends on a file chip's icon in Firefox (#41949) Co-authored-by: Julius Marminge --- apps/web/src/index.css | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4441b65f8143f..aac51580dd887 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -2084,6 +2084,17 @@ code { vertical-align: -0.125em; } +/* Firefox resolves a drag over the sprite icon's to the shared and collapses the + selection there, or snaps an unselectable icon's point into the text before it. Passing the + pointer to the chip lands the selection at its label. Chromium keeps triple-click line + selection only without user-select: none here. */ +@supports (-moz-appearance: none) { + .chat-markdown-file-link > svg { + pointer-events: none; + user-select: none; + } +} + .chat-markdown-file-link > [data-slot="context-chip-label"] { display: inline; } From f516cf9de87763d146b363ee752cc2cc69f6f08e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:07:53 -0800 Subject: [PATCH 28/65] fix(opencode): project skills show in the / menu from the first snapshot on OpenCode 2 (#42080) --- .../provider-opencode/src/server/driver.ts | 59 ++++++++++--------- .../src/server/status.test.ts | 30 +++------- .../provider-opencode/src/server/status.ts | 41 ++++++++++--- 3 files changed, 72 insertions(+), 58 deletions(-) diff --git a/packages/provider-opencode/src/server/driver.ts b/packages/provider-opencode/src/server/driver.ts index 10af4aeffa908..cc1977325c0ea 100644 --- a/packages/provider-opencode/src/server/driver.ts +++ b/packages/provider-opencode/src/server/driver.ts @@ -38,6 +38,7 @@ import { readOpenCodeGoUsageLimits } from "./usageLimits.ts"; import { loadOpenCode2Catalog, loadOpenCode2DirectoryCatalog } from "./openCode2Catalog.ts"; import { checkOpenCodeProviderStatus, + followOpenCode2Scans, loadOpenCode2Workspace, makeOpenCode2CatalogWatch, makeOpenCode2ModelLoader, @@ -411,10 +412,25 @@ export const OpenCodeDriver: ProviderDriver< connection.events, loadOpenCode2DirectoryCatalog(connection.client, machineDirectory(connection)), ); + // Locations whose scan T3 saw end on the current server; a scan is announced only once. + let scans = { url: "", scanned: new Set() }; + const followScans = (connection: OpenCode2Server.OpenCode2Connection) => + Effect.suspend(() => { + const scanned = new Set(); + scans = { url: connection.url, scanned }; + return connection.events.pipe( + Effect.flatMap((events) => + followOpenCode2Scans(events, (directory) => Effect.sync(() => scanned.add(directory))), + ), + Effect.scoped, + Effect.ignore, + Effect.forkScoped, + ); + }); // A session or text generation can start the server too, and reads no catalog when it does. - yield* Stream.runForEach(openCode2Server.connections, followMachineCatalog).pipe( - Effect.forkScoped, - ); + yield* Stream.runForEach(openCode2Server.connections, (connection) => + followScans(connection).pipe(Effect.andThen(followMachineCatalog(connection))), + ).pipe(Effect.forkScoped); const loadOpenCode2Models = yield* makeOpenCode2ModelLoader( openCode2Server.withConnection((connection) => followMachineCatalog(connection).pipe( @@ -424,29 +440,23 @@ export const OpenCodeDriver: ProviderDriver< processEnv, ); const listOpenCode2Workspace = (cwd: string) => - openCode2Server.withConnection(({ client, events }) => + openCode2Server.withConnection(({ client, events, url }) => Effect.gen(function* () { // OpenCode names a location by its resolved path (no trailing slash or `..`). const directory = pathService.resolve(cwd); const location = { directory }; + if (scans.url !== url) scans = { url, scanned: new Set() }; + const { scanned: seen } = scans; const scanned = yield* Deferred.make(); - const pending = new Set(["command.updated", "skill.updated"]); const stream = yield* events.pipe(Effect.option); if (stream._tag === "Some") { - yield* stream.value.pipe( - Stream.runForEach((event) => - "location" in event && - event.location?.directory === directory && - pending.delete(event.type) && - pending.size === 0 - ? Deferred.succeed(scanned, undefined) - : Effect.void, - ), - Effect.ignore, - Effect.forkScoped, - ); + yield* followOpenCode2Scans(stream.value, (scannedDirectory) => + scannedDirectory === directory + ? Deferred.succeed(scanned, undefined).pipe(Effect.asVoid) + : Effect.void, + ).pipe(Effect.forkScoped); } - return yield* loadOpenCode2Workspace( + const workspace = yield* loadOpenCode2Workspace( Effect.all( { skills: client.skill.list({ location }).pipe(Effect.map((list) => list.data)), @@ -456,17 +466,12 @@ export const OpenCodeDriver: ProviderDriver< ), Deferred.await(scanned), // Without events no scan can be awaited, so trust the first read as before. - stream._tag === "None" - ? Effect.succeed(true) - : client.debug.location.list().pipe( - Effect.map((loaded) => loaded.some((entry) => entry.directory === directory)), - Effect.timeout("2 seconds"), - Effect.orElseSucceed(() => true), - ), - // OpenCode answers provider.list for a location only once its skill scan has ended. - client.provider.list({ location }).pipe(Effect.timeout("10 seconds"), Effect.ignore), + stream._tag === "None" || seen.has(directory), processEnv, ); + // A location loaded before T3 watched never announces its scan; wait for it only once. + seen.add(directory); + return workspace; }).pipe(Effect.scoped), ); const serverOwner = yield* OpenCodeServerOwner.make({ diff --git a/packages/provider-opencode/src/server/status.test.ts b/packages/provider-opencode/src/server/status.test.ts index bac2b31047176..c378c9ec8b848 100644 --- a/packages/provider-opencode/src/server/status.test.ts +++ b/packages/provider-opencode/src/server/status.test.ts @@ -1254,15 +1254,18 @@ const scanned: OpenCode2Workspace = { }; it.effect( - "reads a loaded OpenCode 2 directory listing no commands again once its scan has ended", + "waits for the scan of an OpenCode 2 directory that lists built-ins before T3 saw its scan end", () => Effect.gen(function* () { - const reads: Array = [{ commands: [], skills: [] }, scanned]; + const reads: Array = [ + { commands: builtinCommands, skills: builtinSkills }, + scanned, + ]; const scanEnded = yield* Deferred.make(); const load = yield* loadOpenCode2Workspace( Effect.sync(() => reads.shift()!), Deferred.await(scanEnded), - Effect.succeed(true), + false, ).pipe(Effect.forkChild); yield* Effect.yieldNow; NodeAssert.equal(reads.length, 1); @@ -1271,30 +1274,13 @@ it.effect( }), ); -it.effect("waits for the scan of a cold OpenCode 2 directory that first lists only built-ins", () => - Effect.gen(function* () { - const calls: Array = []; - const reads: Array = [ - { commands: builtinCommands, skills: builtinSkills }, - scanned, - ]; - const workspace = yield* loadOpenCode2Workspace( - Effect.sync(() => (calls.push("read"), reads.shift()!)), - Effect.sync(() => void calls.push("scanned")), - Effect.sync(() => (calls.push("loaded"), false)), - ); - NodeAssert.deepEqual(workspace, scanned); - NodeAssert.deepEqual(calls, ["loaded", "read", "scanned", "read"]); - }), -); - -it.effect("reads an already loaded OpenCode 2 directory once without waiting for a scan", () => +it.effect("reads an OpenCode 2 directory whose scan T3 saw end once without waiting", () => Effect.gen(function* () { const calls: Array = []; const workspace = yield* loadOpenCode2Workspace( Effect.sync(() => (calls.push("read"), scanned)), Effect.sync(() => void calls.push("scanned")), - Effect.succeed(true), + true, ); NodeAssert.deepEqual(workspace, scanned); NodeAssert.deepEqual(calls, ["read"]); diff --git a/packages/provider-opencode/src/server/status.ts b/packages/provider-opencode/src/server/status.ts index a429ab63aec7e..c29926976ec4b 100644 --- a/packages/provider-opencode/src/server/status.ts +++ b/packages/provider-opencode/src/server/status.ts @@ -819,23 +819,46 @@ export interface OpenCode2Workspace { } /** - * Reading a location the server has not loaded boots its scan, and only reads after the scan's - * `command.updated` plus `skill.updated` are complete; `scanned` must listen before `read`. A - * loaded location listing no commands is still scanning. A location another caller booted - * moments earlier lists as loaded with only built-ins, so `settled` waits out its scan first. + * Runs `onScanned` for each location whose scan ends, which OpenCode announces once, after loading + * the location, as `command.updated` plus `skill.updated`. + */ +export const followOpenCode2Scans = ( + events: Stream.Stream< + { readonly type: string; readonly location?: { readonly directory?: string } | undefined }, + E + >, + onScanned: (directory: string) => Effect.Effect, +) => { + const pending = new Map>(); + return events.pipe( + Stream.runForEach((event) => { + const directory = event.location?.directory; + if (directory === undefined) return Effect.void; + if (event.type !== "command.updated" && event.type !== "skill.updated") return Effect.void; + const seen = pending.get(directory) ?? new Set(); + pending.set(directory, seen.add(event.type)); + if (seen.size < 2) return Effect.void; + pending.delete(directory); + return onScanned(directory); + }), + Effect.ignore, + ); +}; + +/** + * Until its scan ends a location lists only built-ins, even once the server lists it as loaded, + * and nothing but the scan's end tells the two apart. Unless the caller saw that scan end, read to + * boot the location, wait for its scan (`scanned` must listen before `read`), and read again. */ export const loadOpenCode2Workspace = Effect.fn("OpencodeProviderStatus.loadOpenCode2Workspace")( function* ( read: Effect.Effect, scanned: Effect.Effect, - loaded: Effect.Effect, - settled: Effect.Effect = Effect.void, + sawScan: boolean, environment?: NodeJS.ProcessEnv, ) { - const wasLoaded = yield* loaded; - yield* settled; const first = yield* read; - if (wasLoaded && first.commands.length > 0) return first; + if (sawScan) return first; yield* scanned.pipe( Effect.timeoutOption(resolveProviderProbeTimeoutMs("opencode", 10_000, environment)), ); From b28b13bd1f0e10cfb1864fa3d6c37c276dd0031a Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 05:13:23 -0600 Subject: [PATCH 29/65] fix(cli): keep --track folder labels valid when an emoji crosses the name limit (#42083) Co-authored-by: Julius Marminge --- apps/server/src/cli/project.test.ts | 15 +++++++++++++++ apps/server/src/cli/project.ts | 4 +++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 6dfd723e7084a..6c3469c1eb948 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -143,6 +143,12 @@ it.effect( const homeShared = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-home-")); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "api", ".git"), { recursive: true }); NodeFS.mkdirSync(NodePath.join(workspaceRoot, "notes")); + // Names are cut to 128 UTF-16 units, never between the halves of an emoji. + const named = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-names-")); + const straddling = NodePath.join(named, `${"a".repeat(127)}🚀`); + const fitting = NodePath.join(named, `${"b".repeat(126)}🚀`); + const padded = NodePath.join(named, `${" ".repeat(127)}🚀`); + for (const folder of [straddling, fitting, padded]) NodeFS.mkdirSync(folder); yield* runCli([ "project", "add", @@ -151,6 +157,12 @@ it.effect( `${shared}${NodePath.sep}`, "--track", `~/${NodePath.basename(homeShared)}`, + "--track", + straddling, + "--track", + fitting, + "--track", + padded, "--base-dir", baseDir, ]).pipe(Effect.provideService(HostProcess.HomeDirectory, NodeOS.tmpdir())); @@ -158,6 +170,9 @@ it.effect( { path: NodePath.join(workspaceRoot, "api"), name: "api", discovered: true }, { path: shared, name: NodePath.basename(shared) }, { path: homeShared, name: NodePath.basename(homeShared) }, + { path: straddling, name: "a".repeat(127) }, + { path: fitting, name: `${"b".repeat(126)}🚀` }, + { path: padded, name: "🚀" }, ]); }).pipe(Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index 1fa7cc0f3f264..fb11ade0c75dd 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -8,6 +8,7 @@ import { ProjectId, } from "@t3tools/contracts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; +import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -401,9 +402,10 @@ const projectAddCommand = Command.make("add", { const named = flags.track .map((folder) => { const resolved = path.resolve(expandHomePath(folder, home)); + const name = (path.basename(resolved) || resolved).trimStart(); return { path: resolved, - name: (path.basename(resolved) || resolved).slice(0, 128).trim(), + name: name.slice(0, splitsSurrogatePair(name, 128) ? 127 : 128).trim(), }; }) .filter( From 30bda7ede9d2bd02c6ff6a0aa04fff7945ded813 Mon Sep 17 00:00:00 2001 From: TheGuyWithHAT Date: Tue, 24 Nov 2026 12:13:44 +0100 Subject: [PATCH 30/65] fix(server): resolve project favicon links with URL fragments (#42082) Co-authored-by: geezoria <25051260+geezoria@users.noreply.github.com> Co-authored-by: Julius Marminge --- apps/server/src/project/ProjectFaviconResolver.test.ts | 4 ++-- apps/server/src/project/ProjectFaviconResolver.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/apps/server/src/project/ProjectFaviconResolver.test.ts b/apps/server/src/project/ProjectFaviconResolver.test.ts index 00ac4e5d17ef3..5de818cbeea9d 100644 --- a/apps/server/src/project/ProjectFaviconResolver.test.ts +++ b/apps/server/src/project/ProjectFaviconResolver.test.ts @@ -202,7 +202,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { - + `, ); yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); @@ -306,7 +306,7 @@ it.layer(layerTest)("ProjectFaviconResolverLive", (it) => { links: [ { rel: "stylesheet", href: "/app.css" }, { rel: "icon", href: "https://cdn.example.com/icon.svg" }, - { rel: "icon shortcut", href: "/brand/logo.svg" }, + { rel: "icon shortcut", href: "/brand/logo.svg#mark" }, ], }), });`, diff --git a/apps/server/src/project/ProjectFaviconResolver.ts b/apps/server/src/project/ProjectFaviconResolver.ts index b2df7e0f53eb3..85930064d033d 100644 --- a/apps/server/src/project/ProjectFaviconResolver.ts +++ b/apps/server/src/project/ProjectFaviconResolver.ts @@ -83,7 +83,7 @@ const ICON_REL_VALUE = String.raw`(?:"(?:[^"]*[\t\n\f\r ])?icon(?=[\t\n\f\r "])| const HTML_ATTRIBUTE_RE = /([^\t\n\f\r "'<>/=]+)(?:[\t\n\f\r ]*=[\t\n\f\r ]*(?:"([^"]*)"|'([^']*)'|([^\t\n\f\r >]+)))?/g; const ICON_REL_RE = new RegExp(String.raw`\brel\s*:\s*${ICON_REL_VALUE}`, "i"); -const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?]+)/i; +const ICON_HREF_RE = /\bhref\s*:\s*["']([^"'?#]+)/i; export class ProjectFaviconResolutionError extends Schema.TaggedError()( "ProjectFaviconResolutionError", @@ -144,7 +144,7 @@ function* extractIconHrefs(source: string): Generator { const href = attributes.get("href"); // An unquoted `{...}` is a JSX expression, not a path. if (!href || (!href.quoted && href.value.startsWith("{"))) continue; - const path = href.value.split("?")[0]; + const path = href.value.split(/[?#]/, 1)[0]; if (path) yield path; } for (const run of source.split("}")) { From 0a7864c887821d109b9b2da4257a2f5efaefd51e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:15:45 -0800 Subject: [PATCH 31/65] fix(web): a run finishing in a background window stays unread (#42084) --- .../ThreadVisitWatermark.browser.test.tsx | 48 +++++++++++++++++++ .../components/chat/ThreadVisitWatermark.tsx | 13 +++++ .../client-runtime/src/state/threadVisits.ts | 12 ++++- 3 files changed, 72 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx b/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx index 3e35d2fcc0cb9..5283fb8feb3d4 100644 --- a/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadVisitWatermark.browser.test.tsx @@ -59,6 +59,7 @@ it("records the visit of the next thread at once after switching threads", async mocks.visitRun.mockReturnValue(Effect.void); setShell(threadA, "2026-01-02T00:00:00.000Z"); setShell(threadB, "2026-01-03T00:00:00.000Z"); + using _focus = vi.spyOn(document, "hasFocus").mockReturnValue(true); using _timers = fakeTimers(); vi.setSystemTime(NOW); // A palette pick already sent B's open with its query, so B's visit is a plain watermark advance. @@ -81,3 +82,50 @@ it("records the visit of the next thread at once after switching threads", async // within the throttle window would otherwise keep it unread. expect(visitedThreadIds()).toEqual(["a", "b"]); }); + +it("does not mark a run that finishes in a background window as seen", async () => { + mocks.visitRun.mockReset(); + mocks.visitRun.mockReturnValue(Effect.void); + const threadC: ScopedThreadRef = { environmentId: ENVIRONMENT, threadId: ThreadId.make("c") }; + setShell(threadC, "2026-01-02T00:00:00.000Z"); + let focused = true; + let visibility: DocumentVisibilityState = "visible"; + using _focus = vi.spyOn(document, "hasFocus").mockImplementation(() => focused); + using _visibility = vi + .spyOn(document, "visibilityState", "get") + .mockImplementation(() => visibility); + using _timers = fakeTimers(); + vi.setSystemTime(NOW); + + await using _screen = await render( + + + , + ); + expect(visitedThreadIds()).toEqual(["c"]); + + // The user switches to another app while the run is still working. + focused = false; + visibility = "hidden"; + window.dispatchEvent(new Event("blur")); + document.dispatchEvent(new Event("visibilitychange")); + + const completedAt = "2026-01-03T00:00:00.000Z"; + appAtomRegistry.set(shellAtom(shellKey(threadC)), { + environmentId: threadC.environmentId, + id: threadC.threadId, + updatedAt: completedAt, + lastVisitedAt: "2026-01-02T00:00:00.000Z", + latestRun: { completedAt }, + }); + vi.advanceTimersByTime(60_000); + + expect(visitedThreadIds()).toEqual(["c"]); + + focused = true; + visibility = "visible"; + document.dispatchEvent(new Event("visibilitychange")); + window.dispatchEvent(new Event("focus")); + + expect(visitedThreadIds()).toEqual(["c", "c"]); +}); diff --git a/apps/web/src/components/chat/ThreadVisitWatermark.tsx b/apps/web/src/components/chat/ThreadVisitWatermark.tsx index a60147aed86af..387c78b16e0a0 100644 --- a/apps/web/src/components/chat/ThreadVisitWatermark.tsx +++ b/apps/web/src/components/chat/ThreadVisitWatermark.tsx @@ -2,17 +2,30 @@ import { useAtomMount } from "@effect/atom-react"; import { scopedThreadKey } from "@t3tools/client-runtime/environment"; import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits"; import { type ScopedThreadRef } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; import { environmentCatalog } from "../../connection/catalog"; +import { getDocumentActivity, subscribeDocumentActivity } from "../../lib/documentActivity"; import { useUiStateStore } from "../../uiStateStore"; import { environmentThreadShells, threadEnvironment } from "../../state/threads"; +const isDocumentViewed = () => { + const activity = getDocumentActivity(); + return activity.visible && activity.focused; +}; + +const documentViewedAtom = Atom.make((get) => { + get.addFinalizer(subscribeDocumentActivity(() => get.setSelf(isDocumentViewed()))); + return isDocumentViewed(); +}).pipe(Atom.withLabel("document-viewed")); + const threadVisitTracker = createThreadVisitTracker({ threadShellAtom: environmentThreadShells.threadShellAtom, sessionGenerationAtom: environmentCatalog.sessionGenerationAtom, visit: threadEnvironment.visit, markLocalVisit: (ref, visitedAt) => useUiStateStore.getState().markThreadVisited(scopedThreadKey(ref), visitedAt), + viewingAtom: documentViewedAtom, }); // The visit watermark is the one part of the chat view that follows the diff --git a/packages/client-runtime/src/state/threadVisits.ts b/packages/client-runtime/src/state/threadVisits.ts index 4d71a1960fd67..04bb8322dffe8 100644 --- a/packages/client-runtime/src/state/threadVisits.ts +++ b/packages/client-runtime/src/state/threadVisits.ts @@ -44,10 +44,15 @@ export interface ThreadVisitTrackerOptions { * that keeps its own watermark for them records the visit here instead. */ readonly markLocalVisit?: (ref: ScopedThreadRef, visitedAt: string) => void; + /** + * Whether the user can see the thread right now. While false, nothing is + * recorded; the open and the watermark catch up when it turns true. + */ + readonly viewingAtom?: Atom.Atom; } /** - * While mounted, a tracker counts as the user viewing the thread: mounting it + * While mounted and `viewingAtom` holds, a tracker counts as the user viewing the thread: mounting it * records one open (which also feeds search ranking), and every shell update * after that advances the visit watermark, throttled while a run streams. */ @@ -129,6 +134,7 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) { const onShell = (shell: VisitedShell | null) => { clearTimer(); if (shell === null) return; + if (options.viewingAtom && !registry.get(options.viewingAtom)) return; const shellUpdatedAtMs = Date.parse(shell.updatedAt); if (Number.isNaN(shellUpdatedAtMs)) return; @@ -203,6 +209,10 @@ export function createThreadVisitTracker(options: ThreadVisitTrackerOptions) { get.subscribe(sessionGenerationAtom, () => onShell(registry.get(options.threadShellAtom(ref))), ); + if (options.viewingAtom) + get.subscribe(options.viewingAtom, () => + onShell(registry.get(options.threadShellAtom(ref))), + ); }).pipe(Atom.withLabel(`thread-visit-tracker:${key}`)); }); return (ref: ScopedThreadRef | null) => (ref === null ? IDLE_TRACKER : family(threadKey(ref))); From 15afd7f9c85946e4ac918949984b8a54f85e59cf Mon Sep 17 00:00:00 2001 From: lryoooow <153452545+lryoooow@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:15:58 +0800 Subject: [PATCH 32/65] fix(server): treat remote delegated tasks as app-owned on stop and restart (#42069) Co-authored-by: Julius Marminge --- .../src/orchestration-v2/Orchestrator.ts | 4 ++- .../RestartContinuation.test.ts | 36 +++++++++++++++++++ .../orchestration-v2/RestartContinuation.ts | 6 +++- apps/server/src/peer/RemoteDelegation.test.ts | 33 ++++++++++++++++- 4 files changed, 76 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ac80a4d957aed..5cd22bc42c1ce 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -14654,7 +14654,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const stopDelegatedTasks = command.stopDelegatedTasks === false || !projection.subagents.some( - (task) => task.origin === "app_owned" && task.childThreadId !== null, + (task) => + task.origin === "app_owned" && + (task.childThreadId !== null || task.remoteChild !== undefined), ) ? Effect.void : Ref.update(effects, (existing) => [...existing, delegatedTasksStopEffect(command)]); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.test.ts b/apps/server/src/orchestration-v2/RestartContinuation.test.ts index 77af7d2680e05..e86cc9dfd4982 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.test.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.test.ts @@ -1479,3 +1479,39 @@ it.effect("skips restart discovery when no project enables continuation", () => yield* recovery.prepareForShutdown; }), ); + +it("does not continue a settled run whose only open subagent is a remote delegated task", () => { + const base = makeProjection(); + for (const status of ["completed", "waiting"] as const) { + const projection = { + ...base, + runs: [{ ...base.runs[0]!, status }], + providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }], + turnItems: [ + { + id: "item:remote-delegated", + threadId, + runId, + nodeId: NodeId.make("task:remote"), + providerThreadId, + type: "subagent", + subagentId: NodeId.make("task:remote"), + origin: "app_owned", + driver, + providerInstanceId: instanceId, + childThreadId: null, + remoteChild: { + environmentId: "env:box", + threadId: ThreadId.make("thread:remote-child"), + label: "Box", + }, + status: "running", + title: "Remote task", + prompt: "Check remote tests", + result: null, + }, + ], + } as unknown as OrchestrationV2ThreadProjection; + assert.isUndefined(restartContinuationRun(projection, now), status); + } +}); diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.ts index 21d70c62f920e..806f17c20c197 100644 --- a/apps/server/src/orchestration-v2/RestartContinuation.ts +++ b/apps/server/src/orchestration-v2/RestartContinuation.ts @@ -144,7 +144,11 @@ function hasOpenAwaitedWork( const openItem = projection.turnItems.some((item) => { if (item.status !== "pending" && item.status !== "running" && item.status !== "waiting") return false; - if (item.type === "subagent" && item.origin === "app_owned" && item.childThreadId !== null) + if ( + item.type === "subagent" && + item.origin === "app_owned" && + (item.childThreadId !== null || item.remoteChild !== undefined) + ) return false; const work = cancelledTurnItemWork(item); return ( diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 3c14fb427fc2e..d075c44ef9ff2 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -37,7 +37,7 @@ import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Tracer from "effect/Tracer"; import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as TestClock from "effect/testing/TestClock"; -import type * as SqlClient from "effect/sql/SqlClient"; +import * as SqlClient from "effect/sql/SqlClient"; import { McpSchema, McpServer } from "effect/ai"; import * as ServerConfig from "../config.ts"; @@ -2079,6 +2079,37 @@ it.effect("stopping the parent stops its task there", () => ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); +it.effect("the parent's Stop queues stopping a task that runs only there", () => + Effect.scoped( + Effect.gen(function* () { + const thread = yield* makeBoxThread; + const b = yield* serveBox(thread); + const offers = yield* SubscriptionRef.make< + ReadonlyArray + >([]); + const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build); + const a = yield* makeLaptop(database, offers); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + + yield* delegateToBox(a); + yield* a.orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("command:thread-stop:remote-only"), + threadId: parentThreadId, + reason: "User stopped", + }); + const sql = Context.get(database, SqlClient.SqlClient); + const outbox = yield* sql<{ readonly effect_type: string }>` + SELECT effect_type + FROM orchestration_v2_effect_outbox + WHERE thread_id = ${parentThreadId} + `; + expect(outbox.some((row) => row.effect_type === "delegated-tasks.stop")).toBe(true); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + /** A follower retry schedule the test steps: each failed attempt is offered, then waits for `retry`. */ const steppedRetries = Effect.gen(function* () { const failed = yield* Queue.unbounded(); From 59fe770e01e14c6675783ff14e7370e6841fe0cb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:20:07 -0800 Subject: [PATCH 33/65] fix(web): pull request review drafts survive a reload (#42090) --- .../pullRequestReviewStore.test.ts | 31 ++++- .../pullRequest/pullRequestReviewStore.ts | 119 ++++++++++++------ 2 files changed, 108 insertions(+), 42 deletions(-) diff --git a/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts b/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts index 2ba71f34eb080..f3a2cf3d1dc7b 100644 --- a/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestReviewStore.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from "vite-plus/test"; +import { beforeEach, describe, expect, it, vi } from "vite-plus/test"; import { ProjectId } from "@t3tools/contracts"; import { @@ -6,6 +6,7 @@ import { pullRequestReviewKey, usePullRequestReviewStore, } from "./pullRequestReviewStore"; +import { createMemoryStorage } from "../../lib/storage"; function comment(id: string, body = id): PendingReviewComment { return { id, body, path: "src/app.ts", position: { kind: "added", newLine: 1 } }; @@ -62,4 +63,32 @@ describe("pull request review drafts", () => { expect(usePullRequestReviewStore.getState().summaries["review-a"]).toBe("Revised body"); }); + + // regression: #42078 line comments and the summary were lost when the window reloaded + it("keeps unsubmitted line comments and the summary across a reload", async () => { + vi.stubGlobal("localStorage", createMemoryStorage()); + vi.useFakeTimers(); + vi.resetModules(); + try { + const before = await import("./pullRequestReviewStore"); + before.usePullRequestReviewStore.getState().addComment("review-a", comment("drafted")); + before.usePullRequestReviewStore.getState().setSummary("review-a", "Drafted summary"); + await vi.runAllTimersAsync(); + + vi.resetModules(); + const after = await import("./pullRequestReviewStore"); + await vi.runAllTimersAsync(); + + expect(after.usePullRequestReviewStore.getState().drafts["review-a"]).toEqual([ + comment("drafted"), + ]); + expect(after.usePullRequestReviewStore.getState().summaries["review-a"]).toBe( + "Drafted summary", + ); + } finally { + vi.useRealTimers(); + vi.unstubAllGlobals(); + vi.resetModules(); + } + }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestReviewStore.ts b/apps/web/src/components/pullRequest/pullRequestReviewStore.ts index d48695ed8f5a2..dd89d149076c1 100644 --- a/apps/web/src/components/pullRequest/pullRequestReviewStore.ts +++ b/apps/web/src/components/pullRequest/pullRequestReviewStore.ts @@ -1,14 +1,16 @@ -import type { PullRequestRef, PullRequestReviewCommentDraft } from "@t3tools/contracts"; +import { type PullRequestRef, PullRequestReviewCommentDraft } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; import { create } from "zustand"; +import { createJSONStorage, persist } from "zustand/middleware"; -export type PendingReviewComment = PullRequestReviewCommentDraft & { readonly id: string }; +import { resolveStorage } from "../../lib/storage"; +import { randomUUID } from "../../lib/utils"; -// Content-derived ids can collide across comments; use a counter. -let pendingCommentSequence = 0; +export type PendingReviewComment = PullRequestReviewCommentDraft & { readonly id: string }; +// Content-derived ids can collide across comments, and a counter restarts below persisted ids. export function nextPendingReviewCommentId(): string { - pendingCommentSequence += 1; - return `pending-review-comment-${pendingCommentSequence}`; + return `pending-review-comment-${randomUUID()}`; } export function pullRequestReviewKey(reference: PullRequestRef): string { @@ -33,42 +35,77 @@ interface PullRequestReviewStoreState { const EMPTY: ReadonlyArray = []; -export const usePullRequestReviewStore = create()((set) => ({ - drafts: {}, - summaries: {}, - addComment: (key, comment) => - set((state) => ({ - drafts: { ...state.drafts, [key]: [...(state.drafts[key] ?? EMPTY), comment] }, - })), - removeComment: (key, commentId) => - set((state) => { - const remaining = (state.drafts[key] ?? EMPTY).filter((entry) => entry.id !== commentId); - if (remaining.length > 0) return { drafts: { ...state.drafts, [key]: remaining } }; - const { [key]: _removed, ...rest } = state.drafts; - return { drafts: rest }; - }), - removeComments: (key, commentIds) => - set((state) => { - const submitted = new Set(commentIds); - const remaining = (state.drafts[key] ?? EMPTY).filter((entry) => !submitted.has(entry.id)); - if (remaining.length > 0) return { drafts: { ...state.drafts, [key]: remaining } }; - const { [key]: _removed, ...rest } = state.drafts; - return { drafts: rest }; - }), - clear: (key) => - set((state) => { - const { [key]: _removed, ...rest } = state.drafts; - return { drafts: rest }; - }), - setSummary: (key, body) => set((state) => ({ summaries: { ...state.summaries, [key]: body } })), - clearSummary: (key, submittedBody) => - set((state) => { - // Keep summary edits made during submission; the textarea stays editable. - if (state.summaries[key] !== submittedBody) return state; - const { [key]: _removed, ...rest } = state.summaries; - return { summaries: rest }; +const isCommentDraft = Schema.is(PullRequestReviewCommentDraft); +const isPendingComment = (entry: unknown): entry is PendingReviewComment => + isCommentDraft(entry) && typeof (entry as { id?: unknown }).id === "string"; + +type PersistedReviewDrafts = Pick; + +function restoreReviewDrafts(persisted: unknown): PersistedReviewDrafts { + const candidate = persisted as Partial> | null; + const drafts: Record> = {}; + for (const [key, comments] of Object.entries(candidate?.drafts ?? {})) { + const valid = Array.isArray(comments) ? comments.filter(isPendingComment) : []; + if (valid.length > 0) drafts[key] = valid; + } + const summaries: Record = {}; + for (const [key, body] of Object.entries(candidate?.summaries ?? {})) { + if (typeof body === "string") summaries[key] = body; + } + return { drafts, summaries }; +} + +export const usePullRequestReviewStore = create()( + persist( + (set) => ({ + drafts: {}, + summaries: {}, + addComment: (key, comment) => + set((state) => ({ + drafts: { ...state.drafts, [key]: [...(state.drafts[key] ?? EMPTY), comment] }, + })), + removeComment: (key, commentId) => + set((state) => { + const remaining = (state.drafts[key] ?? EMPTY).filter((entry) => entry.id !== commentId); + if (remaining.length > 0) return { drafts: { ...state.drafts, [key]: remaining } }; + const { [key]: _removed, ...rest } = state.drafts; + return { drafts: rest }; + }), + removeComments: (key, commentIds) => + set((state) => { + const submitted = new Set(commentIds); + const remaining = (state.drafts[key] ?? EMPTY).filter( + (entry) => !submitted.has(entry.id), + ); + if (remaining.length > 0) return { drafts: { ...state.drafts, [key]: remaining } }; + const { [key]: _removed, ...rest } = state.drafts; + return { drafts: rest }; + }), + clear: (key) => + set((state) => { + const { [key]: _removed, ...rest } = state.drafts; + return { drafts: rest }; + }), + setSummary: (key, body) => + set((state) => ({ summaries: { ...state.summaries, [key]: body } })), + clearSummary: (key, submittedBody) => + set((state) => { + // Keep summary edits made during submission; the textarea stays editable. + if (state.summaries[key] !== submittedBody) return state; + const { [key]: _removed, ...rest } = state.summaries; + return { summaries: rest }; + }), }), -})); + { + name: "t3code:pull-request-review-drafts:v1", + storage: createJSONStorage(() => + resolveStorage(typeof localStorage !== "undefined" ? localStorage : undefined), + ), + partialize: ({ drafts, summaries }) => ({ drafts, summaries }), + merge: (persisted, current) => ({ ...current, ...restoreReviewDrafts(persisted) }), + }, + ), +); export function usePendingReviewComments( reference: PullRequestRef, From 2cc8e73014d4059752efe717aea960dd5fac8368 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:27:43 -0800 Subject: [PATCH 34/65] fix(server): a message steered in after a self-settle request keeps the thread open (#42092) --- .../ThreadManagementService.test.ts | 55 +++++++++++++++++++ .../ThreadManagementService.ts | 15 +++++ 2 files changed, 70 insertions(+) diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 42a8d7eae9cff..631f9089049c0 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -907,6 +907,7 @@ it.effect.each([ ({ thread: { id: threadId, projectId, deletedAt: null }, runs: raced ? [...runs, nextRun] : runs, + turnItems: [], messages: [ { id: MessageId.make("original"), runId, role: "user" as const }, { @@ -1000,6 +1001,60 @@ it.effect.each([ }), ); +// The agent reads a message steered in after it asked to settle and ends on a question. +it.effect.each(["steer", "promoted_queued_to_steer"] as const)( + "settleAfterRun keeps the thread open after a %s read once the settle was requested", + (inputIntent) => + Effect.gen(function* () { + const projectId = ProjectId.make("project:thread-management:settle-after-steer"); + const threadId = ThreadId.make("thread:thread-management:settle-after-steer"); + const runId = RunId.make("run:thread-management:settle-after-steer"); + yield* TestClock.adjust(Duration.millis(60_000)); + const dispatched: Array = []; + const layerTest = ThreadManagementService.layer.pipe( + Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})), + Layer.provide( + Layer.mock(Orchestrator.OrchestratorV2)({ + getThreadEventSequence: () => Effect.succeed(0), + restartContinuationPending: () => Effect.succeed(false), + streamStoredEventsFrom: () => Stream.empty, + getThreadRecords: () => + Effect.succeed({ + thread: { id: threadId, projectId, deletedAt: null }, + runs: [{ id: runId, ordinal: 1, status: "completed", userMessageId: "original" }], + messages: [ + { id: "original", runId, role: "user" }, + { id: "steered", runId, role: "user" }, + ], + turnItems: [ + { + runId, + type: "user_message", + inputIntent, + status: "completed", + createdAt: "1970-01-01T00:01:30.000Z", + completedAt: "1970-01-01T00:01:30.000Z", + }, + ], + } as unknown as OrchestrationV2ThreadProjection), + dispatch: (command) => + Effect.sync(() => { + dispatched.push(command.type); + return { sequence: 1, storedEvents: [] } as never; + }), + }), + ), + Layer.provide(ServerSettings.layerTest()), + Layer.provide(layerReceiptsTest), + ); + const service = yield* ThreadManagementService.ThreadManagementService.pipe( + Effect.provide(layerTest), + ); + yield* service.settleAfterRun({ projectId, threadId, runId }); + expect(dispatched).toEqual([]); + }), +); + it.effect.each([ { name: "kills the thread's own agent and ends its turn", diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 0c8879cfe18a5..e3bc51179ed10 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1251,6 +1251,21 @@ const make = Effect.gen(function* () { const requestedAt = yield* DateTime.now; const { run } = yield* waitForThread({ ...input, timeoutMs: SETTLE_AFTER_RUN_WAIT_MS }); if (run?.status !== "completed") return; + // A message steered into this run and read after the request supersedes it. + const { turnItems } = yield* getProjectThreadRecords(input, ["turnItems"], { + turnItemRunIds: [run.id], + turnItemTypes: ["user_message"], + }); + if ( + turnItems.some( + (item) => + item.type === "user_message" && + (item.inputIntent === "steer" || item.inputIntent === "promoted_queued_to_steer") && + item.completedAt !== null && + !DateTime.isLessThan(DateTime.makeUnsafe(item.completedAt), requestedAt), + ) + ) + return; const afterSequence = yield* orchestrator.getThreadEventSequence(input.threadId); const trySettle = Effect.gen(function* () { const sequence = yield* orchestrator.getThreadEventSequence(input.threadId); From 75443857dcaa17913379836245fc50146c56202a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 03:37:26 -0800 Subject: [PATCH 35/65] fix(web): Settings text typed before Navigation: Back is saved (#42085) --- .../components/AppRouteModal.browser.test.tsx | 28 +++++++++++++++++++ apps/web/src/components/AppRouteModal.tsx | 27 ++++++++++++++++-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/AppRouteModal.browser.test.tsx b/apps/web/src/components/AppRouteModal.browser.test.tsx index 814cb87f946b0..429e76b3bab69 100644 --- a/apps/web/src/components/AppRouteModal.browser.test.tsx +++ b/apps/web/src/components/AppRouteModal.browser.test.tsx @@ -1,3 +1,4 @@ +import { redirect, useLocation } from "@tanstack/react-router"; import { describe, expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; @@ -27,6 +28,33 @@ describe("AppRouteModal", () => { expect(onCommit).toHaveBeenCalledWith("Keep titles short"); }); + // regression: #42075. Navigation: Back (mod+[) leaves the Settings route without closing the dialog. + it("commits a focused field when the route goes back", async () => { + const onCommit = vi.fn(); + function SettingsRoute() { + const pathname = useLocation({ select: (location) => location.pathname }); + return pathname.startsWith("/settings") ? ( + + + + ) : null; + } + await using screen = await render(, { router: "/" }); + // The app redirects /settings, and the router skips onBeforeNavigate after a redirect. + screen.router!.routeTree.update({ + beforeLoad: ({ location }: { location: { pathname: string } }) => { + if (location.pathname === "/settings") throw redirect({ to: "/settings/general" }); + }, + }); + await screen.router!.navigate({ to: "/settings" }); + + await page.getByRole("textbox", { name: "Instructions" }).fill("Keep titles short"); + screen.router!.history.back(); + + await expect.element(page.getByRole("dialog", { name: "Settings" })).not.toBeInTheDocument(); + expect(onCommit).toHaveBeenCalledWith("Keep titles short"); + }); + it("returns focus to the opener when Esc closes it", async () => { const opener = ; await using screen = await render(opener, { router: "/" }); diff --git a/apps/web/src/components/AppRouteModal.tsx b/apps/web/src/components/AppRouteModal.tsx index 1414b198afdc4..95effddf3698c 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -1,7 +1,8 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; import { T, useGT } from "gt-react"; import { XIcon } from "lucide-react"; -import { useRef, useState, type CSSProperties, type ReactNode } from "react"; +import { useRouter } from "@tanstack/react-router"; +import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react"; import { getCommandPaletteOpener } from "../commandPaletteStore"; import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay"; @@ -35,6 +36,22 @@ export function AppRouteModal({ label, children }: { label: string; children: Re // buttons). Below sm the modal fills the window and leaves that strip empty; up to lg its // 1.5rem inset is shorter than the strip. const nativeTitlebarHeight = useNativeTitlebarHeight(); + const router = useRouter(); + // Leaving the page without closing (Navigation: Back) unmounts a focused field during a + // commit, when React no longer delivers its blur, so commit-on-blur rows would drop what was + // typed. Blur text fields before the navigation renders; other controls keep their focus. + // Not onBeforeNavigate: the router skips it while a past redirect is still recorded. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- router listener that blurs a field before navigation unmounts it + useEffect( + () => + router.subscribe("onBeforeLoad", ({ pathChanged }) => { + const focused = document.activeElement; + if (pathChanged && focused?.matches("input, textarea, [contenteditable]")) { + blurFocusedWithin(popupRef.current); + } + }), + [router], + ); return ( { @@ -116,6 +132,11 @@ export function AppRouteModal({ label, children }: { label: string; children: Re ); } +function blurFocusedWithin(container: HTMLElement | null) { + const focused = document.activeElement; + if (focused instanceof HTMLElement && container?.contains(focused)) focused.blur(); +} + export function AppRouteModalClose() { const gt = useGT(); return ( From b51399fb3899e35aebbcdd56d1c63eca5672fac2 Mon Sep 17 00:00:00 2001 From: Victor Date: Tue, 24 Nov 2026 05:38:02 -0600 Subject: [PATCH 36/65] fix(web): a held Esc or a search of spaces no longer closes Settings (#42093) Co-authored-by: Julius Marminge --- ...ngsSidebarNav.composition.browser.test.tsx | 37 +++++++++++++++++++ .../settings/SettingsSidebarNav.tsx | 2 +- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx index 338c4ff0fa111..88aafbd568600 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.composition.browser.test.tsx @@ -2,6 +2,7 @@ import { expect, it, vi } from "vite-plus/test"; import { page, userEvent } from "vite-plus/test/browser"; import { act, render } from "../../../test/render"; +import { AppRouteModal } from "../AppRouteModal"; import { SidebarProvider } from "../ui/sidebar"; import { SettingsSidebarNav } from "./SettingsSidebarNav"; import { settingsNavGroups, SETTINGS_SECTION_LABELS } from "./settingsSearch"; @@ -12,6 +13,7 @@ vi.mock("./useAvailableSettingsSearchItems", () => ({ ], useHasSecretProvidersEnvironment: () => false, })); +vi.mock("../chat/GlobalVoiceInputIndicator", () => ({ GlobalVoiceInputIndicator: () => null })); it("ignores composing keys in the search", async () => { await using screen = await render( @@ -45,6 +47,41 @@ it("ignores composing keys in the search", async () => { ); }); +it("Esc clears a search of spaces and a held Esc keeps Settings open", async () => { + await using _screen = await render( + + + + + , + { router: "/settings/general" }, + ); + const settings = page.getByRole("dialog", { name: "Settings" }); + const search = page.getByRole("combobox", { name: "Search settings" }); + await expect.element(settings).toHaveFocus(); + + for (const text of ["theme", " "]) { + await search.fill(text); + await userEvent.keyboard("{Escape}"); + await expect.element(search).toHaveValue(""); + await expect.element(search).toHaveFocus(); + await act(() => + search.element().dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + repeat: true, + bubbles: true, + cancelable: true, + }), + ), + ); + await expect.element(settings).toHaveAttribute("data-open"); + } + + await userEvent.keyboard("{Escape}"); + await expect.element(settings).not.toBeInTheDocument(); +}); + function renderNav() { return render( diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 10bc07c123dd8..3c0c506ef9912 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -234,7 +234,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { const handleSearchKeyDown = (event: KeyboardEvent) => { if (event.nativeEvent.isComposing || event.keyCode === 229) return; - if (event.key === "Escape" && isSearching) { + if (event.key === "Escape" && (query || event.repeat)) { event.preventDefault(); event.stopPropagation(); clearSearch(); From 6f6b9786675968e318b82083888bbe2c428920d4 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:17:41 +0530 Subject: [PATCH 37/65] =?UTF-8?q?fix(web):=20image=20preview=20closes=20wi?= =?UTF-8?q?th=20an=20=C3=97=20again=20instead=20of=20a=20Back=20button=20(?= =?UTF-8?q?#41963)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Opus 5.5 --- .../chat/ExpandedImageDialog.browser.test.tsx | 8 ++------ .../components/chat/ExpandedImageDialog.tsx | 19 ++++++------------- .../chat/QueuedRunsControl.browser.test.tsx | 2 +- .../AttachmentFilePreview.browser.test.tsx | 2 +- apps/web/src/i18n/translations/de.json | 4 ++-- apps/web/src/i18n/translations/en.json | 4 ++-- apps/web/src/i18n/translations/es.json | 4 ++-- apps/web/src/i18n/translations/fr.json | 4 ++-- apps/web/src/i18n/translations/ja.json | 4 ++-- apps/web/src/i18n/translations/ko.json | 4 ++-- apps/web/src/i18n/translations/pt-BR.json | 4 ++-- apps/web/src/i18n/translations/ru.json | 4 ++-- apps/web/src/i18n/translations/sv.json | 4 ++-- apps/web/src/i18n/translations/zh.json | 4 ++-- 14 files changed, 30 insertions(+), 41 deletions(-) diff --git a/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx index 915ed5f929538..7287547df71fc 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.browser.test.tsx @@ -53,9 +53,7 @@ describe("ExpandedImageDialog", () => { await userEvent.keyboard("{Tab}"); await userEvent.keyboard("{Enter}"); } - await expect - .element(page.getByRole("button", { name: "Back, close image preview" })) - .toHaveFocus(); + await expect.element(page.getByRole("button", { name: "Close image preview" })).toHaveFocus(); await userEvent.keyboard("{Escape}"); await expect.element(opener).toHaveFocus(); expect(opener.element().matches(":focus-visible")).toBe(c.focusVisible); @@ -116,9 +114,7 @@ describe("ExpandedImageDialog", () => { expect(onClose).not.toHaveBeenCalled(); // Focus returns to the popup's trigger and opens its tooltip; leave it for a plain control. - ( - screen.getByRole("button", { name: "Back, close image preview" }).element() as HTMLElement - ).focus(); + (screen.getByRole("button", { name: "Close image preview" }).element() as HTMLElement).focus(); await userEvent.keyboard("{Escape}"); await vi.waitFor(() => expect(onClose).toHaveBeenCalledOnce()); }); diff --git a/apps/web/src/components/chat/ExpandedImageDialog.tsx b/apps/web/src/components/chat/ExpandedImageDialog.tsx index 0f278c408d487..0d6f1b812de69 100644 --- a/apps/web/src/components/chat/ExpandedImageDialog.tsx +++ b/apps/web/src/components/chat/ExpandedImageDialog.tsx @@ -1,13 +1,7 @@ import { memo, useRef, useState, type ReactNode, type KeyboardEvent } from "react"; import { flushSync } from "react-dom"; -import { T, useGT } from "gt-react"; -import { - ArrowLeftIcon, - ChevronLeftIcon, - ChevronRightIcon, - ImageIcon, - TextIcon, -} from "lucide-react"; +import { useGT } from "gt-react"; +import { ChevronLeftIcon, ChevronRightIcon, ImageIcon, TextIcon, XIcon } from "lucide-react"; import { Button } from "../ui/button"; import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog"; import type { ExpandedImageItem, ExpandedImagePreview } from "./ExpandedImagePreview"; @@ -200,14 +194,13 @@ export const ExpandedImageDialog = memo(function ExpandedImageDialog({ {preview.images.length > 1 && ( ) : null} ); From 4c31da157b6096713c0b790f3b0333fb5c3ea568 Mon Sep 17 00:00:00 2001 From: Georgi Todorov <68182763+jorotodorovv@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:19:18 +0200 Subject: [PATCH 59/65] fix(server): Linux agent CLIs spawned via ProcessLauncher no longer show in Servers (#42151) Co-authored-by: Julius Marminge --- apps/server/src/preview/PortScanner.test.ts | 93 +++++++++++++++++++-- apps/server/src/preview/PortScanner.ts | 50 +++++++++-- apps/server/src/process/ProcessLauncher.ts | 23 ++++- apps/server/src/processRunner.test.ts | 17 ++-- 4 files changed, 155 insertions(+), 28 deletions(-) diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index 3bf974e58c373..2f9ea973261f9 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -23,6 +23,7 @@ import { expect, vi } from "vite-plus/test"; import { FetchHttpClient } from "effect/http"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as ProcessRunner from "../processRunner.ts"; import * as PortScanner from "./PortScanner.ts"; @@ -1023,12 +1024,17 @@ effectIt.effect.each(["linux", "darwin"] as const)( effectIt.effect("stops only a job's own process group", () => Effect.sync(() => { const serverPid = 100; + const launcherPid = 150; const rows = [ { pid: 10, ppid: 1, pgid: 10 }, // `vp run dev`, whose job holds this server { pid: 20, ppid: 10, pgid: 10 }, // the web dev server in the same job { pid: serverPid, ppid: 10, pgid: 10 }, - { pid: 200, ppid: serverPid, pgid: 200 }, // agent CLI + { pid: launcherPid, ppid: serverPid, pgid: 10 }, // Linux ProcessLauncher worker + { pid: 200, ppid: serverPid, pgid: 200 }, // direct agent CLI { pid: 210, ppid: 200, pgid: 200 }, // a server it spawned without a group of its own + { pid: 250, ppid: launcherPid, pgid: 250 }, // launcher-spawned agent CLI (e.g. agy acp) + { pid: 260, ppid: 250, pgid: 250 }, // a server in the launcher-spawned agent CLI's group + { pid: 270, ppid: 250, pgid: 270 }, // a job started by the launcher-spawned agent CLI { pid: 300, ppid: 200, pgid: 300 }, // agent tool shell { pid: 400, ppid: 300, pgid: 400 }, // `npm run dev &` { pid: 401, ppid: 400, pgid: 400 }, @@ -1036,10 +1042,11 @@ effectIt.effect("stops only a job's own process group", () => { pid: 600, ppid: 500, pgid: 600 }, // terminal job ]; const table = new Map(rows.map((row) => [row.pid, row])); - expect(PortScanner.stoppableProcessGroup(table, 401, serverPid)).toBe(400); - expect(PortScanner.stoppableProcessGroup(table, 600, serverPid)).toBe(600); - for (const pid of [20, 210, 500, 999]) { - expect(PortScanner.stoppableProcessGroup(table, pid, serverPid)).toBeNull(); + expect(PortScanner.stoppableProcessGroup(table, 401, serverPid, launcherPid)).toBe(400); + expect(PortScanner.stoppableProcessGroup(table, 600, serverPid, launcherPid)).toBe(600); + expect(PortScanner.stoppableProcessGroup(table, 270, serverPid, launcherPid)).toBe(270); + for (const pid of [20, 150, 210, 250, 260, 500, 999]) { + expect(PortScanner.stoppableProcessGroup(table, pid, serverPid, launcherPid)).toBeNull(); } // The tool shell is the command; its `npm run dev &` job only inherited the name. const variables = new Map([ @@ -1055,6 +1062,82 @@ effectIt.effect("stops only a job's own process group", () => }), ); +effectIt.effect( + "excludes Linux agent CLIs spawned through ProcessLauncher (including after restarts) while keeping their dev servers", + () => { + let launcherPid = 9_000; + const firstDevPort = 43_201; + const secondDevPort = 43_202; + let lsofStdout = + `p4300\ncagy\nn127.0.0.1:43200\n` + + `p4301\ncclaude\nn127.0.0.1:43199\n` + + `p4242\ncnode\nn127.0.0.1:${firstDevPort}\n`; + const procFiles: Record = { + "/proc/4300/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agy\0`, + "/proc/4300/stat": `4300 (agy) S ${launcherPid} 4300 4300 0`, + "/proc/4301/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-claude\0`, + "/proc/4301/stat": `4301 (claude) S ${process.pid} 4301 4301 0`, + "/proc/4242/environ": `${PortScanner.AGENT_THREAD_ENV}=thread-agy\0`, + "/proc/4242/stat": "4242 (node) S 4300 4300 4300 0", + }; + const missing = FileSystem.makeNoop({}); + const layer = layerScanner.pipe( + Layer.provide( + Layer.mergeAll( + FileSystem.layerNoop({ + readFileString: (path) => { + const content = procFiles[path]; + return content === undefined ? missing.readFileString(path) : Effect.succeed(content); + }, + }), + Layer.succeed(ProcessRunner.ProcessRunner, { + run: (input) => + input.command === "lsof" + ? Effect.succeed(processOutput(lsofStdout)) + : Effect.succeed( + processOutput( + `${launcherPid} ${process.pid} ${process.pid}\n` + + `4300 ${launcherPid} 4300\n` + + "4242 4300 4300\n", + ), + ), + }), + Layer.succeed(ProcessLauncher.ProcessLauncher, { + currentPid: Effect.sync(() => launcherPid), + }), + Layer.succeed(HostProcess.Platform, "linux"), + FetchHttpClient.layer.pipe( + Layer.provide(Layer.succeed(FetchHttpClient.Fetch, () => Promise.reject(new Error()))), + ), + ), + ), + ); + + return Effect.gen(function* () { + const scanner = yield* PortScanner.PortDiscovery; + expect(yield* scanner.scan()).toMatchObject([ + { port: firstDevPort, pid: 4242, agent: { threadId: "thread-agy" } }, + ]); + + // Refuses to stop a server sharing the ProcessLauncher-spawned agent CLI's process group. + const stop = yield* Effect.flip(scanner.stopServer({ pid: 4242, port: firstDevPort })); + expect(stop.reason).toBe("shared-group"); + + // After ProcessLauncher restarts with a new helper PID, new agent CLIs are still excluded. + launcherPid = 9_001; + procFiles["/proc/4400/environ"] = `${PortScanner.AGENT_THREAD_ENV}=thread-agy-2\0`; + procFiles["/proc/4400/stat"] = `4400 (agy) S ${launcherPid} 4400 4400 0`; + procFiles["/proc/4401/environ"] = `${PortScanner.AGENT_THREAD_ENV}=thread-agy-2\0`; + procFiles["/proc/4401/stat"] = "4401 (node) S 4400 4401 4401 0"; + lsofStdout = `p4400\ncagy\nn127.0.0.1:43210\np4401\ncnode\nn127.0.0.1:${secondDevPort}\n`; + + expect(yield* scanner.scan()).toMatchObject([ + { port: secondDevPort, pid: 4401, agent: { threadId: "thread-agy-2" } }, + ]); + }).pipe(Effect.provide(layer)); + }, +); + effectIt.effect.each([ { case: "its parent's arguments", diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index 794d88e9c6ba2..c48d6a3ad6abe 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -26,6 +26,7 @@ import * as Semaphore from "effect/Semaphore"; import { FetchHttpClient, HttpClient } from "effect/http"; import * as BackgroundPolicy from "../background/BackgroundPolicy.ts"; +import * as ProcessLauncher from "../process/ProcessLauncher.ts"; import * as WindowsTcpListeners from "../process/windowsTcpListeners.ts"; import * as ProcessRunner from "../processRunner.ts"; @@ -388,14 +389,23 @@ const parseProcEnvironThread = (raw: string): ThreadId | null => { }; /** - * A listener with an agent thread in its environment. An agent CLI is a direct child of this - * server and has that environment too, but its own ports are not servers it started. + * A listener with an agent thread in its environment. An agent CLI is spawned directly by this + * server or its Linux process launcher and has that environment too, but its own ports are not + * servers it started. */ interface AgentListener { readonly threadId: ThreadId; readonly isAgentCli: boolean; } +const isServerSpawnedChild = ( + parentPid: number | null, + serverPid: number, + launcherPid?: number, +): boolean => + parentPid !== null && + (parentPid === serverPid || (launcherPid !== undefined && parentPid === launcherPid)); + /** Reads the parent pid from `/proc//stat`, whose command field can hold spaces. */ const parseProcStatParent = (raw: string): number | null => { const parent = Number( @@ -414,6 +424,7 @@ const parseProcStatParent = (raw: string): number | null => { const parsePsEnvironmentThreads = ( raw: string, serverPid: number, + launcherPid?: number, ): ReadonlyMap => { const threads = new Map(); for (const line of raw.split("\n")) { @@ -423,7 +434,10 @@ const parsePsEnvironmentThreads = ( threads.set( Number(match[1]), value && !DEVTOOLS_PORT_ARGUMENT.test(match[3]!) - ? { threadId: ThreadId.make(value), isAgentCli: Number(match[2]) === serverPid } + ? { + threadId: ThreadId.make(value), + isAgentCli: isServerSpawnedChild(Number(match[2]), serverPid, launcherPid), + } : null, ); } @@ -489,16 +503,19 @@ const parseProcessTable = (raw: string): ReadonlyMap => /** * The process group stopping `pid` signals. Shells with job control and agent tool shells give * every job its own group, so the group is the job. Null when the group also holds this server, - * a direct child of it (agent CLIs and terminal shells), or one of its ancestors. + * a direct child of it or its process launcher (agent CLIs and terminal shells), or one of its + * ancestors. */ export const stoppableProcessGroup = ( table: ReadonlyMap, pid: number, serverPid: number, + launcherPid?: number, ): number | null => { const group = table.get(pid)?.pgid; if (group === undefined || group <= 1) return null; const guarded = new Set([serverPid]); + if (launcherPid !== undefined) guarded.add(launcherPid); for ( let parent = table.get(serverPid)?.ppid; parent !== undefined && parent > 1 && !guarded.has(parent); @@ -507,7 +524,12 @@ export const stoppableProcessGroup = ( guarded.add(parent); } for (const row of table.values()) { - if (row.pgid === group && (guarded.has(row.pid) || row.ppid === serverPid)) return null; + if ( + row.pgid === group && + (guarded.has(row.pid) || isServerSpawnedChild(row.ppid, serverPid, launcherPid)) + ) { + return null; + } } return group; }; @@ -551,6 +573,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { const listenerDiscovery = (yield* HostProcess.Environment)[PORT_DISCOVERY_ENV] !== "0"; const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope); const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy; + const processLauncher = yield* ProcessLauncher.ProcessLauncher; const stateRef = yield* Ref.make({ listeners: new Map(), terminalProcesses: new Map(), @@ -581,6 +604,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() { ) { const cached = yield* Ref.get(agentThreadsRef); const unread = pids.filter((pid) => !cached.has(pid)); + const launcherPid = unread.length === 0 ? undefined : yield* processLauncher.currentPid; const readProcListener = Effect.fnUntraced(function* (pid: number) { const threadId = yield* fileSystem.readFileString(`/proc/${pid}/environ`).pipe( Effect.map(parseProcEnvironThread), @@ -596,7 +620,10 @@ export const make = Effect.gen(function* PortDiscoveryMake() { Effect.map(parseProcStatParent), Effect.orElseSucceed(() => null), ); - return [pid, { threadId, isAgentCli: parent === process.pid }] as const; + return [ + pid, + { threadId, isAgentCli: isServerSpawnedChild(parent, process.pid, launcherPid) }, + ] as const; }); const read: ReadonlyMap = unread.length === 0 @@ -611,7 +638,9 @@ export const make = Effect.gen(function* PortDiscoveryMake() { maxOutputBytes: PS_MAX_OUTPUT_BYTES, }) .pipe( - Effect.map((result) => parsePsEnvironmentThreads(result.stdout, process.pid)), + Effect.map((result) => + parsePsEnvironmentThreads(result.stdout, process.pid, launcherPid), + ), Effect.orElseSucceed(() => { agentScanPending = true; return new Map(); @@ -1242,7 +1271,12 @@ export const make = Effect.gen(function* PortDiscoveryMake() { const table = yield* readProcessTable; // It exited after the scan, so there is nothing left to stop. if (!table.has(input.pid)) return; - const group = stoppableProcessGroup(table, input.pid, process.pid); + const group = stoppableProcessGroup( + table, + input.pid, + process.pid, + yield* processLauncher.currentPid, + ); if (group === null) return yield* new PreviewStopLocalServerError({ reason: "shared-group" }); // False when the whole group already exited. const signalGroup = (signal: "SIGTERM" | "SIGKILL") => diff --git a/apps/server/src/process/ProcessLauncher.ts b/apps/server/src/process/ProcessLauncher.ts index f62a3c8445da2..397be7c42885d 100644 --- a/apps/server/src/process/ProcessLauncher.ts +++ b/apps/server/src/process/ProcessLauncher.ts @@ -22,6 +22,16 @@ import type { LauncherEvent, LauncherSpawnRequest } from "./processLauncherWorke const READY_TIMEOUT = "10 seconds"; const SPAWN_REPLY_TIMEOUT = "10 seconds"; +/** + * Exposes the active Linux process-launcher helper PID so callers such as port discovery can + * recognize direct children spawned through the helper instead of directly from the server. + */ +export class ProcessLauncher extends Context.Reference<{ + readonly currentPid: Effect.Effect; +}>("t3/process/ProcessLauncher", { + defaultValue: () => ({ currentPid: Effect.undefined }), +}) {} + /** A child of the launcher, presented to the native spawner as a Node ChildProcess. */ class HostedChild extends NodeEvents.EventEmitter @@ -152,7 +162,11 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( replyTimeout: Duration.Input = SPAWN_REPLY_TIMEOUT, ) { const fallback = yield* ChildProcessSpawner.ChildProcessSpawner; - if ((yield* HostProcess.Platform) !== "linux") return fallback; + if ((yield* HostProcess.Platform) !== "linux") { + return Context.make(ChildProcessSpawner.ChildProcessSpawner, fallback).pipe( + Context.add(ProcessLauncher, { currentPid: Effect.undefined }), + ); + } const executablePath = yield* HostProcess.ExecutablePath; const args = yield* launcherArguments(); @@ -368,13 +382,16 @@ export const make = Effect.fn("ProcessLauncher.make")(function* ( ); // Start while the server is still small; the launcher's own fork is the last full-size one. launch(); - return ChildProcessSpawner.make((command) => + const spawner = ChildProcessSpawner.make((command) => Effect.flatMap(isReady, (ready) => (ready ? hosted : fallback).spawn(command)), ); + return Context.make(ChildProcessSpawner.ChildProcessSpawner, spawner).pipe( + Context.add(ProcessLauncher, { currentPid: Effect.sync(() => current?.worker.pid) }), + ); }); /** Replaces the ChildProcessSpawner in context, which stays the fallback when the launcher cannot start. */ -export const layer = Layer.effect(ChildProcessSpawner.ChildProcessSpawner, make()); +export const layer = Layer.effectContext(make()); /** The server's one spawner: memoized, so every build site shares a single launcher. */ export const layerServer = layer.pipe(Layer.provide(NonBlockingSpawner.layer)); diff --git a/apps/server/src/processRunner.test.ts b/apps/server/src/processRunner.test.ts index bd4ad037defa6..f31d7411c8625 100644 --- a/apps/server/src/processRunner.test.ts +++ b/apps/server/src/processRunner.test.ts @@ -592,10 +592,12 @@ describe("ProcessRunner.layer", () => { () => Effect.gen(function* () { const runner = yield* ProcessRunner.ProcessRunner; + const launcher = yield* ProcessLauncher.ProcessLauncher; const parentPid = runner .run({ command: "sh", args: ["-c", "echo $PPID"] }) .pipe(Effect.map((result) => expectHelperPid(result.stdout))); const helper = yield* parentPid; + expect(yield* launcher.currentPid).toBe(helper); process.kill(helper, "SIGSTOP"); const error = yield* runner.run({ command: "true", args: [] }).pipe(Effect.flip); const replacement = yield* parentPid; @@ -603,15 +605,11 @@ describe("ProcessRunner.layer", () => { expect(error._tag).toBe("ProcessSpawnError"); expect(replacement).not.toBe(helper); expect(replacement).not.toBe(process.pid); + expect(yield* launcher.currentPid).toBe(replacement); }).pipe( Effect.provide( ProcessRunner.layer.pipe( - Layer.provide( - Layer.effect( - ChildProcessSpawner.ChildProcessSpawner, - ProcessLauncher.make("1 second"), - ), - ), + Layer.provideMerge(Layer.effectContext(ProcessLauncher.make("1 second"))), Layer.provide(NodeServices.layer), ), ), @@ -651,12 +649,7 @@ describe("ProcessRunner.layer", () => { const runner = Context.get( yield* Layer.build( ProcessRunner.layer.pipe( - Layer.provide( - Layer.effect( - ChildProcessSpawner.ChildProcessSpawner, - ProcessLauncher.make("1 second"), - ), - ), + Layer.provide(Layer.effectContext(ProcessLauncher.make("1 second"))), ), ), ProcessRunner.ProcessRunner, From 13b7893ac0a17907ef76d667b2109ca6e37d26ff Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 06:24:05 -0800 Subject: [PATCH 60/65] fix(server): a timed-out provider update no longer force-kills the installer (#42171) --- .../providerMaintenanceRunner.test.ts | 65 ++++++++++++++++++- .../src/provider/providerMaintenanceRunner.ts | 36 ++-------- 2 files changed, 69 insertions(+), 32 deletions(-) diff --git a/apps/server/src/provider/providerMaintenanceRunner.test.ts b/apps/server/src/provider/providerMaintenanceRunner.test.ts index fa608d634a384..bdf74046def6d 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.test.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.test.ts @@ -876,7 +876,7 @@ describe("providerMaintenanceRunner", () => { // binary behind that later updates mistake for an install. it.effect.each([ { runFor: "6 minutes", status: "succeeded", message: "Provider updated." }, - { runFor: "31 minutes", status: "failed", message: "Update timed out after 30 minutes." }, + { runFor: "2 hours", status: "succeeded", message: "Provider updated." }, ] as const)("lets a slow installer run for $runFor", ({ runFor, status, message }) => { const started = Deferred.makeUnsafe(); return Effect.gen(function* () { @@ -1273,6 +1273,69 @@ describe("providerMaintenanceRunner", () => { }), ); + // npm moves the working package and its bin shims aside before it downloads + // the new version; a forced kill then (taskkill /F on Windows) leaves no CLI. + it.effect("does not force-kill an npm global update still running at the timeout", () => + Effect.gen(function* () { + const kills: Array = []; + let spawns = 0; + const spawned = yield* Deferred.make(); + const respawned = yield* Deferred.make(); + const exit = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make(() => + Deferred.succeed((spawns += 1) === 1 ? spawned : respawned, undefined).pipe( + Effect.as( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Deferred.await(exit), + isRunning: Effect.succeed(true), + kill: () => Effect.sync(() => kills.push("kill")), + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }), + ), + ), + ); + + yield* Effect.gen(function* () { + const { registry } = yield* makeRegistry(baseOpenCodeProvider); + const updater = yield* makeTestRunner(registry); + yield* updater.updateProvider(OPENCODE_DRIVER).pipe(Effect.forkScoped); + yield* Deferred.await(spawned); + yield* TestClock.adjust("31 minutes"); + + assert.deepStrictEqual( + kills, + [], + "the update timeout force-killed npm while it was replacing the installed CLI", + ); + // npm is still replacing the install, so a retry must not start a second installer. + yield* Effect.yieldNow.pipe(Effect.repeat({ times: 20 })); + const retry = yield* Effect.raceFirst( + updater.updateProvider(OPENCODE_DRIVER).pipe( + Effect.flip, + Effect.map((error) => error.reason), + ), + Deferred.await(respawned).pipe(Effect.as("a second installer started")), + ); + assert.include(retry, "already running"); + }).pipe( + Effect.provide( + Layer.mergeAll( + layerNonWindowsPlatform, + layerLatestVersionHttpClient("9.9.9"), + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + ), + ), + ); + }), + ); + it.effect("resolves npm to a .cmd shim from the provider's PATH on win32", () => { const captured: Array<{ readonly command: string; diff --git a/apps/server/src/provider/providerMaintenanceRunner.ts b/apps/server/src/provider/providerMaintenanceRunner.ts index a09bf1ee7dbba..4fb57bb08d3d0 100644 --- a/apps/server/src/provider/providerMaintenanceRunner.ts +++ b/apps/server/src/provider/providerMaintenanceRunner.ts @@ -15,7 +15,6 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; @@ -41,11 +40,6 @@ import type { ProviderMaintenanceCapabilities } from "@t3tools/provider-core/ser import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; const isServerProviderUpdateError = Schema.is(ServerProviderUpdateError); -// Native updaters (`claude update`) download a ~300 MB binary without printing -// progress, and killing one mid-download leaves a truncated binary that the -// next run treats as installed. Allow a slow connection to finish. -const UPDATE_TIMEOUT_MINUTES = 30; -const UPDATE_TIMEOUT_MS = UPDATE_TIMEOUT_MINUTES * 60_000; const UPDATE_OUTPUT_MAX_BYTES = 10_000; // Sample installer output because every progress update resends the provider list to all clients. const UPDATE_PROGRESS_INTERVAL = Duration.seconds(1); @@ -57,7 +51,6 @@ export interface ProviderMaintenanceCommandResult { readonly stdout: string; readonly stderr: string; readonly exitCode: number | null; - readonly timedOut: boolean; readonly stdoutTruncated: boolean; readonly stderrTruncated: boolean; } @@ -194,31 +187,16 @@ const runProviderMaintenanceCommandWithSpawner = Effect.fn("ProviderMaintenanceR stdout: stdout.text, stderr: stderr.text, exitCode: Number(exitCode), - timedOut: false, stdoutTruncated: stdout.truncated, stderrTruncated: stderr.truncated, } satisfies ProviderMaintenanceCommandResult; }, ); - return yield* collectCommandResult().pipe( - Effect.scoped, - Effect.timeoutOption(Duration.millis(UPDATE_TIMEOUT_MS)), - Effect.map((result) => - Option.match(result, { - onSome: (value) => value, - onNone: () => - ({ - stdout: "", - stderr: "", - exitCode: null, - timedOut: true, - stdoutTruncated: false, - stderrTruncated: false, - }) satisfies ProviderMaintenanceCommandResult, - }), - ), - ); + // No timeout: killing an installer mid-install leaves the provider half-replaced (npm has moved + // the old package and its shims aside; `claude update` leaves a truncated binary), and an + // installer still running must keep the update's locks until it exits. + return yield* collectCommandResult().pipe(Effect.scoped); }, ); @@ -282,9 +260,6 @@ function failureReason(result: ProviderMaintenanceCommandResult): string | null } function failureMessage(result: ProviderMaintenanceCommandResult): string { - if (result.timedOut) { - return `Update timed out after ${UPDATE_TIMEOUT_MINUTES} minutes.`; - } const summary = result.exitCode !== null && result.exitCode !== 0 ? `Update command exited with code ${result.exitCode}` @@ -594,12 +569,11 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () { ), ); const finishedAt = yield* nowIso; - if (result.timedOut || result.exitCode !== 0) { + if (result.exitCode !== 0) { yield* Effect.logWarning("Provider update command failed", { provider, command: describeCommand(command), exitCode: result.exitCode, - timedOut: result.timedOut, output: commandOutput(result), }); return yield* finish( From 480f9f48614a324cdc9dcfdb9fe7c60e8791db84 Mon Sep 17 00:00:00 2001 From: Mihai Crisan <108331599+mihaicrisan04@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:27:36 +0200 Subject: [PATCH 61/65] fix(web): shortcut recorder takes Shift+Esc instead of cancelling (#42187) Co-authored-by: Julius Marminge --- .../KeybindingsSettings.browser.test.tsx | 28 +++++++++++++++++++ .../settings/KeybindingsSettings.tsx | 19 +++++++++---- 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx b/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx index 8a91ce19d8cd5..bfe09b47aa277 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.browser.test.tsx @@ -111,6 +111,34 @@ describe("Esc in a shortcut recorder", () => { await userEvent.keyboard("{Escape}"); expect(onOpenChange).toHaveBeenCalledWith(false, expect.anything()); }); + + it.each([ + { name: "existing binding", field: existingField, open: () => activate(existingPill, "click") }, + { + name: "new binding", + field: newField, + open: async () => { + await activate(page.getByRole("button", { name: "Add keybinding" }), "click"); + await activate(newField, "focus"); + }, + }, + ])("records Shift+Esc in the $name field", async ({ field, open }) => { + const onOpenChange = vi.fn(); + await using _screen = await render( + + + Settings + + + , + ); + + await open(); + await userEvent.keyboard("{Shift>}{Escape}{/Shift}"); + + await expect.element(field).toHaveValue("shift+esc"); + expect(onOpenChange).not.toHaveBeenCalled(); + }); }); it("unassigns a default shortcut and restores its condition when one is assigned again", async () => { diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 720ec97ca0504..5ea9bc1595560 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -756,6 +756,13 @@ function rowKeybindingTarget(row: KeybindingRow): ServerRemoveKeybindingInput { }; } +// Esc with a modifier is a shortcut to record, not a cancel. +function isBareEscape(event: KeyboardEvent) { + return ( + event.key === "Escape" && !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey + ); +} + function useKeybindingRowEditor({ row, allRows, @@ -804,9 +811,9 @@ function useKeybindingRowEditor({ const captureKeybinding = (event: KeyboardEvent) => { if (event.key === "Tab" && !isRecording) return; event.preventDefault(); - if (event.key === "Escape") { - // An unhandled Escape closes the settings page. - event.stopPropagation(); + // An unhandled Escape closes the settings page. + if (event.key === "Escape") event.stopPropagation(); + if (isBareEscape(event)) { const field = event.currentTarget; flushSync(() => setDraft({ @@ -1195,9 +1202,9 @@ function useNewKeybindingDraft({ const captureKeybinding = (event: KeyboardEvent) => { if (event.key === "Tab" && !isRecording) return; event.preventDefault(); - if (event.key === "Escape") { - // An unhandled Escape closes the settings page. - event.stopPropagation(); + // An unhandled Escape closes the settings page. + if (event.key === "Escape") event.stopPropagation(); + if (isBareEscape(event)) { setDraft({ keyDraft: "", isRecording: false }); event.currentTarget.blur(); return; From ae45e00923e026b2edd037bcac8d61be11976b46 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 06:30:02 -0800 Subject: [PATCH 62/65] fix(pi): Pi exiting while its session is idle ends the session as stopped (#42196) --- .../provider-pi/src/server/adapter.test.ts | 36 +++++++++++++++++++ packages/provider-pi/src/server/adapter.ts | 14 +++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index cd9b40f834840..c0ce5cb813421 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -2078,6 +2078,42 @@ describe("PiAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("ends the session as stopped when Pi exits while no turn is running", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const adapter = yield* makeAdapter(fake, ""); + const runtime = yield* adapter.openSession({ + threadId: THREAD_ID, + providerSessionId: SESSION_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + const statuses: Array<{ status: string; lastError: string | null | undefined }> = []; + const drained = yield* runtime.events.pipe( + Stream.runForEach((event) => + Effect.sync(() => { + if (event.type === "provider_session.updated") + statuses.push({ + status: event.providerSession.status, + lastError: event.providerSession.lastError, + }); + }), + ), + Effect.exit, + Effect.forkScoped, + ); + yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* fake.closeStdout; + const exit = yield* Fiber.join(drained); + assert.isTrue(Exit.isSuccess(exit)); + assert.deepEqual(statuses.at(-1), { status: "stopped", lastError: null }); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("counts a running Pi for port discovery until its session closes", () => Effect.gen(function* () { const host = yield* ProviderHost.ProviderHost; diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 2f3b6f5b49cf7..47af91b6c78e9 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -2883,6 +2883,18 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( Effect.gen(function* () { runtimeRetired = true; const state = threadState; + // Pi ending while nothing is in flight is an idle exit, not a failure. + const idle = + state !== null && + state.activeTurn === null && + pendingWake === null && + piAsyncRuns.size === 0 && + pendingPrompts.size === 0 && + !nativeCompacting && + !registrationInProgress && + rollbackBarrier === null && + extensionStatusReset === null && + pendingPromptResponsesDrained === null; closed = true; if (pendingPromptResponsesDrained !== null) yield* Deferred.fail( @@ -2916,7 +2928,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( if (unsolicitedActivityDetected) { yield* updateProviderSession("error", PI_UNSOLICITED_ACTIVITY_ERROR); yield* Queue.end(events); - } else if (stopRequested) { + } else if (stopRequested || idle) { yield* updateProviderSession("stopped", null); yield* Queue.end(events); } else { From 43e0b37382dff937c8f376e500a694fe02b6399e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 06:41:52 -0800 Subject: [PATCH 63/65] fix(web): PR Summary tab keeps its scroll and comment order when you switch right-panel tabs (#42179) --- .../pullRequest/PullRequestDetailPanel.tsx | 10 ++- .../PullRequestSummaryTab.browser.test.tsx | 57 +++++++++++++++++ .../pullRequest/PullRequestSummaryTab.tsx | 62 +++++++++++++++++-- .../pullRequest/holdLinkedNodeInView.ts | 25 ++++++++ 4 files changed, 147 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 729c6b4157876..9bc214851c74e 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -339,6 +339,10 @@ function linkedTab(anchor: PullRequestAnchor | null): PullRequestDetailTab | nul } } +// The Summary restores its scroll on remount; a header left expanded would condense over the +// restored position and its scroll compensation would move the view. +const summaryCondensedByScopeKey = new Map(); + export function PullRequestDetailPanel({ environmentId, shortcutsEnabled, @@ -544,7 +548,7 @@ export function PullRequestDetailPanel({ // Each tab restores the condensed state its own scrolling left behind. const [condensedByTab, setCondensedByTab] = useState< Partial> - >({}); + >(() => ({ summary: summaryCondensedByScopeKey.get(tabScopeKey) ?? false })); const condensed = condensedByTab[tab] ?? false; const scrollerByTab = useRef>>({}); // Fresh ref callbacks would detach and reattach every scroller on each render. @@ -2105,7 +2109,9 @@ export function PullRequestDetailPanel({ compensationRef.current = { tab, scroller, target: top - chromeDelta }; next = true; } - if (next !== previous) setCondensedByTab({ ...condensedByTab, [tab]: next }); + if (next === previous) return; + if (tab === "summary") summaryCondensedByScopeKey.set(tabScopeKey, next); + setCondensedByTab({ ...condensedByTab, [tab]: next }); }} > {detailQuery.error && !detail ? ( diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx index a9139cc4a6e00..d208e34f934f3 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx @@ -273,6 +273,63 @@ it("shows a comment's exact time in the chosen 24-hour clock", async () => { ); }); +it("keeps the chosen comment order when the right panel remounts the tab", async () => { + setup(); + const comment = (id: string, createdAt: string) => ({ + id, + kind: "review-comment" as const, + body: `Remark ${id}`, + author: { login: "reviewer", name: null, avatarUrl: null }, + createdAt, + url: null, + path: null, + reviewState: null, + }); + const value = { + ...detail, + comments: [comment("10", "2026-09-01T10:00:00Z"), comment("11", "2026-09-02T10:00:00Z")], + commentCount: 2, + }; + { + await using screen = await render(value); + await userEvent.click(screen.getByRole("button", { name: "Show oldest comments first" })); + await expect + .element(screen.getByRole("button", { name: "Show newest comments first" })) + .toBeVisible(); + } + // Switching to another right-panel tab unmounts the pull request surface. + await using screen = await render(value); + await expect + .element(screen.getByRole("button", { name: "Show newest comments first" })) + .toBeVisible(); +}); + +it("comes back at the scroll position it left when the right panel remounts the tab", async () => { + setup(); + const body = Array.from({ length: 80 }, (_, index) => `Paragraph ${index}`).join("\n\n"); + const value = { ...detail, body, url: "https://github.com/owner/repo/pull/2" }; + const mount = async (shown = value) => { + const container = document.createElement("div"); + container.className = "flex h-[300px]"; + const screen = await renderUi(tab(shown), { container }); + const scroller = container.querySelector("[data-pull-request-summary-scroll]")!; + return Object.assign(screen, { scroller }); + }; + { + await using screen = await mount(); + screen.scroller.scrollTop = 500; + await vi.waitFor(() => expect(screen.scroller.scrollTop).toBe(500)); + await act(async () => screen.scroller.dispatchEvent(new Event("scroll"))); + } + // The tab can come back before the content that reached that position has loaded. + await using screen = await mount({ ...value, body: "Paragraph 0" }); + await screen.rerender(tab(value)); + await vi.waitFor(() => expect(screen.scroller.scrollTop).toBe(500)); + await screen.unmount(); + await using again = await mount(); + expect(again.scroller.scrollTop).toBe(500); +}); + it("scrolls from the keyboard after a click inside it", async () => { setup(); const body = Array.from({ length: 80 }, (_, index) => `Paragraph ${index}`).join("\n\n"); diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx index 1f409d282ecc3..61ccfd23e0fa8 100644 --- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx @@ -1,6 +1,6 @@ import { pullRequestCommentPreview } from "./pullRequestMarkdown.logic"; import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor"; -import { holdLinkedNodeInView } from "./holdLinkedNodeInView"; +import { holdLinkedNodeInView, holdScrollTop } from "./holdLinkedNodeInView"; import { useAtomValue } from "@effect/atom-react"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { useAtomCommand } from "~/state/use-atom-command"; @@ -25,7 +25,14 @@ import { } from "lucide-react"; import * as Schema from "effect/Schema"; import { msg, T, useGT, useMessages, Var } from "gt-react"; -import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react"; +import { + useEffect, + useEffectEvent, + useLayoutEffect, + useRef, + useState, + type ReactNode, +} from "react"; import { m, type MessageResolver } from "~/i18n/messages"; @@ -461,6 +468,14 @@ export function PullRequestSection({ const COMMENT_PAGE = 10; +interface SummaryView { + readonly order: "newest" | "oldest"; + readonly shown: number; + readonly scrollTop: number; +} +// Session-only: switching right-panel tabs unmounts the Summary, which comes back as it was left. +const summaryViewByScopeKey = new Map(); + const COMMENT_FILTER_STORAGE_KEY = "t3code:pull-request-comment-filter:v1"; const CommentFilterSchema = Schema.Struct({ bots: Schema.Boolean, resolved: Schema.Boolean }); const DEFAULT_COMMENT_FILTER: typeof CommentFilterSchema.Type = { bots: false, resolved: false }; @@ -510,7 +525,23 @@ export function PullRequestSummaryTab({ const fixCheckLabel = requestedFixCheckLabel ?? gt("Fix", { $context: "verb, fix a review finding" }); const terminology = sourceControlClients.get(detail.provider).changeRequest; - const [shown, setShown] = useState({ url: detail.url, count: COMMENT_PAGE }); + const viewKey = `${environmentId}:${detail.url}`; + const rememberView = (patch: Partial) => { + const view = summaryViewByScopeKey.get(viewKey) ?? { + order: "newest", + shown: COMMENT_PAGE, + scrollTop: 0, + }; + summaryViewByScopeKey.set(viewKey, { ...view, ...patch }); + }; + const [shown, setShownState] = useState(() => ({ + url: detail.url, + count: summaryViewByScopeKey.get(viewKey)?.shown ?? COMMENT_PAGE, + })); + const setShown = (next: { url: string; count: number }) => { + setShownState(next); + rememberView({ shown: next.count }); + }; const shownConversations = shown.url === detail.url ? shown.count : COMMENT_PAGE; const [commentFilter, setCommentFilter] = useLocalStorage( COMMENT_FILTER_STORAGE_KEY, @@ -536,7 +567,9 @@ export function PullRequestSummaryTab({ filteredItems, shownConversations, ); - const [commentOrder, setCommentOrder] = useState<"newest" | "oldest">("newest"); + const [commentOrder, setCommentOrder] = useState( + () => summaryViewByScopeKey.get(viewKey)?.order ?? "newest", + ); const visibleItems = orderPullRequestComments(recentItems, commentOrder); const showOldestCommentsButton = hiddenConversationCount > 0 ? ( @@ -637,6 +670,8 @@ export function PullRequestSummaryTab({ } } const stopHolding = useRef<(() => void) | null>(null); + // A restore clamped by content still loading must not overwrite the saved position. + const restoringScroll = useRef(false); const revealSummary = useEffectEvent(() => { const root = scrollRef.current; if (revealUrl === undefined || !root) return; @@ -674,6 +709,16 @@ export function PullRequestSummaryTab({ revealSummary(); // oxlint-disable-next-line react/exhaustive-effect-dependencies -- retries once the description markdown renders, including after its editor closes }, [revealUrl, description, checksReveals, descriptionReveals, editingDescription]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- puts a remounted Summary back at the scroll position it left, before paint + useLayoutEffect(() => { + const scrollTop = summaryViewByScopeKey.get(viewKey)?.scrollTop ?? 0; + if (!scrollRef.current || scrollTop === 0) return; + restoringScroll.current = true; + stopHolding.current = holdScrollTop(scrollRef.current, scrollTop, () => { + restoringScroll.current = false; + }); + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- restores once per mount + }, []); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the hold observes DOM outside React and must end with the tab useEffect(() => () => stopHolding.current?.(), []); // Checkbox ticks and the editor share one draft, so each starts from the other's latest body. @@ -871,6 +916,9 @@ export function PullRequestSummaryTab({ scrollRef.current = node; scrollerRef(node); }} + onScroll={(event) => { + if (!restoringScroll.current) rememberView({ scrollTop: event.currentTarget.scrollTop }); + }} tabIndex={-1} data-workspace-focus-default className="h-full overflow-y-auto outline-none" @@ -1152,7 +1200,11 @@ export function PullRequestSummaryTab({ ? gt("Show oldest comments first") : gt("Show newest comments first") } - onClick={() => setCommentOrder((value) => (value === "newest" ? "oldest" : "newest"))} + onClick={() => { + const order = commentOrder === "newest" ? "oldest" : "newest"; + setCommentOrder(order); + rememberView({ order }); + }} > {commentOrder === "newest" ? gt("Newest first") : gt("Oldest first")} diff --git a/apps/web/src/components/pullRequest/holdLinkedNodeInView.ts b/apps/web/src/components/pullRequest/holdLinkedNodeInView.ts index 4261cb2fb0da8..27d17966cc604 100644 --- a/apps/web/src/components/pullRequest/holdLinkedNodeInView.ts +++ b/apps/web/src/components/pullRequest/holdLinkedNodeInView.ts @@ -37,3 +37,28 @@ export function holdLinkedNodeInView( } return stop; } + +/** + * Keeps the scroller at `scrollTop` while content loads in under it, until the user scrolls or the + * returned stop runs. A remounted tab can render before the content that reached that offset. + */ +export function holdScrollTop( + scroller: HTMLElement, + scrollTop: number, + onStop: () => void, +): () => void { + const controller = new AbortController(); + const stop = () => { + unobserve(); + controller.abort(); + onStop(); + }; + const unobserve = observeResize([...scroller.children], () => { + scroller.scrollTop = scrollTop; + }); + for (const type of USER_SCROLL_INTENT) { + scroller.addEventListener(type, stop, { passive: true, signal: controller.signal }); + } + scroller.scrollTop = scrollTop; + return stop; +} From 53294d5a4fe0df2c34f9e43b584280793395173a Mon Sep 17 00:00:00 2001 From: AymanKhan9 Date: Tue, 24 Nov 2026 20:14:40 +0530 Subject: [PATCH 64/65] fix(server): switchRef keeps the real branch name for remotes containing slashes (#42193) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 44 ++++++++++++++++++++ apps/server/src/vcs/GitVcsDriverCore.ts | 30 +++++++++++-- 2 files changed, 70 insertions(+), 4 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 7a099e5d4ecdf..29484e835fed7 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6976,6 +6976,50 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "tracks the real branch name and refuses local collisions for remotes containing slashes", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const slashedRemote = yield* makeTmpDir("git-remote-slashed-"); + yield* git(slashedRemote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "team/origin", slashedRemote]); + yield* git(cwd, ["push", "team/origin", "HEAD:refs/heads/feature/demo"]); + yield* git(cwd, ["push", "team/origin", "HEAD:refs/heads/conflict"]); + yield* git(cwd, ["fetch", "team/origin"]); + + const driver = yield* GitVcsDriver.GitVcsDriver; + const switched = yield* driver.switchRef({ cwd, refName: "team/origin/feature/demo" }); + + assert.equal(switched.refName, "feature/demo"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "feature/demo"); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(upstream)", "refs/heads/feature/demo"]), + "refs/remotes/team/origin/feature/demo", + ); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(refname)", "refs/heads/origin"]), + "", + ); + + yield* git(cwd, ["checkout", "--no-track", "-b", "conflict"]); + yield* git(cwd, ["commit", "--allow-empty", "-m", "Local conflict work"]); + yield* git(cwd, ["checkout", initialBranch]); + + const conflicted = yield* driver + .switchRef({ cwd, refName: "team/origin/conflict" }) + .pipe(Effect.flip); + + assert.equal(conflicted.reason, "branch_already_exists"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + assert.equal( + yield* git(cwd, ["for-each-ref", "--format=%(refname)", "refs/heads/origin"]), + "", + ); + }), + ); + it.effect("rejects a missing branch without restoring a matching dirty file", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 53c5f51d7166f..5fcddc70e144a 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -6902,9 +6902,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ) : null; - const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.refName); + const localTrackedBranchCandidate = + remoteExists && !localInputExists && !localTrackingBranch + ? yield* executeGit("GitVcsDriver.switchRef.remoteNames", input.cwd, ["remote"], { + timeoutMs: 5_000, + allowNonZeroExit: true, + }).pipe( + Effect.map((result) => { + const remoteNames = result.exitCode === 0 ? parseRemoteNames(result.stdout) : []; + return ( + parseRemoteRefWithRemoteNames(input.refName, remoteNames)?.branchName ?? + deriveLocalBranchNameFromRemoteRef(input.refName) + ); + }), + ) + : null; const localTrackedBranchTargetExists = - remoteExists && !localInputExists && !localTrackingBranch && localTrackedBranchCandidate + localTrackedBranchCandidate !== null ? yield* executeGit( "GitVcsDriver.switchRef.localTrackedBranchTargetExists", input.cwd, @@ -6917,7 +6931,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : false; const newTrackingBranch = - !localInputExists && remoteExists && !localTrackingBranch && !localTrackedBranchTargetExists + localTrackedBranchCandidate !== null && !localTrackedBranchTargetExists ? localTrackedBranchCandidate : null; @@ -6926,7 +6940,15 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* : newTrackingBranch ? ["checkout", newTrackingBranch] : remoteExists && !localTrackingBranch - ? ["checkout", "--track", input.refName] + ? localTrackedBranchCandidate + ? [ + "checkout", + "--track", + "-b", + localTrackedBranchCandidate, + `refs/remotes/${input.refName}`, + ] + : ["checkout", "--track", input.refName] : remoteExists && localTrackingBranch ? ["checkout", localTrackingBranch] : ["checkout", input.refName]; From e1531b9f818e390d9d79abbc4c97426557fc6b5b Mon Sep 17 00:00:00 2001 From: Andrei Shenets Date: Tue, 24 Nov 2026 15:37:11 +0100 Subject: [PATCH 65/65] fix(web): an unfinished PR inline comment survives a refresh that changes the diff Fixes pingdotgg/t3code#42199 --- .../PullRequestCodeTab.browser.test.tsx | 47 ++++++++++++ .../pullRequest/PullRequestCodeTab.tsx | 71 ++++++++++++++++--- 2 files changed, 109 insertions(+), 9 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx index 2f9f76c941da8..241bb75fcc08f 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.browser.test.tsx @@ -396,6 +396,53 @@ it("keeps a linked test file expanded when a refresh changes the rest of the dif await expect.element(testLine).toBeVisible(); }); +// regression: #42199 an agent's push re-keyed every file and dropped the comment being typed +it("keeps an unfinished inline comment when a background refresh changes another file", async () => { + setup({ paged: false }); + mocks.withTestFile = true; + __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, diffFilesCollapsed: false }); + using _preferences = { + [Symbol.dispose]() { + __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS); + }, + }; + const reviewable = { + ...detail, + capabilities: { + ...detail.capabilities, + review: { ...detail.capabilities.review, inlineComment: true }, + }, + viewerPermissions: { ...detail.viewerPermissions, comment: true }, + }; + const reviewTab = (backgroundRefreshToken: number) => ( + {}} + environmentId={EnvironmentId.make("environment")} + reference={reviewable} + detail={reviewable} + selectedCommitOid={null} + onSelectedCommitChange={() => {}} + onRefresh={() => {}} + backgroundRefreshToken={backgroundRefreshToken} + /> + ); + const container = document.createElement("div"); + container.className = "flex h-[700px] w-[900px]"; + await using screen = await render(reviewTab(0), { container }); + const header = screen.getByText("early-0.ts", { exact: true }).first(); + await expect.element(header).toBeVisible(); + const root = header.element().getRootNode() as ShadowRoot; + await userEvent.click(root.querySelector('[data-column-number="1"]')!); + const input = () => screen.getByRole("textbox", { name: "Comment on lines early-0.ts:1" }); + await input().fill("Unsent review note"); + + mocks.refreshed = true; + await screen.rerender(reviewTab(1)); + + await expect.element(screen.getByText("4 files", { exact: true })).toBeVisible(); + await expect.element(input()).toHaveValue("Unsent review note"); +}); + // Two short pages of a source and a test file each; the next page loads only through the file tree. async function renderShortPages(stack: AsyncDisposableStack) { setup({ paged: true }); diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 159a05509fe10..1aae48ba4db00 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -59,6 +59,7 @@ import { useEffectEvent, useRef, useState, + type ComponentProps, type ReactNode, } from "react"; import { msg, T, useGT, useMessages, Var } from "gt-react"; @@ -84,6 +85,7 @@ import { isTestChangedFile } from "@t3tools/shared/changedFileKind"; import { orderDiffFilesForReview } from "@t3tools/client-runtime/diff-file-order"; import { isWorkspaceImagePreviewPath } from "@t3tools/shared/mediaPreview"; import { + buildFileDiffContentVersion, buildFileDiffIdentityKey, buildFileDiffRenderKey, fnv1a32, @@ -377,7 +379,9 @@ interface MutableAnnotationGroup { } interface DraftAnchor { - readonly fileKey: string; + // A refresh re-keys every file's render key, so the draft finds its file by identity and content. + readonly identityKey: string; + readonly fileVersion: number; readonly path: string; readonly oldPath: string | null; readonly position: PullRequestReviewPosition; @@ -385,6 +389,33 @@ interface DraftAnchor { readonly range: SelectedLineRange; } +interface SavedDraftText { + readonly draft: DraftAnchor | null; + readonly text: string; +} + +// Text is kept outside the viewer, which remounts the box when a refresh re-keys its file. +function PullRequestDraftCommentAnnotation({ + restoreText, + saveText, + ...props +}: Omit, "text" | "onTextChange"> & { + readonly restoreText: () => string; + readonly saveText: (text: string) => void; +}) { + const [text, setText] = useState(restoreText); + return ( + { + setText(next); + saveText(next); + }} + /> + ); +} + export interface PullRequestAgentSelectionInput { readonly comment: ReviewCommentContext; readonly request: string; @@ -488,6 +519,7 @@ function PullRequestCodeTab({ range: SelectedLineRange; } | null>(null); const [draft, setDraft] = useState(null); + const savedDraftText = useRef({ draft: null, text: "" }); const [threadPending, setThreadPending] = useState(false); const [orphansOpen, setOrphansOpen] = useState(false); // Scope slices before reset to prevent using a previous pull request's data or cursor. @@ -783,6 +815,22 @@ function PullRequestCodeTab({ }) : loadedFiles; const hiddenTestFileCount = loadedFiles.length - files.length; + const draftFile = + draft === null + ? undefined + : loadedFiles.find((file) => buildFileDiffIdentityKey(file) === draft.identityKey); + const draftFileKey = + draftFile !== undefined && buildFileDiffContentVersion(draftFile) === draft?.fileVersion + ? buildFileDiffRenderKey(draftFile) + : null; + if (draft !== null && draftFileKey === null) { + const diffLoaded = loadedSlices.length > 0 && loadedSlices.at(-1)?.nextCursor === null; + // Never attach the draft to lines of a changed file; one missing mid-refresh may come back. + if (draftFile !== undefined || diffLoaded) { + setDraft(null); + setSelectedLines(null); + } + } const filePaths = files.map((file) => resolveFileDiffPath(file)); const omittedFileStats = new Map( loadedSlices.flatMap((slice) => @@ -862,7 +910,7 @@ function PullRequestCodeTab({ groupAt(anchor.side, anchor.line).pending.push(comment); } } - if (draft?.fileKey === fileKey) { + if (draft !== null && draftFileKey === fileKey) { const anchor = getReviewPositionAnchor(draft.position); groupAt(anchor.side, anchor.line).draft = true; } @@ -1095,7 +1143,8 @@ function PullRequestCodeTab({ resolveDiffReviewAnchor(file, range, rangeComments); if (anchor === null) return; setDraft({ - fileKey: item.id, + identityKey: buildFileDiffIdentityKey(file), + fileVersion: buildFileDiffContentVersion(file), path, oldPath: previousPath === path ? null : previousPath, ...anchor, @@ -1108,17 +1157,16 @@ function PullRequestCodeTab({ text: string, onFinish: (comment: ReviewCommentContext) => void, ) => { - const file = files.find((candidate) => buildFileDiffRenderKey(candidate) === anchor.fileKey); const comment = - file === undefined + draftFile === undefined || draftFileKey === null ? null : buildDiffReviewComment({ - id: `pull-request-selection:${diffReviewSelectionId(anchor.fileKey, anchor.range)}`, + id: `pull-request-selection:${diffReviewSelectionId(draftFileKey, anchor.range)}`, sectionId: `pull-request:${detail.number}`, // oxlint-disable-next-line t3code/no-untranslated-copy -- context title sent to the agent sectionTitle: `PR #${detail.number} review`, filePath: anchor.path, - fileDiff: file, + fileDiff: draftFile, range: anchor.range, text, }); @@ -1355,13 +1403,18 @@ function PullRequestCodeTab({ /> ))} {annotation.metadata.draft && draft && canSelectLines ? ( - + savedDraftText.current.draft === draft ? savedDraftText.current.text : "" + } + saveText={(text) => { + savedDraftText.current = { draft, text }; + }} environmentId={environmentId} projectId={reference.projectId} ownerKey={JSON.stringify([environmentId, reviewKey, draft])} kind="draft" rangeLabel={`${draft.path}:${getReviewPositionAnchor(draft.position).line}`} - text="" completionScope={canCommentOnLines ? completionScope : null} submitLabel={canCommentOnLines ? gt("Add to review") : gt("Add to agent")} {...(canCommentOnLines && onAddToAgentSelection