From 3445b0b400d2a5928bd2c20271856830800dd13a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:32:59 -0800 Subject: [PATCH 001/128] fix(web): terminal output no longer edits a hidden question draft (#24773) --- apps/web/src/components/chat/ChatComposer.tsx | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 9e4493b5f75ae..fae55b8923d56 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -3033,7 +3033,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ); }, addTerminalContext: (selection: TerminalContextSelection) => { - if (!activeThread || isChoiceOnlyPendingQuestion || isLiteralPendingAnswer) return; + if (!activeThread) return; + // Answers are plain text, so a terminal excerpt cannot ride along with one. Writing it + // to the thread draft instead would hide it until the question closes. + if (activePendingProgress) { + toastManager.add({ + type: "info", + title: "Terminal output can't be added to a question answer.", + description: "Answer or dismiss the question first, then add it to chat.", + }); + return; + } const snapshot = readComposerSnapshotStable(); const context = { id: randomUUID(), @@ -3134,7 +3144,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) focusComposer, environmentId, primaryEnvironmentId, - isChoiceOnlyPendingQuestion, isLiteralPendingAnswer, pendingUserInputs.length, projectSelectionRequired, From 4d1808dc4cf32b331e3042a897ba4a2d8865a79d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:33:05 -0800 Subject: [PATCH 002/128] fix(opencode): show prompts other OpenCode 2 clients send into a T3 session (#27839) --- .../Adapters/OpenCode2AdapterV2.test.ts | 407 +++++++++++++++++- .../src/server/v2/adapter.ts | 88 +++- 2 files changed, 488 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 160bcc6f32699..3311723532966 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -5701,7 +5701,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); - const continued = (after: ReadonlyArray) => + const continued = (after: ReadonlyArray, external?: string) => Effect.gen(function* () { const offers: Array = []; const offered = yield* Deferred.make(); @@ -5709,6 +5709,15 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { ...backgroundLaunch(CHILD), event("session.execution.succeeded", { sessionID: SESSION }), event("session.execution.succeeded", { sessionID: CHILD }), + ...(external === undefined + ? [] + : [ + event("session.inbox.enqueued", { + inboxID: external, + sessionID: SESSION, + item: { type: "user", payload: { text: "qwe!", files: [] }, delivery: "steer" }, + }), + ]), event("session.inbox.enqueued", { inboxID: "msg_report", sessionID: SESSION, @@ -5728,6 +5737,9 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }, }), event("session.execution.started", { sessionID: SESSION }), + ...(external === undefined + ? [] + : [event("session.inbox.delivered", { sessionID: SESSION, inboxID: external })]), event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report" }), event("session.text.ended", { sessionID: SESSION, @@ -5813,6 +5825,59 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect( + "reverts OpenCode at another client's prompt queued before a continuation's report", + () => + Effect.gen(function* () { + const { runtime, thread, first, second } = yield* continued( + [ + out("message.list", ""), + reply("message.list", { + data: [ + { + id: "msg_report", + time: { created: 3 }, + text: CONTINUED_REPORT, + type: "synthetic", + }, + { id: "msg_external", time: { created: 2 }, text: "qwe!", type: "user" }, + { id: CONTINUED_PROMPT, time: { created: 1 }, text: "hi", type: "user" }, + ], + cursor: {}, + }), + out("session.revert.stage", { + sessionID: SESSION, + messageID: "msg_external", + files: false, + }), + replyData("session.revert.stage", { messageID: "msg_external", files: [] }), + out("session.revert.commit", { sessionID: SESSION }), + reply("session.revert.commit", null), + out("message.list", ""), + reply("message.list", { + data: [{ id: CONTINUED_PROMPT, time: { created: 1 }, text: "hi", type: "user" }], + cursor: {}, + }), + ], + "msg_external", + ); + const snapshot = yield* runtime.rollbackThread({ + providerThread: thread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint:first"), + appRunOrdinal: 1, + providerTurn: first, + }, + providerThreadTurns: [first, second], + }); + assert.deepEqual( + snapshot.providerTurns.map((turn) => turn.id), + [first.id], + ); + }).pipe(Effect.scoped), + ); + it.effect("keeps a subagent a stopped background reply started off the next turn", () => Effect.gen(function* () { const CHILD_B = "ses_f1485c529ffeBBBBBBBBBBBBBB"; @@ -6190,6 +6255,346 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped, Effect.provide(IdAllocator.layer)), ); + it.effect( + "reverts a report's continuation at its report after a Stop dropped another client's prompt", + () => + Effect.gen(function* () { + const kept = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`; + const offers: Array = []; + const reportOffered = yield* Deferred.make(); + const { runtime, thread } = yield* resumed([ + event("session.inbox.enqueued", { + inboxID: "msg_stale", + sessionID: SESSION, + item: { type: "user", payload: { text: "qwe!", files: [] }, delivery: "steer" }, + }), + event("session.execution.started", { sessionID: SESSION }), + event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_stale" }), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.model.selected", { + sessionID: SESSION, + model: { id: "buffered", providerID: "opencode" }, + }), + out("session.switchModel", { sessionID: SESSION, model: "" }), + reply("session.switchModel", null), + ...backgroundLaunch(CHILD), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.inbox.enqueued", { + inboxID: "msg_report", + sessionID: SESSION, + item: { + type: "synthetic", + payload: { + text: CONTINUED_REPORT, + description: "Sleep", + metadata: { + source: "subagent", + childID: CHILD, + agent: "General", + state: "completed", + }, + }, + delivery: "steer", + }, + }), + event("session.execution.started", { sessionID: SESSION }), + event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report" }), + event("session.execution.succeeded", { sessionID: SESSION }), + out("message.list", ""), + reply("message.list", { + data: [ + { id: "msg_report", time: { created: 3 }, text: CONTINUED_REPORT, type: "synthetic" }, + { id: kept, time: { created: 2 }, text: "hi", type: "user" }, + { id: "msg_stale", time: { created: 1 }, text: "qwe!", type: "user" }, + ], + cursor: {}, + }), + out("session.revert.stage", { + sessionID: SESSION, + messageID: "msg_report", + files: false, + }), + replyData("session.revert.stage", { messageID: "msg_report", files: [] }), + out("session.revert.commit", { sessionID: SESSION }), + reply("session.revert.commit", null), + out("message.list", ""), + reply("message.list", { + data: [ + { id: kept, time: { created: 2 }, text: "hi", type: "user" }, + { id: "msg_stale", time: { created: 1 }, text: "qwe!", type: "user" }, + ], + cursor: {}, + }), + ]).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => + Effect.sync(() => void offers.push(request)).pipe( + Effect.andThen(() => + offers.length === 2 ? Deferred.succeed(reportOffered, undefined) : Effect.void, + ), + Effect.asVoid, + ), + take: Effect.never, + }), + ); + const turns: Array = []; + const buffered = yield* Deferred.make(); + const bothEnded = yield* Deferred.make(); + yield* runtime.events.pipe( + Stream.tap((event) => + Effect.gen(function* () { + if ( + event.type === "provider_thread.updated" && + event.providerThread.nativeMetadata?.modelSelection?.model === "opencode/buffered" + ) { + yield* Deferred.succeed(buffered, undefined); + } + if ( + event.type === "provider_turn.updated" && + event.providerTurn.status !== "running" + ) { + turns.push(event.providerTurn); + if (turns.length === 2) yield* Deferred.succeed(bothEnded, undefined); + } + }), + ), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Deferred.await(buffered); + yield* runtime.interruptTurn({ + providerThread: thread, + providerTurnId: yield* providerTurnId, + requestRuntimeRestart: true, + }); + yield* runtime.startTurn(withLineage(thread)); + yield* Deferred.await(reportOffered); + yield* runtime.startTurn(continuationTurn(thread, offers[1]!)); + yield* Deferred.await(bothEnded); + const [first, continuation] = turns; + const snapshot = yield* runtime.rollbackThread({ + providerThread: thread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint:first"), + appRunOrdinal: 1, + providerTurn: first!, + }, + providerThreadTurns: [first!, continuation!], + }); + assert.deepEqual( + snapshot.providerTurns.map((turn) => turn.id), + [first!.id], + ); + }).pipe(Effect.scoped), + ); + + it.effect( + "reverts a report's continuation at its report after a reconnect lost another client's prompt start", + () => + Effect.gen(function* () { + const kept = `msg_t3_turn_${SESSION}:attempt:opencode2-adapter`; + const offered = + yield* Deferred.make(); + const { runtime, thread } = yield* resumed([ + event("session.inbox.enqueued", { + inboxID: "msg_stale", + sessionID: SESSION, + item: { type: "user", payload: { text: "qwe!", files: [] }, delivery: "steer" }, + }), + { type: "runtime_exit", status: "success" } as const, + out("event.subscribe"), + event("session.model.selected", { + sessionID: SESSION, + model: { id: "buffered", providerID: "opencode" }, + }), + out("session.switchModel", { sessionID: SESSION, model: "" }), + reply("session.switchModel", null), + ...backgroundLaunch(CHILD), + event("session.execution.succeeded", { sessionID: SESSION }), + event("session.execution.succeeded", { sessionID: CHILD }), + event("session.inbox.enqueued", { + inboxID: "msg_report", + sessionID: SESSION, + item: { + type: "synthetic", + payload: { + text: CONTINUED_REPORT, + description: "Sleep", + metadata: { + source: "subagent", + childID: CHILD, + agent: "General", + state: "completed", + }, + }, + delivery: "steer", + }, + }), + event("session.execution.started", { sessionID: SESSION }), + event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_report" }), + event("session.execution.succeeded", { sessionID: SESSION }), + out("message.list", ""), + reply("message.list", { + data: [ + { id: "msg_report", time: { created: 3 }, text: CONTINUED_REPORT, type: "synthetic" }, + { id: kept, time: { created: 2 }, text: "hi", type: "user" }, + { id: "msg_stale", time: { created: 1 }, text: "qwe!", type: "user" }, + ], + cursor: {}, + }), + out("session.revert.stage", { + sessionID: SESSION, + messageID: "msg_report", + files: false, + }), + replyData("session.revert.stage", { messageID: "msg_report", files: [] }), + out("session.revert.commit", { sessionID: SESSION }), + reply("session.revert.commit", null), + out("message.list", ""), + reply("message.list", { + data: [ + { id: kept, time: { created: 2 }, text: "hi", type: "user" }, + { id: "msg_stale", time: { created: 1 }, text: "qwe!", type: "user" }, + ], + cursor: {}, + }), + ]).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => Deferred.succeed(offered, request).pipe(Effect.asVoid), + take: Effect.never, + }), + ); + const turns: Array = []; + const reconnected = yield* Deferred.make(); + const bothEnded = yield* Deferred.make(); + yield* runtime.events.pipe( + Stream.tap((event) => + Effect.gen(function* () { + if ( + event.type === "provider_thread.updated" && + event.providerThread.nativeMetadata?.modelSelection?.model === "opencode/buffered" + ) { + yield* Deferred.succeed(reconnected, undefined); + } + if ( + event.type === "provider_turn.updated" && + event.providerTurn.status !== "running" + ) { + turns.push(event.providerTurn); + if (turns.length === 2) yield* Deferred.succeed(bothEnded, undefined); + } + }), + ), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Deferred.await(reconnected); + yield* runtime.startTurn(withLineage(thread)); + yield* runtime.startTurn(continuationTurn(thread, yield* Deferred.await(offered))); + yield* Deferred.await(bothEnded); + const [first, continuation] = turns; + const snapshot = yield* runtime.rollbackThread({ + providerThread: thread, + target: { + type: "provider_turn", + checkpointId: CheckpointId.make("checkpoint:first"), + appRunOrdinal: 1, + providerTurn: first!, + }, + providerThreadTurns: [first!, continuation!], + }); + assert.deepEqual( + snapshot.providerTurns.map((turn) => turn.id), + [first!.id], + ); + }).pipe(Effect.scoped), + ); + + it.effect("shows a second prompt another client sent while its continuation was pending", () => + Effect.gen(function* () { + const offers: Array = []; + const prompt = (inboxID: string, text: string) => + event("session.inbox.enqueued", { + inboxID, + sessionID: SESSION, + item: { type: "user", payload: { text, files: [] }, delivery: "steer" }, + }); + // T3's own prompt can be admitted after a failed submit ended its turn. + const late = `msg_t3_turn_${SESSION}:attempt:late`; + const { runtime, thread } = yield* resumed([ + prompt(late, "mine"), + prompt("msg_external_a", "first?"), + event("session.execution.started", { sessionID: SESSION }), + event("session.inbox.delivered", { sessionID: SESSION, inboxID: late }), + event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_external_a" }), + prompt("msg_external_b", "second?"), + event("session.inbox.delivered", { sessionID: SESSION, inboxID: "msg_external_b" }), + event("session.text.ended", { + sessionID: SESSION, + assistantMessageID: "msg_external_reply", + ordinal: 0, + text: "Both!", + }), + event("session.execution.succeeded", { sessionID: SESSION }), + // Handled only after the wake above has buffered everything before it. + event("session.model.selected", { + sessionID: SESSION, + model: { id: "buffered", providerID: "opencode" }, + }), + ]).pipe( + Effect.provideService(ProviderContinuationRequests.ProviderContinuationRequests, { + offer: (request) => Effect.sync(() => void offers.push(request)), + take: Effect.never, + }), + ); + const collected: Array = []; + const buffered = yield* Deferred.make(); + const ended = yield* Deferred.make(); + yield* runtime.events.pipe( + Stream.tap((event) => + Effect.gen(function* () { + collected.push(event); + if ( + event.type === "provider_thread.updated" && + event.providerThread.nativeMetadata?.modelSelection?.model === "opencode/buffered" + ) { + yield* Deferred.succeed(buffered, undefined); + } + if (event.type === "turn.terminal") yield* Deferred.succeed(ended, undefined); + }), + ), + Stream.runDrain, + Effect.forkScoped, + ); + yield* Deferred.await(buffered); + yield* runtime.startTurn(continuationTurn(thread, offers[0]!)); + yield* Deferred.await(ended); + assert.deepEqual( + collected.flatMap((event) => + event.type === "turn_item.updated" && + (event.turnItem.type === "user_message" || event.turnItem.type === "assistant_message") + ? [`${event.turnItem.type}: ${event.turnItem.text}`] + : [], + ), + ["user_message: first?", "user_message: second?", "assistant_message: Both!"], + ); + assert.deepEqual( + [ + ...new Set( + collected.flatMap((event) => + event.type === "message.updated" + ? [`${event.message.role}: ${event.message.text}`] + : [], + ), + ), + ], + ["user: first?", "user: second?", "assistant: Both!"], + ); + }).pipe(Effect.scoped), + ); + it.effect("shows a question asked while OpenCode wakes for a background reply", () => Effect.gen(function* () { const OTHER = "ses_other00000000000000000000"; diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 080b1c2b1d69c..b4d14717afedb 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -359,6 +359,8 @@ interface ThreadState { >; readonly stoppedChildren: Set; readonly strandedSteers: Set; + /** Prompts other clients queued while no T3 turn ran, shown once delivered; `leads` the next wake if no report preceded it. */ + readonly externalPrompts: Map; mcp: | { readonly name: string; readonly directory: string; readonly credential: string } | undefined; @@ -618,6 +620,7 @@ const turnPromptId = (sessionId: string, attemptId: string) => SessionMessage.ID.make(`msg_t3_turn_${sessionId}:${attemptId}`); const steerPromptId = (sessionId: string, messageId: string) => SessionMessage.ID.make(`msg_t3_steer_${sessionId}:${messageId}`); +const isOwnPrompt = (inboxId: string) => inboxId.startsWith("msg_t3_"); const promptOf = (turn: OrchestrationV2ProviderTurn) => { const nativeId = turn.nativeTurnRef?.nativeId; @@ -836,6 +839,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr reports: new Map(), stoppedChildren: new Set(), strandedSteers: new Set(), + externalPrompts: new Map(), mcp: undefined, instructions: undefined, }); @@ -1118,6 +1122,57 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); }); + // T3's own prompts are sent while their turn is active, so only other clients reach here. + const emitExternalPrompt = Effect.fnUntraced(function* ( + state: ThreadState, + turn: ActiveTurn, + inboxId: string, + text: string, + ) { + const now = yield* DateTime.now; + const base = { + ...itemBase(state, turn, inboxId, "completed", now, now, now), + nodeId: turn.input.rootNodeId, + }; + // History derives the same ID from the message ID, so a later snapshot does not duplicate it. + const messageId = idAllocator.derive.messageFromProviderItem({ + driver, + nativeItemId: inboxId, + }); + yield* emit({ + type: "message.updated", + driver, + message: { + createdBy: "user", + creationSource: "provider", + id: messageId, + threadId: turn.input.threadId, + runId: turn.input.runId, + nodeId: base.nodeId, + role: "user", + text, + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + }, + }); + yield* emit({ + type: "turn_item.updated", + driver, + turnItem: { + ...base, + createdBy: "user", + creationSource: "provider", + type: "user_message", + messageId, + inputIntent: "turn_start", + text, + attachments: [], + }, + }); + }); + // Todo updates share the provider event span. const emitTodo = Effect.fnUntraced(function* ( state: ThreadState, @@ -2757,6 +2812,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const { delivered, stopped } = yield* takeReports(state); if (stopped) return; const route = state.providerThread.appThreadId; + // History begins at whichever OpenCode queued first: a report or another client's prompt. + // A prompt leads only this wake, so one dropped undelivered cannot move a later boundary. + const leading = [...state.externalPrompts].find(([, prompt]) => prompt.leads)?.[0]; + for (const prompt of state.externalPrompts.values()) prompt.leads = false; const wake: Wake = { messageId: route === null @@ -2768,7 +2827,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr detail: delivered.length === 0 ? null : delivered.map((entry) => entry.text).join("\n\n"), dropped: false, after: delivered.at(-1)?.inboxId, - first: delivered[0]?.inboxId, + first: leading ?? delivered[0]?.inboxId, children: new Set(), }; state.wakes.push(wake); @@ -3173,21 +3232,36 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } if (event.type === "session.inbox.cancelled" || event.type === "session.inbox.delivered") { state.reports.delete(event.data.inboxID); + const external = state.externalPrompts.get(event.data.inboxID); + state.externalPrompts.delete(event.data.inboxID); const turn = state.active; if (turn !== undefined && turn.steers.delete(event.data.inboxID)) { turn.settledInbox.add(event.data.inboxID); if (event.type === "session.inbox.cancelled") yield* endIfSettled(state, turn); + } else if ( + event.type === "session.inbox.delivered" && + external !== undefined && + turn !== undefined + ) { + yield* emitExternalPrompt(state, turn, event.data.inboxID, external.text); } return; } + // No T3 turn existed while a wake held these, so its user items came from another client. if ( event.type === "session.inbox.enqueued" && event.data.item.type === "user" && - state.subagent !== undefined && - state.subagent.prompt === undefined && - state.active === undefined + (state.active === undefined || (held && state.subagent === undefined)) ) { - state.subagent.prompt = event.data.item.payload.text; + const text = event.data.item.payload.text; + if (state.subagent !== undefined) state.subagent.prompt ??= text; + // T3's own prompts can be admitted after a failed submit ended their turn. + else if (!isOwnPrompt(event.data.inboxID)) { + state.externalPrompts.set(event.data.inboxID, { + text, + leads: !held && state.reports.size === 0, + }); + } return; } const started = @@ -3482,11 +3556,13 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr currentScope = scope; yield* Scope.close(previous, Exit.void); // A restarted server forgot T3's MCP servers; the next turn adds them again. + // The gap may have started a pending prompt unseen, so none may set a later wake's boundary. for (const state of threads.values()) { state.mcp = undefined; state.goalFresh = false; state.goalRefreshing = false; state.goalRevision += 1; + for (const prompt of state.externalPrompts.values()) prompt.leads = false; } if (supportsNativeGoals()) { yield* Effect.forEach( @@ -4126,7 +4202,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const wake = state.wakes.shift()!; const turn = state.active; if (turn !== undefined && wake.after !== undefined) turn.before = wake.after; - // Its first report is where its history begins, so fork and rollback cut there. + // Fork and rollback cut where its history begins. if (turn !== undefined && wake.first !== undefined) { turn.providerTurn = { ...turn.providerTurn, nativeTurnRef: ref(wake.first, "weak") }; } From 2a8ec9c8e1bb5aa7205166ed0008cf720e7f9449 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:34:48 -0800 Subject: [PATCH 003/128] fix(web): single-digit numbered lists no longer clip in wide fonts (#23573) --- apps/web/src/appearanceFonts.browser.test.ts | 36 ++++++++++++++++++++ apps/web/src/appearanceFonts.ts | 19 +++++++++-- apps/web/src/index.css | 10 +++--- 3 files changed, 56 insertions(+), 9 deletions(-) diff --git a/apps/web/src/appearanceFonts.browser.test.ts b/apps/web/src/appearanceFonts.browser.test.ts index 9bdc5c2ef9864..289e48ecad050 100644 --- a/apps/web/src/appearanceFonts.browser.test.ts +++ b/apps/web/src/appearanceFonts.browser.test.ts @@ -52,4 +52,40 @@ describe("applyAppearanceFontVariables", () => { else root.setAttribute("style", style); } }); + + it("widens the numbered-list gutter only when the interface font's marker would clip", () => { + const root = document.documentElement; + const style = root.getAttribute("style"); + const gutter = (sans: string) => { + applyAppearanceFontVariables(root, { + sans, + code: "", + composer: "", + sizeInterface: 16, + sizePrompt: 14, + sizeCode: 13, + smoothing: true, + separate: false, + }); + const markdown = document.createElement("div"); + markdown.className = "chat-markdown"; + markdown.style.fontSize = "14px"; + const list = document.createElement("ol"); + markdown.append(list); + document.body.append(markdown); + try { + return Number.parseFloat(getComputedStyle(list).paddingInlineStart); + } finally { + markdown.remove(); + } + }; + try { + // `0. ` in a 14px monospace font is about 25px, past the 20px default. + expect(gutter("monospace")).toBeGreaterThan(24); + expect(gutter("sans-serif")).toBe(20); + } finally { + if (style === null) root.removeAttribute("style"); + else root.setAttribute("style", style); + } + }); }); diff --git a/apps/web/src/appearanceFonts.ts b/apps/web/src/appearanceFonts.ts index e7c2867cb279f..19f2d88d3c29d 100644 --- a/apps/web/src/appearanceFonts.ts +++ b/apps/web/src/appearanceFonts.ts @@ -88,6 +88,16 @@ export function applyAppearanceFontVariables( } } + const markerWidth = probeWidth( + appearanceFontStack(preferences.sans, DEFAULT_SANS_FONT_STACK), + LIST_MARKER_PROBE_TEXT, + ); + if (markerWidth === null) { + root.style.removeProperty("--list-marker-sans"); + } else { + root.style.setProperty("--list-marker-sans", `${(markerWidth / PROBE_FONT_SIZE).toFixed(3)}em`); + } + root.style.fontSize = `${clampInterfaceFontSize(preferences.sizeInterface)}px`; root.style.setProperty( "--font-size-prompt", @@ -127,15 +137,18 @@ function clampCodeFontSize(value: number): number { } const FONT_PROBE_TEXT = "mmmmmmmmMMWli1O0@# fjord"; +// The widest single-digit `ol` marker; CSS can't measure it to size the list gutter. +const LIST_MARKER_PROBE_TEXT = "0. "; +const PROBE_FONT_SIZE = 16; let fontProbeContext: CanvasRenderingContext2D | null | undefined; -function probeWidth(fontList: string): number | null { +function probeWidth(fontList: string, text = FONT_PROBE_TEXT): number | null { if (fontProbeContext === undefined) { fontProbeContext = document.createElement("canvas").getContext("2d"); } if (fontProbeContext === null) return null; - fontProbeContext.font = `16px ${fontList}`; - return fontProbeContext.measureText(FONT_PROBE_TEXT).width; + fontProbeContext.font = `${PROBE_FONT_SIZE}px ${fontList}`; + return fontProbeContext.measureText(text).width; } /** Probes canvas metrics because document.fonts.check() accepts uninstalled families. */ diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 21c3816f8d34b..654ef108e8e75 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1933,13 +1933,11 @@ code { list-style-type: disc; } -/* --list-gutter defaults to the same 1.25rem as .chat-markdown ul, but - ChatMarkdown's `ol` renderer widens it (via inline style) for lists whose - widest marker has multiple characters so it isn't clipped by list-style-position: - outside painting the marker past the padding box. Reset it here too so a - nested ol without its own widened marker doesn't inherit the outer one. */ +/* Outside markers paint past the padding box, so the gutter must fit `0. `, + measured per font in appearanceFonts. ChatMarkdown widens it inline for + multi-digit markers; setting it here stops a nested ol inheriting that. */ :is(.chat-markdown, .composer-tiptap) ol { - --list-gutter: 1.25rem; + --list-gutter: max(1.25rem, var(--list-marker-sans, 0px)); padding-inline-start: var(--list-gutter, 1.25rem); list-style-type: decimal; } From 93c10239b415e35a887d69f519b83754b128767e Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Wed, 11 Nov 2026 15:34:59 -0800 Subject: [PATCH 004/128] feat(cli): t3 service runs on Windows, so Windows hosts update remotely (#34524) Co-authored-by: Kayzel Co-authored-by: Claude Fable 5.2 --- apps/server/src/bin.ts | 11 +- apps/server/src/cli/server.ts | 7 +- apps/server/src/cli/service.ts | 2 +- apps/server/src/cli/serviceLauncher.ts | 23 +- apps/server/src/cli/update.ts | 2 +- apps/server/src/cloud/bootService.test.ts | 212 +++++++++- apps/server/src/cloud/bootService.ts | 397 ++++++++++++++++-- .../src/cloud/serviceLauncherClient.test.ts | 18 + .../server/src/cloud/serviceLauncherClient.ts | 17 + apps/server/src/cloud/serviceProtocol.ts | 30 +- apps/server/src/serviceLauncher.test.ts | 192 ++++++++- apps/server/src/serviceLauncher.ts | 259 ++++++++++-- docs/internals/server-updates.md | 13 +- docs/user/background-service.md | 17 +- docs/user/install.md | 20 +- docs/user/remote-access.md | 13 +- 16 files changed, 1110 insertions(+), 123 deletions(-) diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index b69fa6e4bb299..1a0589ddc6029 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -38,10 +38,13 @@ if ( }) ) { // The launcher owns shutdown until its child exits, so it bypasses the Effect CLI runtime. - // The service unit passes no arguments; flags and help go through the full CLI. - if (process.argv[2] === "__service-launcher" && process.argv.length === 3) { - const { runServiceLauncherCli } = await import("./cli/serviceLauncher.ts"); - await runServiceLauncherCli(); + // A service unit passes nothing, or on Windows the launcher's own flags; help and anything + // else go through the full CLI. + const launcher = + process.argv[2] === "__service-launcher" ? await import("./cli/serviceLauncher.ts") : undefined; + const launcherOptions = launcher?.parseServiceLauncherArgs(process.argv.slice(3)); + if (launcher !== undefined && launcherOptions !== undefined) { + await launcher.runServiceLauncherCli(launcherOptions); } else { const { runCliCommand } = await loadCliMain(); await runCliCommand(); diff --git a/apps/server/src/cli/server.ts b/apps/server/src/cli/server.ts index 3088f6d82974e..a360d749b0c82 100644 --- a/apps/server/src/cli/server.ts +++ b/apps/server/src/cli/server.ts @@ -6,6 +6,7 @@ import * as Schema from "effect/Schema"; import { Command, GlobalFlag } from "effect/cli"; import * as CliError from "effect/cli/CliError"; +import { awaitServiceLauncherStop } from "../cloud/serviceLauncherClient.ts"; import * as ServerConfig from "../config.ts"; import { awaitLauncherLoss } from "../launcherWatch.ts"; import * as DatabaseMaintenance from "../persistence/DatabaseMaintenance.ts"; @@ -35,8 +36,10 @@ const runServerCommand = Effect.fn("server.runServerCommand")(function* ( const logLevel = yield* GlobalFlag.LogLevel; const selectAutomaticPort = yield* AutomaticPort.make.pipe(Effect.provide(ProcessRunner.layer)); const config = yield* resolveServerConfig(flags, logLevel, { ...options, selectAutomaticPort }); - const run = runServer.pipe( - Effect.provideService(ServerConfig.ServerConfig, config), + const run = Effect.raceFirst( + runServer.pipe(Effect.provideService(ServerConfig.ServerConfig, config)), + awaitServiceLauncherStop().pipe(Effect.andThen(Effect.interrupt)), + ).pipe( // Settings' Reclaim stops the server; repair once the database is closed, before the restart. Effect.ensuring( DatabaseMaintenance.runRequestedReclaim(config.dbPath).pipe( diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts index ce43154116b8e..dedc095f62ffd 100644 --- a/apps/server/src/cli/service.ts +++ b/apps/server/src/cli/service.ts @@ -154,7 +154,7 @@ function formatServiceStatus( protection?: ServiceProtection.ServiceProtectionState, ): string { if (!status.supported) { - return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd"; + return "T3 Code service\n Status: unavailable on this machine\n Supported on: Linux with systemd, macOS with launchd, Windows with Task Scheduler"; } if (!status.installed) { return "T3 Code service\n Status: not installed\n Next: Run `t3 service install`."; diff --git a/apps/server/src/cli/serviceLauncher.ts b/apps/server/src/cli/serviceLauncher.ts index 252659fd25489..fc5882cbf935a 100644 --- a/apps/server/src/cli/serviceLauncher.ts +++ b/apps/server/src/cli/serviceLauncher.ts @@ -1,8 +1,25 @@ -import { main as runServiceLauncher } from "../serviceLauncher.ts"; +import { type LauncherOptions, main as runServiceLauncher } from "../serviceLauncher.ts"; -export async function runServiceLauncherCli(): Promise { +/** The flags a Windows task passes, parsed here so the launcher starts without the full CLI. */ +export function parseServiceLauncherArgs(args: ReadonlyArray): LauncherOptions | undefined { + let baseDir: string | undefined; + let logFile: string | undefined; + let serviceUnit: string | undefined; + for (let index = 0; index < args.length; index += 2) { + const flag = args[index]; + const value = args[index + 1]; + if (value === undefined) return undefined; + if (flag === "--base-dir") baseDir = value; + else if (flag === "--log-file") logFile = value; + else if (flag === "--service-unit") serviceUnit = value; + else return undefined; + } + return { baseDir, logFile, serviceUnit }; +} + +export async function runServiceLauncherCli(options?: LauncherOptions): Promise { try { - await runServiceLauncher(); + await runServiceLauncher(options); } catch (cause) { const message = cause instanceof Error ? cause.message : String(cause); process.stderr.write(`[service-launcher] ${message}\n`); diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index 99bf380f1c0dd..53ff536e6d112 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -596,7 +596,7 @@ export const runUpdate = Effect.fn("cli.update.run")(function* (input: { } if (servicePlan?.handedOff === true) { yield* Console.log( - ` Background service switching to ${targetVersion} from a separate systemd unit, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`, + ` Background service switching to ${targetVersion} outside this session, since this session runs inside it and disconnects when it restarts. Result: ${servicePlan.logPath}`, ); } else if (servicePlan !== undefined && restartService) { yield* Console.log(` Background service restarted on ${targetVersion}`); diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 8b0fc8f6fbb1a..0b60b28e557ad 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -1,5 +1,6 @@ // @effect-diagnostics-next-line nodeBuiltinImport:off -- Cross-process launcher contention uses real filesystem leases and IPC barriers. import * as NodeChildProcess from "node:child_process"; +import * as NodeSqlite from "node:sqlite"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -17,10 +18,13 @@ import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { vi } from "vite-plus/test"; import * as ProcessRunner from "../processRunner.ts"; +import { serviceLauncherLockPath } from "../serviceLauncher.ts"; import * as BootService from "./bootService.ts"; import { pinnedRuntimePaths } from "./pinnedRuntime.ts"; import { + disabledServiceTask, parseServiceState, + serviceTaskIsDisabled, SERVICE_ENV_FILE, SERVICE_LAUNCHER_PROTOCOL, SERVICE_RESTART_PENDING_FILE, @@ -45,7 +49,13 @@ vi.mock("node:fs", async (importOriginal) => { }; }); -it("reads the served T3 home back out of a rendered unit or plist", () => { +const windowsTaskOptions = { + userId: "PC\\theo", + homeDir: "C:\\Users\\theo", + conhostPath: "C:\\Windows\\System32\\conhost.exe", +}; + +it("reads the served T3 home back out of a rendered unit, plist, or task", () => { const plan = (baseDir: string) => ({ program: [`${baseDir}/runtime/versions/1.2.3/t3`, "__service-launcher"], baseDir, @@ -69,6 +79,11 @@ it("reads the served T3 home back out of a rendered unit or plist", () => { }), ), ).toBe("/Users/theo/a&b"); + expect( + BootService.bootServiceBaseDirOf( + BootService.renderBootServiceTask(plan("C:\\Users\\theo\\T3 a&b\\"), windowsTaskOptions), + ), + ).toBe("C:\\Users\\theo\\T3 a&b\\"); expect(BootService.bootServiceBaseDirOf("[Service]\nExecStart=/x\n")).toBeUndefined(); }); @@ -99,6 +114,12 @@ it.each([ (plan: BootService.BootServicePlan) => BootService.renderBootServicePlist(plan, { homeDir: "/Users/theo", environmentPath: "" }), ], + [ + "a task", + "C:\\Users\\theo\\T3 a&b ", + (plan: BootService.BootServicePlan) => + BootService.renderBootServiceTask(plan, windowsTaskOptions), + ], ] as const)("reads the launcher back out of %s", (_, baseDir, render) => { const program = `${baseDir}/runtime/versions/1.2.3/t3`; expect( @@ -148,6 +169,10 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( lingerStartsManager: boolean; enabled: boolean; active: boolean; + /** A Windows launcher: it holds its lock until its task ends. */ + launcher?: { readonly close: () => void }; + /** Task Scheduler's own copy of the task. */ + task?: { xml: string; enabled: boolean }; } = { failCommand: undefined, linger: "yes", @@ -171,6 +196,19 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( control.managerReachable ||= control.lingerStartsManager; } if (!failed && command === "systemctl --user enable t3code.service") control.enabled = true; + const taskMissing = + input.command === "schtasks" && input.args[0] !== "/Create" && control.task === undefined; + if (input.command === "schtasks" && !failed) { + if (input.args[0] === "/Create") { + const xml = yield* fs.readFileString(input.args[2] ?? ""); + control.task = { xml, enabled: !serviceTaskIsDisabled(xml) }; + } + if (control.task !== undefined && input.args[0] === "/Change") { + control.task.enabled = input.args.includes("/ENABLE"); + } + if (input.args[0] === "/Delete") delete control.task; + if (input.args[0] === "/End") control.launcher?.close(); + } if (!failed && command === "systemctl --user restart t3code.service") control.active = true; // The manager loads units only from its own unit directory. const unitOutsideManager = @@ -199,28 +237,35 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( ], }) : input.args[0] === "--version" - ? `t3 v${/versions\/([^/]+)\//.exec(input.command)?.[1] ?? "1.2.3"}\n` - : input.command === "loginctl" && input.args[0] === "show-user" - ? `${control.linger ?? ""}\n` - : input.args[1] === "is-enabled" - ? control.enabled - ? "enabled\n" - : "disabled\n" - : "", + ? `t3 v${/versions[\\/]([^\\/]+)[\\/]/.exec(input.command)?.[1] ?? "1.2.3"}\n` + : input.command === "schtasks" && input.args.includes("/XML") + ? control.task?.enabled === false + ? disabledServiceTask(control.task.xml) + : (control.task?.xml ?? "") + : input.command === "loginctl" && input.args[0] === "show-user" + ? `${control.linger ?? ""}\n` + : input.args[1] === "is-enabled" + ? control.enabled + ? "enabled\n" + : "disabled\n" + : "", stderr: "", code: ChildProcessSpawner.ExitCode( - failed || - unitOutsideManager || - ((command === "systemctl --user show-environment" || input.command === "busctl") && - (!control.managerReachable || - (control.busNeedsRuntimeDir && input.env?.XDG_RUNTIME_DIR === undefined))) || - (input.command === "loginctl" && - input.args[0] === "show-user" && - control.linger === undefined) || - (input.args[1] === "is-active" && !control.active) || - (input.args[1] === "is-enabled" && !control.enabled) - ? 1 - : 0, + taskMissing && input.args.includes("/HRESULT") + ? 0x80070002 + : failed || + taskMissing || + unitOutsideManager || + ((command === "systemctl --user show-environment" || input.command === "busctl") && + (!control.managerReachable || + (control.busNeedsRuntimeDir && input.env?.XDG_RUNTIME_DIR === undefined))) || + (input.command === "loginctl" && + input.args[0] === "show-user" && + control.linger === undefined) || + (input.args[1] === "is-active" && !control.active) || + (input.args[1] === "is-enabled" && !control.enabled) + ? 1 + : 0, ), timedOut: false, stdoutTruncated: false, @@ -265,10 +310,19 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( env: { HOME: home, ...(xdgConfigHome === undefined ? {} : { XDG_CONFIG_HOME: xdgConfigHome }), + USERPROFILE: home, + LOCALAPPDATA: path.join(home, "AppData", "Local"), + USERDOMAIN: "PC", + USERNAME: "theo", ...(environmentPath === undefined || environmentPath === "" ? {} : { PATH: environmentPath }), - ...(insideService ? { T3_BOOT_SERVICE_UNIT: "t3code.service" } : {}), + ...(insideService + ? { + T3_BOOT_SERVICE_UNIT: + platform === "win32" ? "t3code-task.xml" : "t3code.service", + } + : {}), ...(underSudo ? { SUDO_USER: "julius" } : {}), }, }), @@ -1224,6 +1278,120 @@ process.disconnect(); }), ); + it.effect("installs, reports a stopped launcher, and uninstalls on Windows", () => + Effect.gen(function* () { + const { service, fs, statePath, commands, control, runtime } = yield* makeHarness("win32"); + const path = yield* Path.Path; + const plan = yield* service.install(); + const task = yield* fs.readFileString(plan.unitPath); + + expect(plan.unitPath).toBe( + path.join(path.dirname(plan.baseDir), "AppData", "Local", "t3code", "t3code-task.xml"), + ); + expect(BootService.bootServiceProgramOf(task)).toBe(runtime.entryPath); + expect(BootService.bootServiceBaseDirOf(task)).toBe(plan.baseDir); + expect(task).toContain("PC\\theo"); + expect(task).toContain("IgnoreNew"); + expect(parseServiceState(yield* fs.readFileString(statePath))).toEqual({ + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.2.3", + }); + expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual([ + `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + "schtasks /Run /TN t3code-PC-theo", + ]); + // No launcher holds the lock here. + expect(yield* service.status).toMatchObject({ + installed: true, + current: false, + problems: ["service-stopped"], + }); + + // A task that Task Scheduler refuses to delete stays installed, so a retry finds it. + control.failCommand = "schtasks /Delete /TN t3code-PC-theo /F"; + expect((yield* service.uninstall.pipe(Effect.flip))._tag).toBe("BootServiceCommandError"); + expect((yield* service.status).installed).toBe(true); + control.failCommand = undefined; + + commands.length = 0; + expect(yield* service.uninstall).toBe(true); + expect(commands).toEqual([ + "schtasks /Change /TN t3code-PC-theo /DISABLE", + "schtasks /End /TN t3code-PC-theo", + "schtasks /Delete /TN t3code-PC-theo /F", + ]); + expect(control.task).toBeUndefined(); + expect((yield* service.status).installed).toBe(false); + + // One removed by hand leaves nothing to disable or delete. + yield* service.install(); + delete control.task; + expect(yield* service.uninstall).toBe(true); + }), + ); + + it.effect("stops a Windows launcher by ending its task, and restarts one left disabled", () => + Effect.gen(function* () { + const { service, commands, control, makeService } = yield* makeHarness("win32"); + const plan = yield* service.install(); + const launcher = new NodeSqlite.DatabaseSync(serviceLauncherLockPath(plan.baseDir)); + launcher.exec("BEGIN EXCLUSIVE"); + control.launcher = launcher; + + // Task Scheduler runs its own copy of the task, so a deferred restart registers the new one. + const newer = yield* makeService(undefined, "1.2.4"); + yield* newer.install({ start: false }); + const newerRuntime = pinnedRuntimePaths(yield* Path.Path, plan.baseDir, "1.2.4", "win32"); + expect(BootService.bootServiceProgramOf(control.task?.xml ?? "")).toBe( + newerRuntime.entryPath, + ); + expect(control.task?.enabled).toBe(true); + + // An interrupted stop disables the task and leaves its launcher running. + yield* service.install({ start: false, allowDowngrade: true }); + control.task = { xml: control.task?.xml ?? "", enabled: false }; + yield* newer.install({ start: false }); + expect(control.task).toMatchObject({ enabled: false }); + expect(BootService.bootServiceProgramOf(control.task.xml)).toBe(newerRuntime.entryPath); + expect((yield* service.status).problems).toEqual(["service-disabled", "restart-pending"]); + + commands.length = 0; + yield* service.withStopped(Effect.sync(() => commands.push("repair"))); + expect(commands.filter((command) => !command.includes("/Query"))).toEqual([ + "schtasks /Change /TN t3code-PC-theo /DISABLE", + "schtasks /End /TN t3code-PC-theo", + "repair", + "schtasks /Change /TN t3code-PC-theo /ENABLE", + "schtasks /Run /TN t3code-PC-theo", + ]); + }), + ); + + it.effect("hands an in-service install and restart to Task Scheduler on Windows", () => + Effect.gen(function* () { + const { service, fs, statePath, commands, makeService } = yield* makeHarness("win32"); + const plan = yield* service.install(); + const inside = yield* makeService(undefined, "1.2.4", undefined, true); + const handoff = [ + `schtasks /Create /XML ${plan.unitPath} /TN t3code-PC-theo /F`, + "schtasks /End /TN t3code-PC-theo", + "schtasks /Run /TN t3code-PC-theo", + ]; + commands.length = 0; + + expect(yield* inside.install()).toMatchObject({ handedOff: true, logPath: plan.logPath }); + expect(commands.filter((command) => command.startsWith("schtasks "))).toEqual(handoff); + expect(parseServiceState(yield* fs.readFileString(statePath))?.activeVersion).toBe("1.2.4"); + expect( + yield* fs.readFileString(`${plan.baseDir}/runtime/${SERVICE_RESTART_PENDING_FILE}`), + ).toBe("1.2.4\n"); + + commands.length = 0; + expect(yield* inside.restart).toBe("queued"); + expect(commands).toEqual(handoff); + }), + ); + // regression: #8173 keep provider CLIs available in the macOS service it.effect("reconstructs a launch agent search path when the installer has no PATH", () => Effect.gen(function* () { diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index dd5a1f060bae6..bc7717d457315 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -18,6 +18,12 @@ import { CLI_RELEASE_BASE_URL_ENV } from "@t3tools/shared/cliRelease"; import * as ProcessRunner from "../processRunner.ts"; import { acquireServiceSelectionLock } from "./serviceSelectionLock.ts"; +import { + serviceLauncherIsRunning, + serviceLauncherLockPath, + serviceTaskName, + waitForServiceLauncherExit, +} from "../serviceLauncher.ts"; import { ensurePinnedRuntimeInstalled, launcherOwnsVersionsDir, @@ -32,6 +38,8 @@ import { SERVICE_STATE_FILE, SERVICE_UNIT_ENV, compareExactServiceVersions, + disabledServiceTask, + serviceTaskIsDisabled, serviceUnitBaseDirOf as bootServiceBaseDirOf, parseServiceState, serviceStateActiveVersion, @@ -51,6 +59,10 @@ export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`; export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service"; export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`; export const BOOT_SERVICE_LOG_FILE = "boot-service.log"; +/** `schtasks /Query /HRESULT` exits with this when the task is not registered. */ +const WINDOWS_TASK_NOT_FOUND = 0x80070002; +/** Task Scheduler keeps its own copy; this one lets status and repair read the task back. */ +const BOOT_SERVICE_TASK_FILE = `${BOOT_SERVICE_NAME}-task.xml`; /** systemd expands `%` specifiers, including in unquoted append-log paths. */ function escapeSystemdSpecifiers(value: string): string { @@ -64,6 +76,9 @@ function quoteSystemdValue(value: string): string { : escaped; } +/** Windows paths cannot contain `"`; only backslashes before the closing quote need doubling. */ +const quoteWindowsArgument = (value: string) => `"${value.replace(/(\\+)$/, "$1$1")}"`; + export interface BootServicePlan { readonly program: ReadonlyArray; readonly baseDir: string; @@ -169,20 +184,87 @@ export function renderBootServicePlist( ].join("\n"); } -export interface BootServiceStep { +/** + * Task Scheduler can neither set variables nor redirect output, so the launcher takes them as + * flags. A console program started by a task opens a window unless a headless console hosts it. + * No XML declaration: schtasks rejects `encoding="UTF-8"` but reads undeclared XML as UTF-8. + */ +export function renderBootServiceTask( + plan: BootServicePlan, + options: { readonly userId: string; readonly homeDir: string; readonly conhostPath: string }, +): string { + const launcherArguments = [ + ...plan.program, + "--base-dir", + plan.baseDir, + "--log-file", + plan.logPath, + "--service-unit", + BOOT_SERVICE_TASK_FILE, + ] + .map(quoteWindowsArgument) + .join(" "); + // conhost reports exit code 0 whatever the launcher returns, so restart-on-failure never + // fires. A repeating trigger with IgnoreNew starts the task again within a minute instead. + // Priority 5 is normal; the default 7 runs below it. + return [ + ``, + ` `, + ` T3 Code server`, + ` `, + ` `, + ` `, + ` ${escapeXmlText(options.userId)}`, + ` `, + ` `, + ` 2000-01-01T00:00:00`, + ` `, + ` PT1M`, + ` `, + ` `, + ` `, + ` `, + ` `, + ` ${escapeXmlText(options.userId)}`, + ` InteractiveToken`, + ` LeastPrivilege`, + ` `, + ` `, + ` `, + ` IgnoreNew`, + ` false`, + ` false`, + ` PT0S`, + ` 5`, + ` `, + ` `, + ` `, + ` ${escapeXmlText(options.conhostPath)}`, + ` --headless ${escapeXmlText(launcherArguments)}`, + ` ${escapeXmlText(options.homeDir)}`, + ` `, + ` `, + ``, + ``, + ].join("\n"); +} + +export type BootServiceStep = { readonly step: string; - readonly command: string; - readonly args: ReadonlyArray; /** Non-zero exit is logged and ignored. */ readonly optional?: boolean; readonly timeout?: Duration.Input; -} +} & ( + | { readonly command: string; readonly args: ReadonlyArray } + /** A step no command can do, such as waiting for the Windows launcher to exit. */ + | { readonly run: Effect.Effect } +); /** Must exceed systemd TimeoutStopSec and launchd ExitTimeOut (both 90s) to avoid shutdown races. */ const STOP_STEP_TIMEOUT = Duration.seconds(120); export interface BootServiceManager { - readonly kind: "systemd" | "launchd"; + readonly kind: "systemd" | "launchd" | "schtasks"; readonly unitPath: string; readonly render: (plan: BootServicePlan) => string; readonly stop: ReadonlyArray; @@ -201,6 +283,9 @@ const defaultSystemdUnitDir = (path: Path.Path, homeDir: string, xdgConfigHome: "user", ); +const scheduledTaskPath = (path: Path.Path, localAppData: string) => + path.join(localAppData, "t3code", BOOT_SERVICE_TASK_FILE); + const launchdPlistPath = (path: Path.Path, homeDir: string) => path.join(homeDir, "Library", "LaunchAgents", BOOT_SERVICE_PLIST_FILE); @@ -337,6 +422,82 @@ function launchdManager(input: { }; } +export interface WindowsSession { + readonly localAppData: string; + /** `DOMAIN\user`, the account whose logon starts the task. */ + readonly userId: string; + readonly taskName: string; + readonly systemRoot: string; +} + +/** The steps one `schtasks` command cannot do. */ +interface WindowsTaskSteps { + /** Disables the task, or the repeating trigger restarts a service that should stay stopped. */ + readonly disable: Effect.Effect; + /** Ends the task and waits for its launcher to exit; Task Scheduler does not wait. */ + readonly stopLauncher: Effect.Effect; + readonly remove: Effect.Effect; +} + +function schtasksManager(input: { + readonly path: Path.Path; + readonly homeDir: string; + readonly session: WindowsSession; + readonly steps: WindowsTaskSteps; +}): BootServiceManager { + const unitPath = scheduledTaskPath(input.path, input.session.localAppData); + const task = ["/TN", input.session.taskName]; + const register = { + step: "registering the scheduled task", + command: "schtasks", + args: ["/Create", "/XML", unitPath, ...task, "/F"], + }; + const run = { step: "starting the service", command: "schtasks", args: ["/Run", ...task] }; + const stop: ReadonlyArray = [ + { step: "disabling the scheduled task", run: input.steps.disable }, + { + step: "stopping the installed service", + run: input.steps.stopLauncher, + timeout: STOP_STEP_TIMEOUT, + }, + ]; + return { + kind: "schtasks", + unitPath, + render: (plan) => + renderBootServiceTask(plan, { + userId: input.session.userId, + homeDir: input.homeDir, + conhostPath: input.path.join(input.session.systemRoot, "System32", "conhost.exe"), + }), + stop, + // Registration also enables the task. + activate: [register, run], + restart: [ + { + step: "enabling the scheduled task", + command: "schtasks", + args: ["/Change", ...task, "/ENABLE"], + }, + { ...run, step: "restarting the service after a failed update" }, + ], + // Ending the task kills only its console host; the launcher sees the console close and + // stops gracefully while the replacement waits for its lock. + handoff: [ + register, + { + step: "ending the scheduled task", + command: "schtasks", + args: ["/End", ...task], + optional: true, + }, + { ...run, step: "restarting the service" }, + ], + deactivate: [...stop, { step: "removing the scheduled task", run: input.steps.remove }], + finalize: [], + }; +} + function selectBootServiceManager(input: { readonly platform: NodeJS.Platform; readonly homeDir: string; @@ -345,10 +506,14 @@ function selectBootServiceManager(input: { readonly uid: number | undefined; readonly path: Path.Path; readonly environmentPath: string; + readonly windows?: { readonly session: WindowsSession; readonly steps: WindowsTaskSteps }; }): BootServiceManager | undefined { if (input.homeDir === "") { return undefined; } + if (input.platform === "win32" && input.windows !== undefined) { + return schtasksManager({ path: input.path, homeDir: input.homeDir, ...input.windows }); + } if (input.platform === "linux") { return systemdManager({ path: input.path, @@ -409,6 +574,10 @@ export const bootServiceUnitPath = Effect.fn("cloud.boot_service.unit_path")(fun const homeDir = yield* HostProcess.HomeDirectory; if (homeDir === "") return undefined; if (platform === "darwin") return launchdPlistPath(path, homeDir); + if (platform === "win32") { + const localAppData = (yield* HostProcess.Environment).LOCALAPPDATA ?? ""; + return localAppData === "" ? undefined : scheduledTaskPath(path, localAppData); + } if (platform !== "linux") return undefined; const unitDir = (yield* readSystemdUnitDirectory(yield* ProcessRunner.ProcessRunner, path)) ?? @@ -421,7 +590,7 @@ export class BootServiceUnsupportedError extends Schema.TaggedError + platform === "win32" ? Config.String(name).pipe(Config.withDefault("")) : Config.succeed(""); + const windowsSession: WindowsSession = { + localAppData: yield* windowsVariable("LOCALAPPDATA"), + userId: `${yield* windowsVariable("USERDOMAIN")}\\${yield* windowsVariable("USERNAME")}`, + taskName: serviceTaskName( + yield* windowsVariable("USERDOMAIN"), + yield* windowsVariable("USERNAME"), + ), + systemRoot: (yield* windowsVariable("SystemRoot")) || "C:\\Windows", + }; + // The unit is per user, so the launcher to stop is the one serving the installed unit's home. + const launcherLockPath = (unit: Option.Option) => + serviceLauncherLockPath( + Option.getOrUndefined(Option.flatMapNullishOr(unit, bootServiceBaseDirOf)) ?? input.baseDir, + ); + const windowsTask = ["/TN", windowsSession.taskName]; + /** Runs a command that changes the task; a task that is not registered has nothing to change. */ + const changeWindowsTask = Effect.fn("cloud.boot_service.change_windows_task")(function* ( + step: string, + verb: string, + flag: string, + ) { + const toError = (cause: unknown) => new BootServiceCommandError({ step, cause }); + const changed = yield* runner + .run({ command: "schtasks", args: [verb, ...windowsTask, flag] }) + .pipe(Effect.mapError(toError)); + if (changed.code === 0) return; + const queried = yield* runner + .run({ + command: "schtasks", + args: ["/Query", ...windowsTask, "/HRESULT"], + timeout: Duration.seconds(5), + }) + .pipe(Effect.mapError(toError)); + if (Number(queried.code) >>> 0 === WINDOWS_TASK_NOT_FOUND) return; + return yield* new BootServiceCommandError({ + step, + exitCode: Number(changed.code), + stdoutLength: changed.stdout.length, + stderrLength: changed.stderr.length, + }); + }); + // Under the unit lease: a launcher registering its task again reads whether it is disabled + // first, and must not do that around this. + const disableWindowsTask = Effect.suspend(() => + Effect.acquireUseRelease( + Effect.tryPromise({ + try: () => acquireServiceSelectionLock(unitPath), + catch: (cause) => + new BootServiceCommandError({ step: "disabling the scheduled task", cause }), + }), + () => changeWindowsTask("disabling the scheduled task", "/Change", "/DISABLE"), + (release) => Effect.sync(release), + ), + ); + /** + * Task Scheduler runs its own copy of the task, so an install that starts nothing still + * registers the new one. A task that was disabled or absent stays stopped. + */ + const refreshWindowsTask = Effect.fn("cloud.boot_service.refresh_windows_task")(function* ( + unit: string, + ) { + const register = (xmlPath: string) => + runStep("registering the scheduled task", "schtasks", [ + "/Create", + "/XML", + xmlPath, + ...windowsTask, + "/F", + ]); + const registered = yield* probe("schtasks", ["/Query", ...windowsTask, "/XML"]); + if ( + Option.isSome(registered) && + registered.value.code === 0 && + !serviceTaskIsDisabled(registered.value.stdout) + ) { + return yield* register(unitPath); + } + return yield* Effect.scoped( + Effect.gen(function* () { + const disabledPath = yield* fs.makeTempFileScoped({ + directory: path.dirname(unitPath), + prefix: ".service-task-", + }); + yield* fs.writeFileString(disabledPath, disabledServiceTask(unit)); + yield* register(disabledPath); + }), + ); + }); + // Ending the task closes the launcher's console, which the launcher takes as its SIGTERM. + // Task Scheduler then reports the task stopped at once, so the lock says when it really is. + const stopWindowsLauncher = Effect.gen(function* () { + const unit = yield* fs.readFileString(unitPath).pipe(Effect.option); + yield* runner.run({ command: "schtasks", args: ["/End", ...windowsTask] }).pipe(Effect.ignore); + yield* Effect.tryPromise({ + try: (signal) => waitForServiceLauncherExit(launcherLockPath(unit), signal), + catch: (cause) => + new BootServiceCommandError({ step: "stopping the installed service", cause }), + }); + }); const logPath = path.join(input.logsDir, BOOT_SERVICE_LOG_FILE); const resolveTarget = (systemdUnitDir: string | undefined) => { const manager = selectBootServiceManager({ @@ -664,6 +936,18 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { uid, path, environmentPath, + ...(windowsSession.localAppData === "" || windowsSession.userId === "\\" + ? {} + : { + windows: { + session: windowsSession, + steps: { + disable: disableWindowsTask, + stopLauncher: stopWindowsLauncher, + remove: changeWindowsTask("removing the scheduled task", "/Delete", "/F"), + }, + }, + }), }); const unitPath = manager?.unitPath ?? ""; const plan: BootServicePlan = { @@ -745,12 +1029,21 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { Effect.forEach( steps, (entry) => { - const run = runStep( - entry.step, - entry.command, - entry.args, - entry.timeout === undefined ? undefined : { timeout: entry.timeout }, - ); + const run = + "run" in entry + ? entry.run.pipe( + Effect.timeoutOrElse({ + duration: entry.timeout ?? Duration.seconds(60), + orElse: () => Effect.fail(new BootServiceCommandError({ step: entry.step })), + }), + Effect.tapError(logFailure), + ) + : runStep( + entry.step, + entry.command, + entry.args, + entry.timeout === undefined ? undefined : { timeout: entry.timeout }, + ); return entry.optional === true ? run.pipe(Effect.ignore) : run.pipe(Effect.asVoid); }, { discard: true }, @@ -844,6 +1137,26 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { (release) => Effect.sync(release), ); + // Running means the launcher holds its lock: a task can stay running after the + // launcher exits, while agents it left behind hold the console host open. + const readSchtasksProblems = Effect.fn("cloud.boot_service.read_schtasks_problems")(function* ( + unit: Option.Option, + ) { + const [task, running] = yield* Effect.all( + [ + probe("schtasks", ["/Query", "/TN", windowsSession.taskName, "/XML"]), + Effect.promise(() => serviceLauncherIsRunning(launcherLockPath(unit))), + ], + { concurrency: "unbounded" }, + ); + const problems: BootServiceProblem[] = []; + if (Option.isNone(task) || task.value.code !== 0 || serviceTaskIsDisabled(task.value.stdout)) { + problems.push("service-disabled"); + } + if (!running) problems.push("service-stopped"); + return problems; + }); + const install = Effect.fn("cloud.boot_service.install")(function* (options?: { readonly allowDowngrade?: boolean; readonly start?: boolean; @@ -959,7 +1272,10 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ]); return { ...plan, handedOff: true }; } - if (installed && start) { + // Task Scheduler restarts the task itself, so the files are written as for a deferred + // restart while this launcher keeps running, then the restart is handed to the manager. + const handOff = installed && start && runningInsideService && manager.kind === "schtasks"; + if (installed && start && !handOff) { yield* runSteps(manager.stop); } @@ -975,11 +1291,17 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { if (Option.isSome(previousStateText)) { const installedVersion = serviceStateActiveVersion(previousStateText.value); if (serviceStateHasPendingUpdate(previousStateText.value)) { - const quote = (word: string) => `'${word.replaceAll("'", "'\\''")}'`; + const windows = platform === "win32"; + const quote = (word: string) => `'${word.replaceAll("'", windows ? "''" : "'\\''")}'`; + const launcher = (version: string) => + quote(pinnedRuntimePaths(path, input.baseDir, version, platform).entryPath); return yield* new BootServiceUpdatePendingError( !currentlyInstalled && installedVersion !== undefined ? { - recoveryCommand: `T3CODE_HOME=${quote(input.baseDir)} ${quote(pinnedRuntimePaths(path, input.baseDir, installedVersion, platform).entryPath)} __service-launcher`, + // PowerShell has no inline variable assignment; the launcher takes a flag. + recoveryCommand: windows + ? `& ${launcher(installedVersion)} __service-launcher --base-dir ${quote(input.baseDir)}` + : `T3CODE_HOME=${quote(input.baseDir)} ${launcher(installedVersion)} __service-launcher`, } : {}, ); @@ -1013,19 +1335,23 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { 2, )}\n`, ); - if (!start && (currentlyInstalled || Option.isSome(previousStateText))) { + if ((!start || handOff) && (currentlyInstalled || Option.isSome(previousStateText))) { const written = yield* fs.readFileString(statePath); if (serviceStateActiveVersion(written) !== input.cliVersion) { return yield* new BootServiceUpdatePendingError(); } } - yield* writeDurably(unitPath, manager.render(plan)); + const unit = manager.render(plan); + yield* writeDurably(unitPath, unit); + if (!start && manager.kind === "schtasks") yield* refreshWindowsTask(unit); }), ), ).pipe( Effect.andThen( Effect.gen(function* () { - if (start) { + if (handOff) { + yield* runSteps(manager.handoff ?? []); + } else if (start) { yield* runSteps(manager.activate); yield* withSelectionLock( statePath, @@ -1044,10 +1370,12 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { cause._tag === "PlatformError" ? new BootServiceInstallError({ cause }) : cause, ), Effect.tapError(() => - installed && start ? runSteps(manager.restart).pipe(Effect.ignore) : Effect.void, + installed && start && !handOff + ? runSteps(manager.restart).pipe(Effect.ignore) + : Effect.void, ), ); - return plan; + return handOff ? { ...plan, handedOff: true } : plan; }); const restart: BootService["Service"]["restart"] = Effect.gen(function* () { @@ -1109,9 +1437,16 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ), ([enabled, active]) => succeeded(active) || succeeded(enabled), ) - : succeeded( - yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]), - ); + : manager.kind === "schtasks" + ? // A task disabled while its launcher runs was left that way by an interrupted stop. + yield* Effect.map( + readSchtasksProblems(unit), + (problems) => + !problems.includes("service-disabled") || !problems.includes("service-stopped"), + ) + : succeeded( + yield* probe("launchctl", ["print", `gui/${uid}/${BOOT_SERVICE_LAUNCHD_LABEL}`]), + ); return yield* Effect.acquireUseRelease( // Require every stop before repair when restoring, so the server releases the database. // Otherwise stops are best-effort; launchd rejects bootout of an unloaded job. @@ -1170,7 +1505,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ? contents.replace(/(PATH<\/key>\n\s*)[^<]*(<\/string>)/, "$1$2") : contents; const problems: BootServiceProblem[] = - manager.kind === "systemd" ? [...(yield* readSystemdProblems(true))] : []; + manager.kind === "systemd" + ? [...(yield* readSystemdProblems(true))] + : manager.kind === "schtasks" + ? [...(yield* readSchtasksProblems(Option.some(unit)))] + : []; if (yield* fs.exists(restartPendingPath)) problems.push("restart-pending"); return { supported: true, diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 3a7e1a21ce288..74783cf215594 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -119,6 +119,24 @@ it.effect("preserves a launcher rejection as a distinct error", () => }), ); +it.effect("stops the server when the launcher asks over IPC", () => + Effect.gen(function* () { + const host = new FakeLauncherProcess({ + protocol: SERVICE_LAUNCHER_PROTOCOL, + childVersion: "1.0.0", + }); + const stopped = yield* Effect.forkChild( + ServiceLauncherClient.awaitServiceLauncherStop({ currentVersion: "1.0.0" }).pipe( + Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, host), + Effect.provideService(HostProcess.Environment, host.env), + ), + { startImmediately: true }, + ); + host.emit({ type: "stop" }); + yield* Fiber.join(stopped); + }), +); + it.effect("rejects contradictory trial context instead of leaving activation closed", () => Effect.gen(function* () { const host = new FakeLauncherProcess({ diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index 3a069e9ec5fb8..d444622dabea4 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -3,6 +3,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import packageJson from "../../package.json" with { type: "json" }; @@ -141,6 +142,22 @@ export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_clie }, ); +/** Completes when the launcher asks this server to stop, which Windows cannot signal. */ +export const awaitServiceLauncherStop = Effect.fn("cloud.service_launcher_client.await_stop")( + function* (options?: { readonly currentVersion?: string }) { + const startup = yield* resolveStartup(options).pipe(Effect.option); + if (Option.isNone(startup) || !startup.value.managed) return yield* Effect.never; + const { host } = startup.value; + return yield* Effect.callback((resume) => { + const onMessage = (...args: ReadonlyArray) => { + if (decodeServiceLauncherParentMessage(args[0])?.type === "stop") resume(Effect.void); + }; + host.on("message", onMessage); + return Effect.sync(() => host.off("message", onMessage)); + }); + }, +); + export const make = Effect.fn("cloud.service_launcher_client.make")(function* (options?: { readonly currentVersion?: string; }) { diff --git a/apps/server/src/cloud/serviceProtocol.ts b/apps/server/src/cloud/serviceProtocol.ts index 2d0fe556ca5a9..eeb6333435795 100644 --- a/apps/server/src/cloud/serviceProtocol.ts +++ b/apps/server/src/cloud/serviceProtocol.ts @@ -21,6 +21,8 @@ export const SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT"; export const SERVICE_STOP_MARKER_FILE = ".service-stopping"; /** Marks a repointed unit whose service still runs the old version; launcher startup clears it. */ export const SERVICE_RESTART_PENDING_FILE = ".restart-pending"; +/** Held by a Windows launcher while it runs: Task Scheduler tracks only the task's console host. */ +export const SERVICE_LAUNCHER_LOCK_FILE = "service-launcher.lock"; const unquoteSystemdValue = (raw: string) => (raw.startsWith('"') && raw.endsWith('"') @@ -31,21 +33,38 @@ const unquoteSystemdValue = (raw: string) => const unescapeXmlText = (value: string) => value.replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&"); +const unquoteWindowsArgument = (raw: string) => + unescapeXmlText(raw).replace(/(\\+)$/, (slashes) => slashes.slice(slashes.length / 2)); + +/** Whether Task Scheduler's copy of a task is disabled as a whole, not one of its triggers. */ +export const serviceTaskIsDisabled = (taskXml: string): boolean => + /[\s\S]*?<\/Settings>/.exec(taskXml)?.[0].includes("false") === true; + +/** A task as Task Scheduler should hold it while its service must stay stopped. */ +export const disabledServiceTask = (taskXml: string): string => + serviceTaskIsDisabled(taskXml) + ? taskXml + : taskXml.replace(" ", " false\n "); + export function serviceUnitBaseDirOf(contents: string): string | undefined { const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1]; if (systemd !== undefined) return unquoteSystemdValue(systemd.trim()); const plist = /T3CODE_HOME<\/key>\s*([^<]*)<\/string>/.exec(contents)?.[1]; - return plist === undefined ? undefined : unescapeXmlText(plist); + if (plist !== undefined) return unescapeXmlText(plist); + const task = /[^<]* "--base-dir" "([^"]*)"/.exec(contents)?.[1]; + return task === undefined ? undefined : unquoteWindowsArgument(task); } -/** The executable an installed unit or plist starts: the launcher's runtime. */ +/** The executable an installed unit, plist, or task starts: the launcher's runtime. */ export function serviceUnitProgramOf(contents: string): string | undefined { const systemd = /^ExecStart=("(?:\\.|[^"\\])*"|\S+)/m.exec(contents)?.[1]; if (systemd !== undefined) return unquoteSystemdValue(systemd); const plist = /ProgramArguments<\/key>\s*\s*([^<]*)<\/string>/.exec( contents, )?.[1]; - return plist === undefined ? undefined : unescapeXmlText(plist); + if (plist !== undefined) return unescapeXmlText(plist); + const task = /--headless "([^"]*)"/.exec(contents)?.[1]; + return task === undefined ? undefined : unquoteWindowsArgument(task); } export interface PendingServiceUpdate { @@ -93,6 +112,10 @@ export type ServiceLauncherParentMessage = | { readonly type: "committed"; readonly updateId: string; + } + | { + /** Shut down as on SIGTERM, which Windows cannot deliver. */ + readonly type: "stop"; }; const SEMVER_NUMBER = "(?:0|[1-9]\\d*)"; @@ -309,6 +332,7 @@ export function decodeServiceLauncherParentMessage( if (value.type === "update-accepted" && typeof value.updateId === "string") { return { type: value.type, updateId: value.updateId }; } + if (value.type === "stop") return { type: value.type }; return value.type === "committed" && typeof value.updateId === "string" ? { type: value.type, updateId: value.updateId } : undefined; diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index dc86e7b08ad0b..e3d53849501d7 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -15,7 +15,11 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import { vi } from "vite-plus/test"; -import { renderBootServicePlist, renderBootServiceUnit } from "./cloud/bootService.ts"; +import { + renderBootServicePlist, + renderBootServiceTask, + renderBootServiceUnit, +} from "./cloud/bootService.ts"; import { databaseBackupBlocker, Launcher, @@ -23,15 +27,20 @@ import { readServiceEnvironment, type BackupSpaceProbe, readServiceState, + registerServiceTask, + serviceLauncherIsRunning, + serviceLauncherLockPath, writeServiceState, } from "./serviceLauncher.ts"; import { compareExactServiceVersions, decodeServiceState, isExactServiceVersion, + disabledServiceTask, SERVICE_ENV_FILE, SERVICE_LAUNCHER_PROTOCOL, SERVICE_RESTART_PENDING_FILE, + SERVICE_STOP_MARKER_FILE, } from "./cloud/serviceProtocol.ts"; const spawnedChildren = vi.hoisted((): Array => []); @@ -222,6 +231,77 @@ it.layer(NodeServices.layer)("service state persistence", (it) => { }), ); + it.effect("registers its task again without enabling one the CLI disabled", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-task-" }); + const unitPath = path.join(root, "t3code-task.xml"); + const unit = renderBootServiceTask(unitPlan(root, "1.1.0"), { + userId: "PC\\theo", + homeDir: "C:\\Users\\theo", + conhostPath: "conhost.exe", + }); + yield* fs.writeFileString(unitPath, unit); + // Task Scheduler's copy: `t3 doctor` disabled it to keep the service stopped. + let task = disabledServiceTask(unit.replace("1.1.0", "1.0.0")); + const schtasks = async (...args: ReadonlyArray) => { + if (args[0] === "/Create") task = await NodeFSP.readFile(args[2] ?? "", "utf8"); + return { stdout: task }; + }; + + yield* Effect.promise(() => registerServiceTask(unitPath, "t3code-PC-theo", schtasks)); + assert.equal(task, disabledServiceTask(unit)); + assert.deepEqual(yield* fs.readDirectory(root), ["t3code-task.xml"]); + + task = unit.replace("1.1.0", "1.0.0"); + yield* Effect.promise(() => registerServiceTask(unitPath, "t3code-PC-theo", schtasks)); + assert.equal(task, unit); + }), + ); + + it.effect("finds its unit through the manager's environment, not service.env", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-launcher-unit-" }); + const home = path.join(root, "home"); + const unitPath = path.join(home, "Library", "LaunchAgents", "t3code.plist"); + const render = (version: string) => + renderBootServicePlist(unitPlan(root, version), { homeDir: home, environmentPath: "" }); + yield* fs.makeDirectory(path.dirname(unitPath), { recursive: true }); + yield* fs.writeFileString(unitPath, render("1.0.0")); + // The server may run with another HOME; the launch agent still lives in the manager's. + yield* fs.writeFileString(path.join(root, SERVICE_ENV_FILE), "HOME=/elsewhere\n"); + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", "1.1.0"), + "process.exit(0);\n", + ); + yield* Effect.promise(() => + writeServiceState(path.join(root, "runtime", "service-state.json"), { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.1.0", + update: { + id: "update-1", + fromVersion: "1.0.0", + targetVersion: "1.1.0", + status: "committed", + }, + }), + ); + vi.stubEnv("HOME", home); + vi.stubEnv("T3_BOOT_SERVICE_UNIT", "t3code.plist"); + + yield* Effect.promise(() => + expect(runLauncher(root)).rejects.toThrow("Active child exited unexpectedly (0)."), + ); + + assert.equal(yield* fs.readFileString(unitPath), render("1.1.0")); + }), + ); + it.effect("adopts a legacy install record without rewriting it", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -610,6 +690,15 @@ if (context.update?.status === "pending") { environmentPath: "/usr/bin:/custom/runtime/versions/1.0.0", }), }, + { + name: "Task Scheduler", + legacyInstall: false, + render: (plan: Parameters[0]) => + renderBootServiceTask( + { ...plan, program: [`${plan.program[0]}.exe`, "__service-launcher"] }, + { userId: "PC\\theo", homeDir: "C:\\Users\\theo", conhostPath: "conhost.exe" }, + ), + }, ])( "commits and repoints $name only after the trial reports prepared", ({ render, legacyInstall }) => @@ -1031,6 +1120,107 @@ if (context.update?.status === "pending") { }), ); + it.effect("holds its lock while it serves and stops the server over IPC, marker set", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-control-" }); + const statePath = path.join(root, "runtime", "service-state.json"); + const databasePath = path.join(root, "userdata", "state.sqlite"); + const reportPath = path.join(root, "stopped-with-marker"); + yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true }); + yield* fs.writeFileString(databasePath, "database"); + const encoded = JSON.stringify({ + databasePath, + reportPath, + markerPath: path.join(root, "runtime", SERVICE_STOP_MARKER_FILE), + }); + const childSource = ` +const fs = require("node:fs"); +const paths = ${encoded}; +process.on("message", (message) => { + if (message.type !== "stop") return; + fs.writeFileSync(paths.reportPath, String(fs.existsSync(paths.markerPath))); + process.exit(0); +}); +process.send({ type: "request-update", targetVersion: "1.1.0", dbPath: paths.databasePath }); +`; + for (const version of ["1.0.0", "1.1.0"]) { + yield* writeFakeRuntime( + fs, + path, + path.join(root, "runtime", "versions", version), + childSource, + ); + } + yield* Effect.promise(() => + writeServiceState(statePath, { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.0.0", + }), + ); + const lockPath = serviceLauncherLockPath(root); + const serving = Promise.withResolvers(); + const launcher = new Launcher( + root, + yield* Effect.promise(() => readServiceState(statePath)), + { + lockPath, + stopChildOverIpc: true, + // The update request proves the child is up; refusing it leaves the server running. + backupSpaceProbe: { + readFreeBytes: () => { + serving.resolve(); + return Promise.resolve(0); + }, + canClone: () => Promise.resolve(false), + }, + }, + ); + const running = launcher.run(); + yield* Effect.promise(() => Promise.race([serving.promise, running])); + + assert.isTrue(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath))); + // What losing the task's console does. + yield* Effect.promise(() => launcher.stop("SIGTERM")); + yield* Effect.promise(() => running); + assert.equal(yield* fs.readFileString(reportPath), "true"); + assert.isFalse(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath))); + }), + ); + + it.effect("leaves a pending update alone when stopped while it starts up", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-startup-stop-" }); + const statePath = path.join(root, "runtime", "service-state.json"); + // Recovery would roll this back: the target runtime is missing. + const pending = { + protocol: SERVICE_LAUNCHER_PROTOCOL, + activeVersion: "1.0.0", + update: { + id: "update-1", + fromVersion: "1.0.0", + targetVersion: "1.1.0", + dbPath: path.join(root, "userdata", "state.sqlite"), + status: "pending", + }, + } as const; + yield* Effect.promise(() => writeServiceState(statePath, pending)); + const lockPath = serviceLauncherLockPath(root); + const launcher = new Launcher(root, pending, { lockPath }); + + const running = launcher.run(); + yield* Effect.promise(() => launcher.stop("SIGTERM")); + yield* Effect.promise(() => running); + + // The lock is released only once the launcher is done with the home. + assert.isFalse(yield* Effect.promise(() => serviceLauncherIsRunning(lockPath))); + assert.deepEqual(yield* Effect.promise(() => readServiceState(statePath)), pending); + }), + ); + it.effect("records no update when the server exits during the backup check", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index fb847dd1edaa0..0c2daf14fd9dd 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -22,9 +22,12 @@ import { decodeServiceLauncherChildMessage, isExactServiceVersion, parseLegacyServiceState, + disabledServiceTask, parseServiceState, + serviceTaskIsDisabled, serviceUnitBaseDirOf, SERVICE_ENV_FILE, + SERVICE_LAUNCHER_LOCK_FILE, SERVICE_LAUNCHER_CONTEXT_ENV, SERVICE_LAUNCHER_PROTOCOL, SERVICE_STATE_FILE, @@ -40,6 +43,9 @@ const HANDOFF_DELAY_MS = 2_000; */ const PREPARED_TIMEOUT_MS = 30 * 60_000; const TERMINATE_GRACE_MS = 5_000; +// A replacement started by a handoff waits up to two minutes for the stopping launcher. +const LOCK_RETRY_MS = 500; +const LOCK_ATTEMPTS = 240; // Match contracts' SERVER_EXIT_CODE_STATE_DIR_OWNED without depending on Effect. const STATE_DIR_OWNED_EXIT_CODE = 78; @@ -76,14 +82,53 @@ const runtimeSpawnArguments = (paths: ReturnType) => ({ */ export interface ServiceUnit { readonly path: string; - /** systemd keeps a loaded copy of the unit; launchd re-reads the plist at bootstrap. */ + /** systemd and Task Scheduler keep a loaded copy; launchd re-reads the plist at bootstrap. */ readonly reload: () => Promise; } +const runSchtasks = (...args: ReadonlyArray) => + NodeUtil.promisify(NodeChildProcess.execFile)("schtasks", args, { + windowsHide: true, + timeout: 30_000, + }); + +/** + * Registering replaces the task, so one the CLI disabled to keep the service stopped is + * registered disabled. The caller holds the unit lease, as the CLI does to disable it. + */ +export async function registerServiceTask( + unitPath: string, + taskName: string, + schtasks: (...args: ReadonlyArray) => Promise<{ readonly stdout: string }> = runSchtasks, +): Promise { + const register = (xmlPath: string) => schtasks("/Create", "/XML", xmlPath, "/TN", taskName, "/F"); + const registered = await schtasks("/Query", "/TN", taskName, "/XML"); + if (!serviceTaskIsDisabled(registered.stdout)) { + await register(unitPath); + return; + } + const disabledPath = `${unitPath}.${process.pid}.disabled`; + try { + const unit = await NodeFSP.readFile(unitPath, "utf8"); + await NodeFSP.writeFile(disabledPath, disabledServiceTask(unit)); + await register(disabledPath); + } finally { + await NodeFSP.rm(disabledPath, { force: true }); + } +} + function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): ServiceUnit | undefined { const unitName = env[SERVICE_UNIT_ENV]?.trim(); + if (!unitName) return undefined; + if (unitName.endsWith(".xml")) { + const localAppData = env.LOCALAPPDATA?.trim(); + if (!localAppData) return undefined; + const path = NodePath.win32.join(localAppData, "t3code", unitName); + const taskName = serviceTaskName(env.USERDOMAIN ?? "", env.USERNAME ?? ""); + return { path, reload: () => registerServiceTask(path, taskName) }; + } const home = env.HOME?.trim(); - if (!unitName || !home) return undefined; + if (!home) return undefined; if (unitName.endsWith(".plist")) { return { path: NodePath.join(home, "Library", "LaunchAgents", unitName), @@ -114,12 +159,13 @@ function serviceUnitFromEnvironment(env: NodeJS.ProcessEnv = process.env): Servi }; } -// systemd's ExecStart value, or the plist string before the __service-launcher argument. +// systemd's ExecStart value, or the plist string or task argument before __service-launcher. // Only the version segment changes, so quoted or escaped paths stay as rendered. // The launch agent's PATH names a versions directory without the executable; leave it. const SERVICE_UNIT_PROGRAMS = [ /^(ExecStart=.*?[\\/]runtime[\\/]versions[\\/])([^\\/\s"]+)([\\/]t3)(?=["\s])/m, /([^<]*?[\\/]runtime[\\/]versions[\\/])([^\\/<]+)([\\/]t3<\/string>\s*__service-launcher<\/string>)/, + /(--headless "[^"<]*?[\\/]runtime[\\/]versions[\\/])([^\\/"<]+)([\\/]t3\.exe" "__service-launcher")/, ] as const; /** @@ -601,10 +647,15 @@ function waitForExit(child: NodeChildProcess.ChildProcess): Promise { async function terminateChild( child: NodeChildProcess.ChildProcess, - signal: NodeJS.Signals = "SIGTERM", + signal: NodeJS.Signals, + overIpc: boolean, ): Promise { if (child.exitCode !== null || child.signalCode !== null) return; - child.kill(signal); + if (overIpc) { + await sendMessage(child, { type: "stop" }).catch(() => child.kill(signal)); + } else { + child.kill(signal); + } const force = setTimeout(() => child.kill("SIGKILL"), TERMINATE_GRACE_MS); try { await waitForExit(child); @@ -613,6 +664,46 @@ async function terminateChild( } } +/** Task Scheduler names are machine-wide, so each Windows account runs its own task. */ +export const serviceTaskName = (domain: string, userName: string) => `t3code-${domain}-${userName}`; + +export const serviceLauncherLockPath = (baseDir: string) => + NodePath.join(baseDir, "runtime", SERVICE_LAUNCHER_LOCK_FILE); + +// An exclusive SQLite transaction, like the server's owner lock: the OS drops it when the holder dies. +async function tryAcquireLauncherLock( + lockPath: string, +): Promise<{ readonly close: () => void } | undefined> { + const { DatabaseSync } = await import("node:sqlite"); + const db = new DatabaseSync(lockPath); + try { + db.exec("PRAGMA busy_timeout = 0; BEGIN EXCLUSIVE;"); + return db; + } catch (cause) { + db.close(); + if (cause instanceof Error && "errcode" in cause && cause.errcode === 5) return undefined; + throw cause; + } +} + +export async function serviceLauncherIsRunning(lockPath: string): Promise { + if (!NodeFS.existsSync(lockPath)) return false; + const lock = await tryAcquireLauncherLock(lockPath); + lock?.close(); + return lock === undefined; +} + +/** Resolves once no launcher holds the lock; the caller bounds the wait through `signal`. */ +export async function waitForServiceLauncherExit( + lockPath: string, + signal: AbortSignal, +): Promise { + while (await serviceLauncherIsRunning(lockPath)) { + signal.throwIfAborted(); + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} + const stopMarkerPath = (baseDir: string) => NodePath.join(baseDir, "runtime", SERVICE_STOP_MARKER_FILE); const restartPendingPath = (baseDir: string) => @@ -632,6 +723,9 @@ export class Launcher { readonly #backupSpaceProbe: Partial | undefined; readonly #serviceUnit: ServiceUnit | undefined; readonly #environment: Readonly; + readonly #output: number | undefined; + readonly #lockPath: string | undefined; + readonly #stopChildOverIpc: boolean; constructor( baseDir: string, @@ -640,12 +734,22 @@ export class Launcher { readonly backupSpaceProbe?: Partial; readonly serviceUnit?: ServiceUnit; readonly environment?: Readonly; + /** Launcher and server output, for managers that cannot redirect it. */ + readonly output?: number; + /** Makes this the only launcher for its home; a replacement waits for the one stopping. */ + readonly lockPath?: string; + /** Windows `kill()` is TerminateProcess, which skips the server's shutdown finalizers. */ + readonly stopChildOverIpc?: boolean; } = {}, ) { this.#baseDir = baseDir; this.#backupSpaceProbe = options.backupSpaceProbe; this.#serviceUnit = options.serviceUnit; this.#environment = { ...(options.environment ?? process.env) }; + this.#output = options.output; + this.#lockPath = options.lockPath; + // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. + this.#stopChildOverIpc = options.stopChildOverIpc ?? process.platform === "win32"; this.#statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE); this.#state = state; } @@ -656,14 +760,48 @@ export class Launcher { process.once("SIGTERM", onSigterm); process.once("SIGINT", onSigint); try { - this.#enqueue(() => this.#recover()); - await this.#completion.promise; + const lock = + this.#lockPath === undefined ? undefined : await this.#acquireLock(this.#lockPath); + try { + // The launcher that held the lock may have moved the state since main read it. + if (lock !== undefined) this.#state = await readServiceState(this.#statePath); + // A stop that arrived before this point leaves nothing to start or recover. + if (!this.#stopRequested) this.#enqueue(() => this.#recover()); + await this.#completion.promise; + } finally { + if (lock !== undefined) { + // Releasing the lock says this launcher is done with the home. + await this.#transitions.catch(() => undefined); + lock.close(); + } + } } finally { process.off("SIGTERM", onSigterm); process.off("SIGINT", onSigint); } } + async #acquireLock(lockPath: string): Promise<{ readonly close: () => void } | undefined> { + for (let attempt = 1; !this.#stopRequested; attempt++) { + const lock = await tryAcquireLauncherLock(lockPath); + if (lock !== undefined) return lock; + if (attempt >= LOCK_ATTEMPTS) { + throw new Error("Another T3 Code service launcher still runs for this T3 home."); + } + await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_MS)); + } + return undefined; + } + + #terminate(child: NodeChildProcess.ChildProcess, signal: NodeJS.Signals = "SIGTERM") { + return terminateChild(child, signal, this.#stopChildOverIpc); + } + + #log(line: string): void { + if (this.#output === undefined) process.stderr.write(line); + else NodeFS.writeSync(this.#output, line); + } + #enqueue(transition: () => Promise): void { this.#transitions = this.#transitions .then(transition, transition) @@ -679,7 +817,7 @@ export class Launcher { this.#clearTimer(); const child = this.#child?.process; this.#child = null; - if (child !== undefined) await terminateChild(child); + if (child !== undefined) await this.#terminate(child); this.#completion.reject(error); } @@ -699,7 +837,7 @@ export class Launcher { this.#stopping = true; const child = this.#child?.process; this.#child = null; - if (child !== undefined) await terminateChild(child, signal); + if (child !== undefined) await this.#terminate(child, signal); this.#done = true; this.#completion.resolve(); }); @@ -813,7 +951,10 @@ export class Launcher { const spawnArguments = runtimeSpawnArguments(paths); const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, { env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) }, - stdio: ["inherit", "inherit", "inherit", "ipc"], + stdio: + this.#output === undefined + ? ["inherit", "inherit", "inherit", "ipc"] + : ["ignore", this.#output, this.#output, "ipc"], }); await new Promise((resolve, reject) => { const onError = (error: Error) => reject(error); @@ -825,7 +966,7 @@ export class Launcher { }); }); if (this.#stopping) { - await terminateChild(child); + await this.#terminate(child); return; } @@ -940,7 +1081,7 @@ export class Launcher { this.#backupSpaceProbe, ).catch(() => undefined); this.#child = null; - await terminateChild(child.process); + await this.#terminate(child.process); await finishOnlineBackup?.(); // A stop during a minutes-long copy should not start a trial; restart resumes the pending update. if (this.#stopRequested) return; @@ -1076,7 +1217,7 @@ export class Launcher { } // Signal listeners alone do not keep Node alive. this.#timer = setInterval(() => {}, 2_147_483_647); - process.stderr.write( + this.#log( "[service-launcher] Another T3 Code server owns this T3 home. Stop it, then restart this service.\n", ); } @@ -1089,7 +1230,7 @@ export class Launcher { ): Promise { if (child !== undefined) { this.#child = null; - await terminateChild(child.process); + await this.#terminate(child.process); } await restoreDatabaseBackup(this.#baseDir, pending); const outcome = terminalUpdate({ pending, status, reason }); @@ -1108,26 +1249,82 @@ export class Launcher { } } -export async function main(): Promise { - const baseDir = process.env.T3CODE_HOME?.trim(); +/** Task Scheduler cannot set variables or redirect output, so a Windows task passes them as flags. */ +export interface LauncherOptions { + readonly baseDir?: string | undefined; + readonly logFile?: string | undefined; + readonly serviceUnit?: string | undefined; +} + +export async function main(options: LauncherOptions = {}): Promise { + const baseDir = (options.baseDir ?? process.env.T3CODE_HOME)?.trim(); if (baseDir === undefined || baseDir === "") { throw new Error("T3CODE_HOME is required by the T3 Code service launcher."); } - const environment = await readServiceEnvironment(baseDir); - const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE); - const contents = await NodeFSP.readFile(statePath, "utf8"); - let state = parseServiceState(contents); - if (state === undefined) { - state = adoptLegacyServiceState(contents); - if (state === undefined) throw new Error("Service state is invalid or unsupported."); - if (!(await runtimeExists(baseDir, state.activeVersion))) { - throw new Error(`Selected t3@${state.activeVersion} runtime is missing or incomplete.`); + const output = + options.logFile === undefined ? undefined : NodeFS.openSync(options.logFile, "a", 0o600); + // oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher has no Effect runtime. + const windows = process.platform === "win32"; + try { + // What the service manager started the launcher with. It locates the unit; service.env + // changes only what the server gets. + const managerEnvironment = { + ...process.env, + T3CODE_HOME: baseDir, + ...(options.serviceUnit === undefined ? {} : { [SERVICE_UNIT_ENV]: options.serviceUnit }), + }; + const environment = await readServiceEnvironment(baseDir, managerEnvironment); + const statePath = NodePath.join(baseDir, "runtime", SERVICE_STATE_FILE); + const contents = await NodeFSP.readFile(statePath, "utf8"); + let state = parseServiceState(contents); + if (state === undefined) { + state = adoptLegacyServiceState(contents); + if (state === undefined) throw new Error("Service state is invalid or unsupported."); + if (!(await runtimeExists(baseDir, state.activeVersion))) { + throw new Error(`Selected t3@${state.activeVersion} runtime is missing or incomplete.`); + } + } + const serviceUnit = serviceUnitFromEnvironment(managerEnvironment); + const launcher = new Launcher(baseDir, state, { + environment, + ...(serviceUnit === undefined ? {} : { serviceUnit }), + ...(output === undefined ? {} : { output }), + ...(windows ? { lockPath: serviceLauncherLockPath(baseDir) } : {}), + }); + // Ending a scheduled task kills its console host without a signal; the console read fails instead. + const watchConsole = windows && process.stdin.isTTY === true; + const onConsoleLost = () => void launcher.stop("SIGTERM"); + if (watchConsole) { + process.stdin.on("error", () => undefined); + process.stdin.once("close", onConsoleLost); + process.stdin.resume(); + } + try { + await launcher.run(); + } finally { + if (watchConsole) { + process.stdin.off("close", onConsoleLost); + process.stdin.destroy(); + } } + } catch (cause) { + if (output !== undefined) { + NodeFS.writeSync( + output, + `[service-launcher] ${cause instanceof Error ? cause.message : String(cause)}\n`, + ); + } + // Agents the server left behind keep the console host, and so the task, running; ending it + // lets the next repeating trigger start the service again. + if (windows && options.serviceUnit !== undefined) { + const taskName = serviceTaskName(process.env.USERDOMAIN ?? "", process.env.USERNAME ?? ""); + NodeChildProcess.spawnSync("schtasks", ["/End", "/TN", taskName], { + stdio: "ignore", + windowsHide: true, + }); + } + throw cause; + } finally { + if (output !== undefined) NodeFS.closeSync(output); } - const serviceUnit = serviceUnitFromEnvironment(); - await new Launcher( - baseDir, - state, - serviceUnit === undefined ? { environment } : { environment, serviceUnit }, - ).run(); } diff --git a/docs/internals/server-updates.md b/docs/internals/server-updates.md index a0405a450dc37..10b196a72adf5 100644 --- a/docs/internals/server-updates.md +++ b/docs/internals/server-updates.md @@ -1,7 +1,7 @@ # Server updates A [stable launcher](../../apps/server/src/serviceLauncher.ts) owns the runtime -selected by systemd or launchd. It is the only runtime writer of durable service +selected by systemd, launchd, or Task Scheduler. It is the only runtime writer of durable service state. Server children request updates over inherited IPC; they never rewrite their service definition or select their own replacement. Local service commands may replace the launcher and state, optionally deferring the restart. Foreground @@ -36,6 +36,17 @@ runtime that installed it. Until a deferred local upgrade restarts, systemd (bef daemon-reload) and launchd (before bootstrap) can respawn the old launcher, which rejects the state the new installer wrote. +Task Scheduler tracks only the console host it started, not the launcher. `schtasks /End` +kills that host and nothing else; the launcher takes its closed console as SIGTERM. The task +reads as stopped at once, and `/Run` then starts a second launcher beside the first, so a +Windows launcher holds a lock file for as long as it runs. A replacement waits for that lock, +and the CLI treats its release as the stop having finished. + +Task Scheduler also runs its own copy of the task, and registering one enables it. So every +write of the task file registers it, including an install that defers its restart. The CLI +disables the task under the unit lease, and a registration under that lease keeps a disabled +task disabled, so the repeating trigger cannot restart a service the CLI is holding stopped. + ## Commit boundary The launcher durably records the pending update before acknowledging it, then diff --git a/docs/user/background-service.md b/docs/user/background-service.md index 7e22a8518490b..28a68e0dfe4ab 100644 --- a/docs/user/background-service.md +++ b/docs/user/background-service.md @@ -1,7 +1,7 @@ # Running T3 Code in the background -On Linux and macOS, T3 Code can run as a service for your user so you do not need -to keep a terminal open. +On Linux, macOS, and Windows, T3 Code can run as a service for your user so you +do not need to keep a terminal open. ## Manage the service @@ -92,11 +92,12 @@ Mac logged in and awake for unattended remote access. Installing over SSH while nobody is logged in at the Mac's screen can fail at the final start step; the service is still installed and will start at the next login. -Windows background services are not supported. To keep a Windows host available -through T3 Connect, leave the desktop app running with its local environment -enabled, or keep `t3 serve` running in a terminal. Minimize the desktop app rather -than closing its last window, which stops its local server. Linking T3 Connect -does not configure automatic startup at Windows sign-in. +Windows starts the service when you log in and stops it when you sign out. It +runs without a window as the `t3code--` task in Task Scheduler, and Task +Scheduler starts it again within a minute if it exits. Lock the screen instead +of signing out, and keep the PC awake, for unattended remote access. Installing +over SSH while nobody is signed in at the PC can fail at the final start step; +the service is still installed and will start at the next sign-in. `t3 up` installs the service when you set up T3 Connect, but the two are managed separately. Signing out of T3 Connect does not stop or uninstall the service. @@ -147,7 +148,7 @@ that session open. | --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | | `linger-unavailable` | Run `loginctl show-user "$(id -un)" --property=Linger` and check that systemd-logind is available. | | `user-manager-unavailable` | Run `systemctl --user status` in a login session for the service user; check your distribution's systemd user-session support. | -| `service-disabled` or `service-stopped` | Read the log and `systemctl --user status t3code.service`, then use the repair command printed by T3 Code. | +| `service-disabled` or `service-stopped` | Read the log and, on Linux, `systemctl --user status t3code.service`, then use the repair command printed by T3 Code. | | `restart-pending` | A newer version is installed but the service still runs the previous one. Run `t3 service restart`. | On macOS, check **System Settings → General → Login Items** if the service no diff --git a/docs/user/install.md b/docs/user/install.md index c353e3f0fecb5..a21828ed56225 100644 --- a/docs/user/install.md +++ b/docs/user/install.md @@ -28,15 +28,15 @@ installer or the desktop app did not create is already there, it leaves that one alone and stops. Set `T3CODE_CHANNEL=nightly` to install the nightly train, or `T3CODE_VERSION` to pin an exact version. -| Task | Command | -| ------------------------------------------------ | ----------------------------------------------------------------------- | -| Start the server and open the web app | `t3` | -| Start the server without a browser | `t3 serve` | -| Use it from your other devices | `t3 up` ([details](./remote-access.md)) | -| Keep it running in the background (macOS, Linux) | `t3 service install` ([details](./background-service.md)) | -| Move to the newest release | `t3 update` | -| Reclaim database space | `t3 doctor` ([details](./background-service.md#reclaim-database-space)) | -| Remove it again | `t3 uninstall` | +| Task | Command | +| ------------------------------------- | ----------------------------------------------------------------------- | +| Start the server and open the web app | `t3` | +| Start the server without a browser | `t3 serve` | +| Use it from your other devices | `t3 up` ([details](./remote-access.md)) | +| Keep it running in the background | `t3 service install` ([details](./background-service.md)) | +| Move to the newest release | `t3 update` | +| Reclaim database space | `t3 doctor` ([details](./background-service.md#reclaim-database-space)) | +| Remove it again | `t3 uninstall` | Run `t3 help` or `t3 --help` for the full reference. To start in a new working directory, use an explicit path such as `t3 ./my-project`. A bare directory name @@ -239,6 +239,6 @@ For provider-specific setup and accounts, see [Codex](./providers-codex.md), - [Working with threads](./thread-sidebar.md): start tasks and organize parallel work. - [Permission modes](./permission-modes.md): choose when agents ask before acting. - [Remote access](./remote-access.md): connect from another device. -- [Running in the background](./background-service.md): keep a Linux or macOS host available. +- [Running in the background](./background-service.md): keep a host available. - [Updating T3 Code](./updating.md): update the app and connected servers. - [Managed policy](./managed-policy.md): configure T3 Code for everyone on a machine. diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 9635a8af2a0a7..910e5e90506d0 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -16,16 +16,15 @@ t3 up ``` It asks how your other devices reach the machine: T3 Connect, the local network, -or both. Choose T3 Connect and follow the sign-in instructions. On Linux and -macOS, it then runs T3 Code as a [background service](./background-service.md). +or both. Choose T3 Connect and follow the sign-in instructions. It then runs +T3 Code as a [background service](./background-service.md). `t3 connect` is the same as `t3 up --connect`. Run `t3 up` again to change your choice, and `t3 status` to see it. -The background service is not available on Windows, so there `t3 up` prints the -`t3 serve` command to keep running in a terminal. You can also keep the desktop -app running with its local environment enabled. Closing the desktop app's last -window stops its local server. Saving your sign-in alone does not start a server -or make the machine reachable. +Instead of the background service, you can keep the desktop app running with +its local environment enabled. Closing the desktop app's last window stops its +local server. Saving your sign-in alone does not start a server or make the +machine reachable. On your other device, sign in to the same T3 Connect account and choose the environment. On the app.t3.codes home page with no computer added yet, signing From 9b98bd07ba461a32920f28a8929810fd097b28a7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:35:25 -0800 Subject: [PATCH 005/128] fix(shared): new chats use the global default when the project default model is hidden (#23615) --- packages/shared/src/projectSettings.test.ts | 26 +++++++++++++++++++++ packages/shared/src/projectSettings.ts | 16 +++++++++++++ 2 files changed, 42 insertions(+) diff --git a/packages/shared/src/projectSettings.test.ts b/packages/shared/src/projectSettings.test.ts index 1cd6baf133bcc..a5edf854c3aec 100644 --- a/packages/shared/src/projectSettings.test.ts +++ b/packages/shared/src/projectSettings.test.ts @@ -119,6 +119,32 @@ describe("resolveProjectSettings", () => { expect(resolved.sources.defaultModelSelection).toBe("environment"); }); + // regression: #17556 a hidden project default silently became the catalog's first model + it.each([ + ["hidden", ["gpt-5.6-terra", "gpt-5.6-sol"], [], "gpt-6.1-sol", "environment"], + ["visible", ["gpt-5.6-terra"], [], "gpt-5.6-sol", "project"], + ["custom", ["gpt-5.6-sol"], ["gpt-5.6-sol"], "gpt-5.6-sol", "project"], + ] as const)( + "resolves a %s project default model against the environment default", + (_visibility, hiddenModels, customModels, expectedModel, expectedSource) => { + const codex = ProviderInstanceId.make("codex"); + const settings = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { + defaultModelSelection: createModelSelection(codex, "gpt-6.1-sol"), + providerInstances: { + [codex]: { driver: ProviderDriverKind.make("codex"), config: { customModels } }, + }, + providerModelPreferences: { [codex]: { hiddenModels, modelOrder: [] } }, + projectSettingsOverrides: { + [projectId]: { defaultModelSelection: createModelSelection(codex, "gpt-5.6-sol") }, + }, + }); + const resolved = resolveProjectSettings(settings, projectId); + expect(resolved.settings.defaultModelSelection?.model).toBe(expectedModel); + expect(resolved.sources.defaultModelSelection).toBe(expectedSource); + expect(resolved.overrides.defaultModelSelection?.model).toBe("gpt-5.6-sol"); + }, + ); + it("moves text generation off an instance the project turned off", () => { const codex = ProviderInstanceId.make("codex"); const settings = { diff --git a/packages/shared/src/projectSettings.ts b/packages/shared/src/projectSettings.ts index bde695fb21386..e6a9ac22418a0 100644 --- a/packages/shared/src/projectSettings.ts +++ b/packages/shared/src/projectSettings.ts @@ -14,6 +14,7 @@ import { type ThreadEnvMode, type WorktreeCleanupRules, } from "@t3tools/contracts"; +import { readCustomModelEntries } from "./model.ts"; import { normalizeProjectPathForComparison } from "./path.ts"; import { fallbackTextGenerationModelSelection } from "./serverSettings.ts"; @@ -148,6 +149,21 @@ function resolveProjectOverrides( ) { continue; } + // Clients resolve a hidden model to the catalog's first visible one, so a + // hidden project default would silently pick a model nobody chose. + // Custom models stay visible even when listed as hidden, as in the clients. + if (key === "defaultModelSelection" && value !== null) { + const { instanceId, model } = value as ModelSelection; + const config = settings.providerInstances[instanceId]?.config as + | { customModels?: unknown } + | undefined; + if ( + settings.providerModelPreferences?.[instanceId]?.hiddenModels.includes(model) && + !readCustomModelEntries(config?.customModels).some((entry) => entry.slug === model) + ) { + continue; + } + } effective[key] = value; sources[key] = "project"; } From 25d2239f9bbc55774b3b6750b733cb2204a138e6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:36:41 -0800 Subject: [PATCH 006/128] fix(web): screen readers hear when a thread is pinned or an action is undone (#25901) --- .../src/hooks/showThreadUndoNotice.test.ts | 21 ++++++++++++++++ apps/web/src/hooks/showThreadUndoNotice.ts | 24 ++++++++++++++++--- apps/web/src/hooks/useThreadActions.ts | 14 +++++++---- .../src/hooks/useThreadActions.undo.test.ts | 12 ++++++++++ 4 files changed, 63 insertions(+), 8 deletions(-) diff --git a/apps/web/src/hooks/showThreadUndoNotice.test.ts b/apps/web/src/hooks/showThreadUndoNotice.test.ts index 33e3ef1f12c11..39c2ad3e63a9a 100644 --- a/apps/web/src/hooks/showThreadUndoNotice.test.ts +++ b/apps/web/src/hooks/showThreadUndoNotice.test.ts @@ -1,3 +1,4 @@ +import { Cause } from "effect"; import { AsyncResult } from "effect/reactivity"; import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; @@ -88,4 +89,24 @@ describe("thread undo notice", () => { await notice().undo(); expect(cancelAnnouncement).toHaveBeenCalledWith("thread-undo-notice"); }); + + it("announces that the undo happened, naming the undone action", async () => { + const { options } = setup(); + showThreadUndoNotice(options); + vi.mocked(announce).mockClear(); + await notice().undo(); + expect(announce).toHaveBeenCalledExactlyOnceWith("Undid unpin of 1 thread"); + }); + + it("does not announce an undo that failed", async () => { + const { options, add } = setup(); + showThreadUndoNotice({ + ...options, + undo: async () => AsyncResult.failure(Cause.fail(new Error("offline"))), + }); + vi.mocked(announce).mockClear(); + await notice().undo(); + expect(add).toHaveBeenCalledOnce(); + expect(announce).not.toHaveBeenCalled(); + }); }); diff --git a/apps/web/src/hooks/showThreadUndoNotice.ts b/apps/web/src/hooks/showThreadUndoNotice.ts index 977dcd68d1ab7..03f1397af7d36 100644 --- a/apps/web/src/hooks/showThreadUndoNotice.ts +++ b/apps/web/src/hooks/showThreadUndoNotice.ts @@ -28,9 +28,21 @@ type UndoNotice = { export const useThreadUndoNotice = create<{ notice: UndoNotice | null }>(() => ({ notice: null })); +const UNDONE_ACTION = { + Settled: "settle", + Snoozed: "snooze", + Unpinned: "unpin", + Archived: "archive", + Discarded: "discard", +} satisfies Record; + +function countLabel(action: UndoOptions["action"], count: number) { + const noun = action === "Discarded" ? "draft" : "thread"; + return `${count} ${noun}${count === 1 ? "" : "s"}`; +} + function threadUndoNoticeSummary(notice: Pick): string { - const noun = notice.action === "Discarded" ? "draft" : "thread"; - return `${notice.action} ${notice.count} ${noun}${notice.count === 1 ? "" : "s"}`; + return `${notice.action} ${countLabel(notice.action, notice.count)}`; } export function threadUndoLabel(keybindings: Parameters[0]) { @@ -87,6 +99,7 @@ function refreshNotice() { // Claim before awaiting to prevent repeated actions restoring a group twice. for (const entry of current) entry.claim.finish(); refreshNotice(); + let undone = 0; await Promise.all( current.map(async ({ undo, failureTitle }) => { const reportFailure = (error: unknown) => { @@ -100,7 +113,8 @@ function refreshNotice() { }; try { const result = await undo(); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + if (result._tag === "Success") undone++; + else if (!isAtomCommandInterrupted(result)) { reportFailure(squashAtomCommandFailure(result)); } } catch (error) { @@ -108,6 +122,10 @@ function refreshNotice() { } }), ); + // Failures already raise a toast, so only what was actually restored is spoken. + if (undone > 0) { + announce(`Undid ${UNDONE_ACTION[latest.action]} of ${countLabel(latest.action, undone)}`); + } }, }); } diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index e91f170689a56..a057f08527323 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -35,6 +35,7 @@ import { vcsEnvironment } from "../state/vcs"; import { useNewThreadHandler } from "./useHandleNewThread"; import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState"; import { releaseComposerDraftUploads } from "../lib/composerDraftUploads"; +import { announce } from "../lib/announce"; import { readLocalApi } from "../localApi"; import { readEnvironmentServerConfigLoaded, @@ -727,7 +728,7 @@ export function useThreadActions() { }); }; - const pinThread = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => { + const sendPin = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => { if (!readEnvironmentServerConfigLoaded(target.environmentId)) { return AsyncResult.failure( Cause.fail( @@ -752,6 +753,12 @@ export function useThreadActions() { }); }; + const pinThread = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => { + const result = await sendPin(target, opts); + if (result._tag === "Success") announce("Pinned 1 thread"); + return result; + }; + const unpinThread = async (target: ScopedThreadRef) => { if (!readEnvironmentServerConfigLoaded(target.environmentId)) { return AsyncResult.failure( @@ -947,10 +954,7 @@ export function useThreadActions() { case "unsnooze": return unsnoozeThread(target); case "pin": - return pinThread( - target, - step.orderKey === undefined ? {} : { orderKey: step.orderKey }, - ); + return sendPin(target, step.orderKey === undefined ? {} : { orderKey: step.orderKey }); case "snooze": return snoozeThreadMutation({ environmentId: target.environmentId, diff --git a/apps/web/src/hooks/useThreadActions.undo.test.ts b/apps/web/src/hooks/useThreadActions.undo.test.ts index 5ec8f1fc64304..a2ce4229d9b06 100644 --- a/apps/web/src/hooks/useThreadActions.undo.test.ts +++ b/apps/web/src/hooks/useThreadActions.undo.test.ts @@ -6,6 +6,7 @@ import { useThreadActions } from "./useThreadActions"; import { threadEnvironment } from "../state/threads"; import { toastManager } from "../components/ui/toast"; import { useThreadUndoNotice } from "./showThreadUndoNotice"; +import { announce } from "../lib/announce"; const commands = vi.hoisted(() => ({ pin: vi.fn(), @@ -44,6 +45,7 @@ vi.mock("../composerDraftStore", () => ({ useComposerDraftStore: () => vi.fn() } vi.mock("../lib/composerDraftUploads", () => ({ releaseComposerDraftUploads: vi.fn() })); vi.mock("../terminalUiStateStore", () => ({ useTerminalUiStateStore: () => vi.fn() })); vi.mock("../uiStateStore", () => ({ useUiStateStore: () => vi.fn() })); +vi.mock("../lib/announce", () => ({ announce: vi.fn(), cancelAnnouncement: vi.fn() })); vi.mock("../lib/archivedThreadsState", () => ({ refreshArchivedThreadsForEnvironment: vi.fn() })); const threadShell = vi.hoisted(() => ({ title: "Thread", @@ -139,12 +141,22 @@ describe("concurrent thread action Undo", () => { ); }); +describe("pin", () => { + it("announces that the thread was pinned", async () => { + vi.mocked(announce).mockClear(); + await useThreadActions().pinThread(target); + expect(announce).toHaveBeenCalledExactlyOnceWith("Pinned 1 thread"); + }); +}); + describe("unpin Undo", () => { it("restores the original snooze after restoring the pin", async () => { threadShell.pinnedAt = "2026-01-01T00:00:00.000Z"; threadShell.snoozedUntil = "2030-01-01T09:00:00.000Z"; await useThreadActions().unpinThread(target); + vi.mocked(announce).mockClear(); await currentUndo()(); + expect(announce).not.toHaveBeenCalledWith("Pinned 1 thread"); expect(commands.pin).toHaveBeenCalledExactlyOnceWith({ environmentId: target.environmentId, input: { threadId: target.threadId, orderKey: "a0" }, From 658367016c110446685837416101956884e92097 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:36:48 -0800 Subject: [PATCH 007/128] fix(desktop): Linux launches no longer leave an icon copy in /tmp (#25775) --- .../src/app/DesktopLinuxUrlHandler.test.ts | 38 ++++++++++++++----- .../desktop/src/app/DesktopLinuxUrlHandler.ts | 5 ++- .../src/app/DesktopPreReadyPlatform.test.ts | 20 +++++++--- .../src/app/DesktopPreReadyPlatform.ts | 13 ++++--- 4 files changed, 54 insertions(+), 22 deletions(-) diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts index 16d2f8e241d2f..7e685358865c7 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.test.ts @@ -26,8 +26,11 @@ interface RecordedRegistration { readonly files: Array<{ readonly path: string; readonly content: string }>; readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray }>; readonly copies: Array<{ readonly source: string; readonly destination: string }>; + readonly icons: Array<{ readonly path: string; readonly bytes: ReadonlyArray }>; } +const ICON_BYTES = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); + const makeEnvironment = (path: Path.Path, overrides: Record = {}) => DesktopEnvironment.DesktopEnvironment.of({ platform: "linux", @@ -69,7 +72,7 @@ const layerHandler = ( readonly writeError?: PlatformError.PlatformError; readonly existingEntry?: string; readonly iconSource?: string; - readonly iconCopyError?: PlatformError.PlatformError; + readonly iconWriteError?: PlatformError.PlatformError; } = {}, ) => DesktopLinuxUrlHandler.layer.pipe( @@ -92,10 +95,25 @@ const layerHandler = ( }), FileSystem.layerNoop({ copyFile: (source, destination) => - input.iconCopyError - ? Effect.fail(input.iconCopyError) + Effect.sync(() => { + recorded.copies.push({ source, destination }); + }), + readFile: (path) => + path === input.iconSource + ? Effect.succeed(ICON_BYTES) + : Effect.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFile", + pathOrDescriptor: path, + }), + ), + writeFile: (path, bytes) => + input.iconWriteError + ? Effect.fail(input.iconWriteError) : Effect.sync(() => { - recorded.copies.push({ source, destination }); + recorded.icons.push({ path, bytes: [...bytes] }); }), readFileString: () => Effect.succeed(input.existingEntry ?? ""), makeDirectory: (path) => @@ -162,6 +180,7 @@ const emptyRecording = (): RecordedRegistration => ({ files: [], commands: [], copies: [], + icons: [], }); describe("DesktopLinuxUrlHandler", () => { @@ -290,22 +309,21 @@ describe("DesktopLinuxUrlHandler", () => { }), }); assert.deepEqual(recorded.files, []); - assert.deepEqual(recorded.copies, [ - { source: "/tmp/.mount_T3/resources/icon.png", destination: iconPath }, - ]); + assert.deepEqual(recorded.copies, [], "icon must not be copied out of the app bundle"); + assert.deepEqual(recorded.icons, [{ path: iconPath, bytes: [...ICON_BYTES] }]); assert.equal(recorded.commands.at(-1)?.command, "xdg-mime"); }); }); - it.effect("still registers the handler when copying its icon fails", () => { + it.effect("still registers the handler when installing its icon fails", () => { const recorded = emptyRecording(); return Effect.gen(function* () { yield* runRegister(recorded, { iconSource: "/tmp/.mount_T3/resources/icon.png", - iconCopyError: PlatformError.systemError({ + iconWriteError: PlatformError.systemError({ _tag: "PermissionDenied", module: "FileSystem", - method: "copyFile", + method: "writeFile", description: "read-only icon directory", }), }); diff --git a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts index cfa8498ae6238..64535c5b3ac11 100644 --- a/apps/desktop/src/app/DesktopLinuxUrlHandler.ts +++ b/apps/desktop/src/app/DesktopLinuxUrlHandler.ts @@ -298,10 +298,11 @@ export const make = Effect.gen(function* () { if (Option.isNone(png)) return; // The AppImage mount is temporary; the chooser needs the icon after exit. yield* fileSystem.makeDirectory(iconsDir, { recursive: true }); - yield* fileSystem.copyFile(png.value, iconPath); + // Electron's copyFile from app.asar extracts to a temp file it never deletes. + yield* fileSystem.writeFile(iconPath, yield* fileSystem.readFile(png.value)); }).pipe( Effect.catch((error) => - logWarning("URL handler icon copy failed", { iconPath, category: error.reason._tag }), + logWarning("URL handler icon install failed", { iconPath, category: error.reason._tag }), ), ); diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts index 22bfc969c4088..34607e08b844f 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts @@ -129,14 +129,19 @@ describe("DesktopPreReadyPlatform", () => { let desktopName = "t3code.desktop"; let desktopEntry = previousEntry; let iconInstalled = false; - copyFileSyncMock.mockImplementation((_source: string, destination: string) => { - iconInstalled = destination === "/xdg/icons/com.t3tools.T3Code.desktop.png"; + const iconSource = "/tmp/.mount_T3/resources/app.asar/apps/desktop/prod-resources/icon.png"; + const iconPath = "/xdg/icons/com.t3tools.T3Code.desktop.png"; + const iconBytes = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); + readFileSyncMock.mockImplementation((path: string) => { + if (path === iconSource) return iconBytes; + return "{}"; }); setDesktopNameMock.mockImplementation((name: string) => { desktopName = name; }); - writeFileSyncMock.mockImplementation((path: string, contents: string) => { - if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = contents; + writeFileSyncMock.mockImplementation((path: string, contents: string | Buffer) => { + if (path === "/xdg/applications/com.t3tools.T3Code.desktop") desktopEntry = String(contents); + if (path === iconPath) iconInstalled = Buffer.compare(Buffer.from(contents), iconBytes) === 0; }); return Effect.scoped( @@ -166,7 +171,12 @@ describe("DesktopPreReadyPlatform", () => { identity.desktopEntry ?? "", "Icon=/xdg/icons/com.t3tools.T3Code.desktop.png", ); - assert.isTrue(identity.iconInstalled); + assert.equal( + copyFileSyncMock.mock.calls.length, + 0, + "icon must not be copied out of the app bundle", + ); + assert.isTrue(identity.iconInstalled, "icon must be written from the bundled bytes"); }), ).pipe(Effect.ensuring(Effect.sync(() => vi.unstubAllEnvs()))); }); diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.ts index ff8c97b8f8260..df8059133fc20 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.ts @@ -104,12 +104,15 @@ export const make = Effect.gen(function* () { if (iconPath !== undefined) { try { NodeFS.mkdirSync(NodePath.posix.dirname(iconPath), { recursive: true }); - NodeFS.copyFileSync( - NodePath.posix.join( - Electron.app.getAppPath(), - "apps/desktop/prod-resources/icon.png", - ), + // Electron's copyFileSync from app.asar extracts to a temp file it never deletes. + NodeFS.writeFileSync( iconPath, + NodeFS.readFileSync( + NodePath.posix.join( + Electron.app.getAppPath(), + "apps/desktop/prod-resources/icon.png", + ), + ), ); } catch {} } From 7315c60b956c1cb5a2d59bd96ff91d362618c8bb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:37:25 -0800 Subject: [PATCH 008/128] fix(server): a failed Claude wake dispatch no longer drops every later wake (#28173) --- .../Adapters/ClaudeAdapterV2.test.ts | 155 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 24 ++- .../ProviderContinuationService.test.ts | 39 +++++ .../ProviderContinuationService.ts | 2 + 4 files changed, 214 insertions(+), 6 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index cf728b4a95ad5..8048046a5927b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -13766,6 +13766,161 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("offers a later wake after an earlier wake's continuation dispatch failed", () => + Effect.scoped( + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const SECOND_SUMMARY = 'Background command "Second sleep" completed (exit code 0)'; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-dispatch-failed-1"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + description: "Second sleep", + uuid: "00000000-0000-4000-8000-000000000121", + }), + ); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + + // A failed dispatch never attaches the wake turn; clearIfCurrent is the only release. + const failed = harness.continuationRequests[0]!; + assert.isDefined(failed.clearIfCurrent); + yield* failed.clearIfCurrent!(); + + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + summary: SECOND_SUMMARY, + uuid: "00000000-0000-4000-8000-000000000123", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000124" }), + ); + assert.lengthOf(harness.continuationRequests, 2); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + + it.effect("keeps a newer wake latched when a stale continuation request is cleared", () => + Effect.scoped( + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-1"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + description: "Second sleep", + uuid: "00000000-0000-4000-8000-000000000131", + }), + ); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + yield* harness.awaitTerminal(2); + + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000133", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000134" }), + ); + assert.lengthOf(harness.continuationRequests, 2); + + yield* harness.continuationRequests[0]!.clearIfCurrent!(); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeAssistant, uuid: "00000000-0000-4000-8000-000000000135" }), + ); + assert.lengthOf(harness.continuationRequests, 2); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect.each([true, false])( "carries a rejected wake rate limit into the continuation failure (event=%s)", (standaloneEvent) => diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index a74deff510958..8b9666ce3d6aa 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5569,7 +5569,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return { kind: "command", label, outcome }; } }); - const requestedContinuations = yield* Ref.make(new Set()); + const requestedContinuations = yield* Ref.make(new Map()); const absorbedWakes = yield* Ref.make(new Set()); const heldProposedPlansByToolUseId = new Map(); const runtimeContext = yield* Effect.context(); @@ -6052,7 +6052,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (!current.has(nativeThreadId)) { return current; } - const updated = new Set(current); + const updated = new Map(current); updated.delete(nativeThreadId); return updated; }); @@ -8911,12 +8911,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); return; } + const nativeThreadId = wakeInput.nativeThreadId; + const latch = Symbol(nativeThreadId); const shouldOffer = yield* Ref.modify(requestedContinuations, (current) => { - if (current.has(wakeInput.nativeThreadId)) { + if (current.has(nativeThreadId)) { return [false, current] as const; } - const updated = new Set(current); - updated.add(wakeInput.nativeThreadId); + const updated = new Map(current); + updated.set(nativeThreadId, latch); return [true, updated] as const; }); if (!shouldOffer) { @@ -8939,6 +8941,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( driver: CLAUDE_PROVIDER, detail, ...(notification === null ? {} : { notification }), + // A process reset can clear and re-latch this thread; a stale failure must not release the newer wake. + clearIfCurrent: () => + Ref.update(requestedContinuations, (current) => { + if (current.get(nativeThreadId) !== latch) { + return current; + } + const updated = new Map(current); + updated.delete(nativeThreadId); + return updated; + }), }); }); @@ -11760,7 +11772,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* attachTurn; const drained = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? []; yield* Ref.update(requestedContinuations, (current) => { - const updated = new Set(current); + const updated = new Map(current); updated.delete(nativeThreadId); return updated; }); diff --git a/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts b/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts index 2d52bf8b15b5c..1827700ca16c5 100644 --- a/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderContinuationService.test.ts @@ -1,5 +1,6 @@ import { assert, describe, it } from "@effect/vitest"; import { + CommandId, MessageId, ProjectId, ProviderDriverKind, @@ -22,6 +23,7 @@ import * as TestClock from "effect/testing/TestClock"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; +import * as Orchestrator from "./Orchestrator.ts"; import * as ProviderContinuationService from "./ProviderContinuationService.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; @@ -418,6 +420,43 @@ describe("ProviderContinuationService", () => { }, ); + it.effect( + "clears a sticky continuation offer when a non-delegated wake dispatch fails generically", + () => { + return Effect.gen(function* () { + const cleared = yield* Deferred.make(); + const layerThreads = Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadRecords: () => Effect.succeed(projection), + dispatch: (command) => + Effect.fail( + new Orchestrator.OrchestratorDispatchError({ + commandId: CommandId.make(String(command.commandId)), + commandType: command.type, + cause: new Error("SQLITE_FULL: database or disk is full"), + }), + ), + }); + const layerWorker = ProviderContinuationService.layer.pipe( + Layer.provide( + Layer.mergeAll(IdAllocator.layer, ProviderContinuationRequests.layer, layerThreads), + ), + ); + + yield* Effect.gen(function* () { + const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; + yield* requests.offer({ + ...request(), + clearIfCurrent: () => Deferred.succeed(cleared, undefined), + }); + yield* Deferred.await(cleared); + }).pipe( + Effect.provide(Layer.merge(ProviderContinuationRequests.layer, layerWorker)), + Effect.scoped, + ); + }); + }, + ); + it.effect( "drops stopped and disposed delegated completions instead of reviving them after recovery", () => { diff --git a/apps/server/src/orchestration-v2/ProviderContinuationService.ts b/apps/server/src/orchestration-v2/ProviderContinuationService.ts index 1fe30ee0645c8..ac414413ca3bc 100644 --- a/apps/server/src/orchestration-v2/ProviderContinuationService.ts +++ b/apps/server/src/orchestration-v2/ProviderContinuationService.ts @@ -274,6 +274,8 @@ export const layer = Layer.effectDiscard( ), Effect.forkScoped, ); + } else if (request.clearIfCurrent !== undefined) { + yield* request.clearIfCurrent(); } }), ), From e5b5da3a7cd629c931ae71306595ae121dc2360b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:37:31 -0800 Subject: [PATCH 009/128] fix(web): reopening a guide with many cached diff pages no longer crashes (#27550) --- .../guide/useGuideDiffFiles.browser.test.tsx | 79 ++++++++++++++++++- .../pullRequest/guide/useGuideDiffFiles.ts | 44 +++++------ 2 files changed, 99 insertions(+), 24 deletions(-) diff --git a/apps/web/src/components/pullRequest/guide/useGuideDiffFiles.browser.test.tsx b/apps/web/src/components/pullRequest/guide/useGuideDiffFiles.browser.test.tsx index 8a92f2c2bf0d0..9780ac0422743 100644 --- a/apps/web/src/components/pullRequest/guide/useGuideDiffFiles.browser.test.tsx +++ b/apps/web/src/components/pullRequest/guide/useGuideDiffFiles.browser.test.tsx @@ -6,7 +6,7 @@ import { expect, it, vi } from "vite-plus/test"; import { act, render } from "../../../../test/render"; const state = vi.hoisted(() => ({ - pages: new Map>>(), + pages: new Map>>(), })); vi.mock("~/state/pullRequests", () => ({ pullRequestEnvironment: { @@ -33,6 +33,10 @@ function Probe({ wantedPaths }: { wantedPaths: string[] }) { ); } +function setup() { + state.pages.clear(); +} + function page(path: string, value: string, nextCursor: string | null): PullRequestDiffResult { return { patch: `diff --git a/${path} b/${path}\n--- a/${path}\n+++ b/${path}\n@@ -1 +1 @@\n-old\n+${value}\n`, @@ -46,7 +50,7 @@ it.each([ { name: "ends before a newly added file", path: "other.ts", cursor: null }, { name: "has an obsolete next cursor", path: "other.ts", cursor: "old-next" }, ])("waits for a cached page that $name to settle", async ({ path, cursor }) => { - state.pages.clear(); + setup(); await using stack = new AsyncDisposableStack(); const registry = stack.adopt(AtomRegistry.make(), (value) => value.dispose()); const first = Atom.make>( @@ -68,3 +72,74 @@ it.each([ await act(() => registry.set(first, AsyncResult.success(page("wanted.ts", "FRESH", null)))); expect(result()).toEqual({ loading: false, files: [["wanted.ts", "FRESH\n"]] }); }); + +it("walks more cached pages than React's re-render limit and stops at the requested file", async () => { + setup(); + await using stack = new AsyncDisposableStack(); + const registry = stack.adopt(AtomRegistry.make(), (value) => value.dispose()); + const pageCount = 30; + for (let index = 0; index < pageCount; index++) { + const last = index === pageCount - 1; + state.pages.set( + index === 0 ? null : `cursor-${index}`, + Atom.make>( + AsyncResult.success( + page(last ? "wanted.ts" : `file-${index}.ts`, "FOUND", `cursor-${index + 1}`), + ), + ), + ); + } + let pastPageReads = 0; + state.pages.set( + `cursor-${pageCount}`, + Atom.make((): AsyncResult.AsyncResult => { + pastPageReads++; + return AsyncResult.initial(true); + }), + ); + await using screen = await render( + + + , + ); + const result = JSON.parse(screen.container.querySelector("output")!.textContent!); + expect(result.loading).toBe(false); + expect(result.files).toContainEqual(["wanted.ts", "FOUND\n"]); + expect(pastPageReads).toBe(0); +}); + +it("waits for a later cached page that is still refreshing", async () => { + setup(); + await using stack = new AsyncDisposableStack(); + const registry = stack.adopt(AtomRegistry.make(), (value) => value.dispose()); + state.pages.set( + null, + Atom.make>( + AsyncResult.success(page("first.ts", "FIRST", "cursor-1")), + ), + ); + const second = Atom.make>( + AsyncResult.success(page("other.ts", "STALE", "old-next"), { waiting: true }), + ); + state.pages.set("cursor-1", second); + state.pages.set( + "old-next", + Atom.make>(AsyncResult.initial(true)), + ); + await using screen = await render( + + + , + ); + const result = () => JSON.parse(screen.container.querySelector("output")!.textContent!); + expect(result()).toEqual({ loading: true, files: [["first.ts", "FIRST\n"]] }); + + await act(() => registry.set(second, AsyncResult.success(page("wanted.ts", "FRESH", null)))); + expect(result()).toEqual({ + loading: false, + files: [ + ["first.ts", "FIRST\n"], + ["wanted.ts", "FRESH\n"], + ], + }); +}); diff --git a/apps/web/src/components/pullRequest/guide/useGuideDiffFiles.ts b/apps/web/src/components/pullRequest/guide/useGuideDiffFiles.ts index 21765c68d18e8..e0e3501fcf07c 100644 --- a/apps/web/src/components/pullRequest/guide/useGuideDiffFiles.ts +++ b/apps/web/src/components/pullRequest/guide/useGuideDiffFiles.ts @@ -1,6 +1,8 @@ import type { FileDiffMetadata } from "@pierre/diffs"; import type { EnvironmentId, PullRequestRef } from "@t3tools/contracts"; -import { useState } from "react"; +import { RegistryContext } from "@effect/atom-react"; +import { AsyncResult } from "effect/reactivity"; +import { useContext, useState } from "react"; import { getRenderablePatch, resolveFileDiffPath } from "~/lib/diffRendering"; import { pullRequestEnvironment } from "~/state/pullRequests"; @@ -39,35 +41,33 @@ export function useGuideDiffFiles({ }); const current: LoadedDiff = loaded.key === key ? loaded : { key, cursor: null, done: false, files: NO_FILES, folded: null }; - const missing = wantedPaths.some((path) => !current.files.has(path)); - const loading = missing && !current.done; - const query = useEnvironmentQuery( - loading - ? pullRequestEnvironment.diff({ - environmentId, - input: { ...reference, ...(current.cursor === null ? {} : { cursor: current.cursor }) }, - }) - : null, - ); + const registry = useContext(RegistryContext); + const isMissing = (diff: LoadedDiff) => wantedPaths.some((path) => !diff.files.has(path)); + const pageAtom = (cursor: string | null) => + pullRequestEnvironment.diff({ + environmentId, + input: { ...reference, ...(cursor === null ? {} : { cursor }) }, + }); + const loading = isMissing(current) && !current.done; + const query = useEnvironmentQuery(loading ? pageAtom(current.cursor) : null); - const data = query.data; - if (data !== null && !query.isPending && !current.done && current.folded !== data) { + // One update for every settled page: an update per page trips React's re-render limit. + let next = current; + let data = query.isPending ? null : query.data; + while (data !== null && !next.done && next.folded !== data && isMissing(next)) { const parsed = getRenderablePatch( data.patch, - `pull-request-guide:${key}:${current.cursor ?? "first"}`, + `pull-request-guide:${key}:${next.cursor ?? "first"}`, ); - const files = new Map(current.files); + const files = new Map(next.files); if (parsed?.kind === "files") { for (const file of parsed.files) files.set(resolveFileDiffPath(file), file); } - setLoaded({ - key, - cursor: data.nextCursor, - done: data.nextCursor === null, - files, - folded: data, - }); + next = { key, cursor: data.nextCursor, done: data.nextCursor === null, files, folded: data }; + const result = next.done || !isMissing(next) ? null : registry.get(pageAtom(next.cursor)); + data = result === null || result.waiting ? null : AsyncResult.getOrElse(result, () => null); } + if (next !== current) setLoaded(next); return { files: current.files, From ed57b9b5ec7e7bbe9a25da1d8883f218eaee1b75 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:38:07 -0800 Subject: [PATCH 010/128] fix(server): a follow-up to a finished remote task is a new task that wakes the parent (#26776) --- apps/server/src/mcp/McpToolAccess.ts | 46 ++- .../src/mcp/toolkits/orchestrator/handlers.ts | 20 +- .../src/mcp/toolkits/orchestrator/tools.ts | 5 +- .../src/orchestration-v2/CommandPolicy.ts | 10 + .../src/orchestration-v2/Orchestrator.ts | 22 +- apps/server/src/peer/PeerForwarding.test.ts | 5 +- apps/server/src/peer/RemoteDelegation.test.ts | 303 +++++++++++++++++- apps/server/src/peer/RemoteDelegation.ts | 135 +++++++- 8 files changed, 516 insertions(+), 30 deletions(-) diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index b82d9bb5ae59c..f96a38d6d7341 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -46,6 +46,7 @@ const refuseOutsideConstruction = (token: symbol) => { let declare: ( handle: (params: P) => Effect.Effect, remote: RemoteCheck

| undefined, + forwarded?: Forwarded, ) => Declaration<(params: P) => Effect.Effect>; /** @@ -58,6 +59,16 @@ type RemoteCheck

= ( ) => Effect.Effect>; let remoteCheckOf: (declaration: Declaration) => RemoteCheck | undefined; +/** What a call answered in a linked environment does here before it returns. */ +type Forwarded = ( + params: P, + environmentId: EnvironmentId, + result: A, +) => Effect.Effect; +let forwardedOf: ( + declaration: Declaration, +) => Forwarded | undefined; + type CheckedHandlerOf = D extends Declaration ? Handler : never; interface CheckedHandler extends Struct.Lambda { @@ -74,19 +85,29 @@ let handlersLayer: , EX, RX>( export class Declaration { readonly #handle: Handler; readonly #remote: RemoteCheck | undefined; + readonly #forwarded: Forwarded | undefined; private constructor( token: typeof builtHere, handle: Handler, remote: RemoteCheck | undefined, + forwarded: Forwarded | undefined, ) { refuseOutsideConstruction(token); this.#handle = handle; this.#remote = remote; + this.#forwarded = forwarded; } static { - declare = (handle, remote) => new Declaration(builtHere, handle, remote); + declare = (handle, remote, forwarded) => + new Declaration( + builtHere, + handle, + remote, + forwarded as Forwarded | undefined, + ); checkedHandler = Struct.lambda((declaration) => declaration.#handle); remoteCheckOf = (declaration) => declaration.#remote; + forwardedOf = (declaration) => declaration.#forwarded; } } @@ -281,6 +302,20 @@ export const either = ( ); }; +/** + * `declaration`, whose result from a linked environment then goes through + * `forwarded` here, for what this environment records about the call. + */ +export const afterForwarding = ( + declaration: Declaration<(params: P) => Effect.Effect>, + forwarded: Forwarded, +) => + declare( + checkedHandler(declaration) as (params: P) => Effect.Effect, + remoteCheckOf(declaration) as RemoteCheck

| undefined, + forwarded, + ); + const fullAccessRequired = "Changing projects or environment settings needs a live full-access/default calling thread or a full-access client."; @@ -387,6 +422,9 @@ const routed = Effect.fn("McpToolAccess.routed")(function* , never> + | undefined; if (remote === undefined) return yield* Effect.die( `${name} takes a linked environment, but it acts as its calling thread, which is here.`, @@ -402,7 +440,11 @@ const routed = Effect.fn("McpToolAccess.routed")(function* )(params); if (Option.isNone(forwarding)) return yield* linksUnavailable; - return yield* forwarding.value.call(scope, tool, target, { ...params, environmentId }); + const result = yield* forwarding.value.call(scope, tool, target, { + ...params, + environmentId, + }); + return forwarded === undefined ? result : yield* forwarded(params, target, result); }); } return handlers as Toolkit.HandlersFrom; diff --git a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts index 3db297bc0d303..1f4ee4a57a6f5 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/handlers.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/handlers.ts @@ -5,6 +5,7 @@ import * as Effect from "effect/Effect"; import * as PeerForwarding from "../../../peer/PeerForwarding.ts"; import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts"; import * as PeerLinks from "../../../peer/PeerLinks.ts"; +import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts"; import { readCaller } from "../../threadAccess.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as McpToolAccess from "../../McpToolAccess.ts"; @@ -168,13 +169,22 @@ const handlers = { return yield* service.update(scope, input); }), ), - t3_thread_send: McpToolAccess.writesThreads( - (input) => [input.threadId], - (input) => + t3_thread_send: McpToolAccess.afterForwarding( + McpToolAccess.writesThreads( + (input) => [input.threadId], + (input) => + Effect.gen(function* () { + const scope = yield* McpInvocationContext.McpInvocationContext; + const service = yield* OrchestratorMcpService.OrchestratorMcpService; + return yield* service.sendToThread(scope, input); + }), + ), + // There the thread's parent is here, so only this side can make a follow-up a task. + (input, environmentId, sent) => Effect.gen(function* () { const scope = yield* McpInvocationContext.McpInvocationContext; - const service = yield* OrchestratorMcpService.OrchestratorMcpService; - return yield* service.sendToThread(scope, input); + const remote = yield* RemoteDelegation.RemoteDelegation; + return yield* remote.followUp(scope, environmentId, input, sent); }), ), t3_thread_wait: McpToolAccess.reads((input) => diff --git a/apps/server/src/mcp/toolkits/orchestrator/tools.ts b/apps/server/src/mcp/toolkits/orchestrator/tools.ts index d1c916f2caefb..38d8fb4e0ada5 100644 --- a/apps/server/src/mcp/toolkits/orchestrator/tools.ts +++ b/apps/server/src/mcp/toolkits/orchestrator/tools.ts @@ -46,6 +46,7 @@ import * as ThreadManagementService from "../../../orchestration-v2/ThreadManage import * as PeerForwarding from "../../../peer/PeerForwarding.ts"; import * as PeerLinkRequests from "../../../peer/PeerLinkRequests.ts"; import * as PeerLinks from "../../../peer/PeerLinks.ts"; +import * as RemoteDelegation from "../../../peer/RemoteDelegation.ts"; import * as McpInvocationContext from "../../McpInvocationContext.ts"; import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts"; import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts"; @@ -63,6 +64,8 @@ const linkingDependencies = [ PeerLinkRequests.PeerLinkRequests, PeerLinks.PeerLinks, ]; +/** A send there may record a follow-up to a remote task. */ +const sendDependencies = [...dependencies, RemoteDelegation.RemoteDelegation]; const threadMetadataDependencies = [ McpInvocationContext.McpInvocationContext, ThreadManagementService.ThreadManagementService, @@ -279,7 +282,7 @@ const ThreadSendTool = Tool.make("t3_thread_send", { success: OrchestratorMcpThreadSendResult, failure: OrchestratorMcpFailure, failureMode: "return", - dependencies, + dependencies: sendDependencies, }) .annotate(Tool.Title, "Send to a T3 thread") .annotate(Tool.Destructive, true) diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 02f329e536feb..cd56460369bd6 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -10,6 +10,7 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -125,6 +126,15 @@ export function isActiveRun(run: OrchestrationV2Run): boolean { ); } +/** The run a follow-up to a finished child binds to: the latest active one, else the last that ran. */ +export function followUpOwnerRun( + runs: ReadonlyArray, +): OrchestrationV2Run | null { + return ( + runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ?? latestExecutedRun(runs) + ); +} + function providerTurnCapabilities( projection: OrchestrationV2ThreadProjection, run: OrchestrationV2Run, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 44fe331d05161..295bdde820e61 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -107,6 +107,7 @@ import { import { CheckpointServiceV2 } from "./CheckpointService.ts"; import { CommandPolicyV2, + followUpOwnerRun, goalCommandStopsActiveRun, isActiveRun, isNativeMaintenanceCommand, @@ -8952,9 +8953,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio task.id === (child.forkedFrom?.type === "node" ? child.forkedFrom.nodeId : undefined), ); if (original === undefined || original.result === null) return; - const owner = - parent.runs.filter(isActiveRun).toSorted((a, b) => b.ordinal - a.ordinal)[0] ?? - latestExecutedRun(parent.runs); + const owner = followUpOwnerRun(parent.runs); if (owner === null || owner.rootNodeId === null) return; const now = message.createdAt; const adapter = yield* providerAdapters.get(run.providerInstanceId); @@ -9072,7 +9071,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio events: Ref.Ref>, ) { const parentProjection = yield* projectionStore - .getThreadRecords(command.parentThreadId, ["runs", "providerTurns", "attempts"]) + .getThreadRecords(command.parentThreadId, ["runs", "providerTurns", "attempts", "subagents"]) .pipe( Effect.mapError( (cause) => new OrchestratorProjectionError({ threadId: command.parentThreadId, cause }), @@ -9081,7 +9080,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const parentRun = parentProjection.runs.find( (candidate) => candidate.id === command.parentRunId, ); - if (parentRun === undefined || !isActiveRun(parentRun) || parentRun.rootNodeId === null) { + // A follow-up to a finished task there binds as one to a child here does. + const followsUp = parentProjection.subagents.some( + (task) => + task.result !== null && + task.remoteChild?.environmentId === command.remoteChild.environmentId && + task.remoteChild.threadId === command.remoteChild.threadId, + ); + if ( + parentRun === undefined || + (followsUp + ? parentRun.id !== followUpOwnerRun(parentProjection.runs)?.id + : !isActiveRun(parentRun)) || + parentRun.rootNodeId === null + ) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index 4e15b02d04e53..857c1049b56a4 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -314,7 +314,10 @@ const makeLaptop = Effect.gen(function* () { Layer.mock(ProjectCloneTracker.ProjectCloneTracker)({}), Layer.mock(SecretRequests.SecretRequests)({}), ServerSettings.layerTest(), - Layer.mock(RemoteDelegation.RemoteDelegation)({}), + // No thread here delegated to the box, so a send there is no follow-up. + Layer.mock(RemoteDelegation.RemoteDelegation)({ + followUp: (_scope, _environmentId, _request, sent) => Effect.succeed(sent), + }), Layer.mock(PeerLinkRequests.PeerLinkRequests)({}), ), ), diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index cb46d63ab6238..1f97ae6023d09 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -31,6 +31,7 @@ import * as Schedule from "effect/Schedule"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as Tracer from "effect/Tracer"; +import * as TestClock from "effect/testing/TestClock"; import type * as SqlClient from "effect/sql/SqlClient"; import { McpSchema, McpServer } from "effect/ai"; @@ -100,6 +101,10 @@ interface BoxThread { readonly laterError: Ref.Ref; /** A later run's reply, after the task's own, as a follow-up message would leave. */ readonly laterReply: Ref.Ref; + /** The reply of a run queued there behind the later one; once set, the thread settles on it. */ + readonly queuedReply: Ref.Ref; + /** A run there restarted, which its continuation finished with this reply. */ + readonly restart: Ref.Ref<{ readonly of: RunId; readonly reply: string } | null>; /** The model the provider there reported running the task's run. */ readonly executedModel: Ref.Ref; /** The run each wait asked for, in order. */ @@ -120,6 +125,8 @@ interface BoxThread { /** Completed on the first interrupt there. */ readonly interruptedOnce: Deferred.Deferred; readonly finished: Deferred.Deferred; + /** Ends the later run a message sent there started, for a wait pinned to it. */ + readonly laterFinished: Deferred.Deferred; /** While set, reading the thread there waits: completed once a read starts, released by `releaseRead`. */ readonly holdRead: Ref.Ref; readonly readStarted: Deferred.Deferred; @@ -147,6 +154,8 @@ const makeBoxThread = Effect.gen(function* () { error: yield* Ref.make(null), laterError: yield* Ref.make(null), laterReply: yield* Ref.make(null), + queuedReply: yield* Ref.make(null), + restart: yield* Ref.make<{ readonly of: RunId; readonly reply: string } | null>(null), executedModel: yield* Ref.make(null), waitedFor: yield* Ref.make>([]), nested: yield* Ref.make(false), @@ -158,6 +167,7 @@ const makeBoxThread = Effect.gen(function* () { runless: yield* Ref.make(false), interruptedOnce: yield* Deferred.make(), finished: yield* Deferred.make(), + laterFinished: yield* Deferred.make(), holdRead: yield* Ref.make(false), readStarted: yield* Deferred.make(), releaseRead: yield* Deferred.make(), @@ -208,6 +218,8 @@ const serveBox = (thread: BoxThread) => { const boxRunId = RunId.make("run:box"); const boxLaterRunId = RunId.make("run:box-later"); +const boxQueuedRunId = RunId.make("run:box-queued"); +const continuationOf = (runId: RunId) => RunId.make(`${runId}:restarted`); const boxToolkitLayer = (thread: BoxThread) => { const runId = boxRunId; @@ -278,6 +290,37 @@ const boxToolkitLayer = (thread: BoxThread) => { threadId: input.threadId, }); } + // The queued run's own task stays open while the follow-up ahead of it settles. + if (input.runId === boxQueuedRunId) return yield* Effect.never; + if (input.runId === boxLaterRunId) { + const laterDone = yield* Deferred.await(thread.laterFinished).pipe( + Effect.timeoutOption(input.timeoutMs), + ); + // Settled, the thread's answer is the run queued behind it, once there is one. + const queued = + Option.isSome(laterDone) && + input.untilDelegatedWorkSettled === true && + (yield* Ref.get(thread.queuedReply)) !== null; + // A restarted run is reported as its continuation, as the box follows the chain. + const restarted = (yield* Ref.get(thread.restart))?.of; + const latest = (runId: RunId) => (runId === restarted ? continuationOf(runId) : runId); + return { + threadId: input.threadId, + run: { + id: latest(boxLaterRunId), + status: Option.isSome(laterDone) ? "completed" : "running", + } as OrchestrationV2Run, + timedOut: Option.isNone(laterDone), + ...(queued + ? { + resultRun: { + id: latest(boxQueuedRunId), + status: "completed", + } as OrchestrationV2Run, + } + : {}), + }; + } const done = yield* Deferred.await(thread.finished).pipe( Effect.timeoutOption(input.timeoutMs), ); @@ -319,8 +362,10 @@ const boxToolkitLayer = (thread: BoxThread) => { } const reply = yield* Ref.get(thread.reply); const later = yield* Ref.get(thread.laterReply); + const queued = yield* Ref.get(thread.queuedReply); const error = yield* Ref.get(thread.error); const laterError = yield* Ref.get(thread.laterError); + const restart = yield* Ref.get(thread.restart); // One item per page, with errors available only in the activity view. const replies = [ ...(reply === null @@ -356,6 +401,26 @@ const boxToolkitLayer = (thread: BoxThread) => { type: "error", }, ]), + ...(queued === null + ? [] + : [ + { + id: TurnItemId.make("item:queued-reply"), + runId: boxQueuedRunId, + text: queued, + type: "assistant_message", + }, + ]), + ...(restart === null + ? [] + : [ + { + id: TurnItemId.make("item:restarted-reply"), + runId: continuationOf(restart.of), + text: restart.reply, + type: "assistant_message", + }, + ]), ].map((entry, position) => ({ ...entry, position })); const visible = options.itemId === undefined @@ -424,10 +489,11 @@ const boxToolkitLayer = (thread: BoxThread) => { stopDelegatedTasks: (input) => recordStop(input.commandId, "delegated-tasks"), sendToThread: (input) => Ref.update(thread.sent, (seen) => [...seen, input.text]).pipe( - Effect.as({ - run: { id: boxLaterRunId, status: "running" }, - delivery: "started", - } as never), + Effect.as( + (input.mode === "queue" + ? { run: { id: boxQueuedRunId, status: "queued" }, delivery: "queued" } + : { run: { id: boxLaterRunId, status: "running" }, delivery: "started" }) as never, + ), ), }); const layerBoxLaunches = Layer.mock(ThreadLaunch.ThreadLaunchService)({ @@ -1702,13 +1768,14 @@ it.effect("stopping the parent stops follow-up work on a task there that has its result: "All green.", }); - // The parent sends the thread there a follow-up, which starts a run there. + // The parent sends the thread there a follow-up, which starts a run there as a new task. const sent = yield* a.call("t3_thread_send", { environmentId: box.environmentId, threadId: delegated.remoteChild.threadId, message: "Now run the slow suite too.", }); expect(sent.isError, JSON.stringify(sent.content)).toBe(false); + const followUpId = (sent.structuredContent as { taskId: NodeId }).taskId; expect(yield* Ref.get(thread.sent)).toEqual(["Now run the slow suite too."]); expect(yield* Ref.get(thread.interrupted)).toBe(0); @@ -1716,9 +1783,15 @@ it.effect("stopping the parent stops follow-up work on a task there that has its threadId: parentThreadId, commandId: CommandId.make("command:stop:laptop-parent-after-result"), }); - // The thread there is stopped as Stop does, and the task keeps its result. + // The thread there is stopped as Stop does, for each task, and the first keeps its result. const task = yield* stoppedThere(a, delegated.taskId); - expect(yield* Ref.get(thread.stops)).toEqual(["thread.stop", "delegated-tasks"]); + expect(yield* stoppedThere(a, followUpId, null)).toMatchObject({ status: "interrupted" }); + expect((yield* Ref.get(thread.stops)).toSorted()).toEqual([ + "delegated-tasks", + "delegated-tasks", + "thread.stop", + "thread.stop", + ]); expect(task).toMatchObject({ status: "completed", result: "All green." }); expect(yield* a.projections.getOpenRemoteDelegatedTasks).toEqual([]); @@ -1728,7 +1801,214 @@ it.effect("stopping the parent stops follow-up work on a task there that has its commandId: CommandId.make("command:stop:laptop-parent-again"), }); expect(yield* stoppedThere(a, delegated.taskId, 2)).toMatchObject({ status: "completed" }); - expect(yield* Ref.get(thread.interrupted)).toBe(2); + expect(yield* stoppedThere(a, followUpId, 1)).toMatchObject({ status: "interrupted" }); + expect(yield* Ref.get(thread.interrupted)).toBe(4); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect.each([ + { order: "sent", queuedFirst: false }, + // Concurrent sends may be recorded here in the opposite order they run there. + { order: "recorded out of order", queuedFirst: true }, +])( + "a follow-up there ends with its own reply, not one queued behind it ($order)", + ({ queuedFirst }) => + 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* a.remote.start(); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + yield* Ref.set(thread.reply, "All green."); + yield* Ref.set(thread.status, "completed"); + yield* Deferred.succeed(thread.finished, undefined); + yield* taskResult(a, delegated.taskId); + + const sendFollowUp = a.call("t3_thread_send", { + environmentId: box.environmentId, + threadId: delegated.remoteChild.threadId, + message: "Now run the slow suite too.", + }); + const sendQueued = a.call("t3_thread_send", { + environmentId: box.environmentId, + threadId: delegated.remoteChild.threadId, + message: "Then the flaky suite.", + mode: "queue", + }); + const [first, second] = queuedFirst + ? [sendQueued, sendFollowUp] + : [sendFollowUp, sendQueued]; + const firstSent = yield* first; + yield* TestClock.adjust("1 second"); + const secondSent = yield* second; + const [followUp, queued] = queuedFirst ? [secondSent, firstSent] : [firstSent, secondSent]; + const followUpId = (followUp.structuredContent as { taskId: NodeId }).taskId; + expect((queued.structuredContent as { taskId?: NodeId }).taskId).toBeDefined(); + + // The thread there settles on the queued run, after the follow-up's own run ended. + yield* Ref.set(thread.laterReply, "The slow suite passes too."); + yield* Ref.set(thread.queuedReply, "The flaky suite passes."); + yield* Deferred.succeed(thread.laterFinished, undefined); + expect(yield* taskResult(a, followUpId)).toMatchObject({ + status: "completed", + result: "The slow suite passes too.", + }); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect.each([ + { + restarted: "follow-up", + of: boxLaterRunId, + laterReply: "Running the slow suite…", + restartReply: "The slow suite passes too.", + queuedReply: "The flaky suite passes.", + }, + { + restarted: "queued", + of: boxQueuedRunId, + laterReply: "The slow suite passes too.", + restartReply: "The flaky suite passes.", + queuedReply: "Running the flaky suite…", + }, +])( + "a follow-up there ends with its own reply when the $restarted run is restarted", + ({ of, laterReply, restartReply, queuedReply }) => + 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* a.remote.start(); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + yield* Ref.set(thread.reply, "All green."); + yield* Ref.set(thread.status, "completed"); + yield* Deferred.succeed(thread.finished, undefined); + yield* taskResult(a, delegated.taskId); + + const followUp = yield* a.call("t3_thread_send", { + environmentId: box.environmentId, + threadId: delegated.remoteChild.threadId, + message: "Now run the slow suite too.", + }); + yield* a.call("t3_thread_send", { + environmentId: box.environmentId, + threadId: delegated.remoteChild.threadId, + message: "Then the flaky suite.", + mode: "queue", + }); + const followUpId = (followUp.structuredContent as { taskId: NodeId }).taskId; + + // The thread there settles on the queued run, after one of the two was restarted. + yield* Ref.set(thread.laterReply, laterReply); + yield* Ref.set(thread.queuedReply, queuedReply); + yield* Ref.set(thread.restart, { of, reply: restartReply }); + yield* Deferred.succeed(thread.laterFinished, undefined); + expect(yield* taskResult(a, followUpId)).toMatchObject({ + status: "completed", + result: "The slow suite passes too.", + }); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); + +it.effect("a follow-up sent after the parent's own run ended is still a task", () => + 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* a.remote.start(); + yield* linkTo(a.links, b, "full-access"); + yield* seedParent(a); + const delegated = yield* delegateToBox(a); + yield* Ref.set(thread.reply, "All green."); + yield* Ref.set(thread.status, "completed"); + yield* Deferred.succeed(thread.finished, undefined); + yield* taskResult(a, delegated.taskId); + + // The parent's turn ends, while a background agent of its own still holds its credential. + const now = yield* DateTime.now; + const projection = yield* a.orchestrator.getThreadProjection(parentThreadId); + const run = projection.runs.find((candidate) => candidate.id === parentRunId)!; + yield* a.sink.write({ + commandId: CommandId.make("command:seed:laptop-parent-ended"), + events: [ + { + id: EventId.make("event:seed-background-agent:laptop-parent"), + type: "provider-thread.updated", + threadId: parentThreadId, + driver, + providerInstanceId: instanceId, + occurredAt: now, + payload: { + ...projection.providerThreads[0]!, + pendingBackgroundTasks: [{ taskId: "native-agent", kind: "subagent" }], + updatedAt: now, + }, + }, + { + id: EventId.make("event:seed-run-ended:laptop-parent"), + type: "run.updated", + threadId: parentThreadId, + runId: parentRunId, + nodeId: parentRootNode, + providerInstanceId: instanceId, + occurredAt: now, + payload: { ...run, status: "completed", completedAt: now }, + }, + ], + }); + + const sent = yield* a.call("t3_thread_send", { + environmentId: box.environmentId, + threadId: delegated.remoteChild.threadId, + message: "Now run the slow suite too.", + }); + expect(sent.isError, JSON.stringify(sent.content)).toBe(false); + const followUp = sent.structuredContent as { taskId?: NodeId }; + expect(followUp.taskId, JSON.stringify(followUp)).toBeDefined(); + const tasks = (yield* a.orchestrator.getThreadProjection(parentThreadId)).subagents; + expect(tasks.find((task) => task.id === followUp.taskId)).toMatchObject({ + runId: parentRunId, + status: "running", + }); + + // Its run there ends with its own reply, and the parent wakes for it. + const wakes = ( + seen: ReadonlyArray, + ) => seen.filter((offer) => offer.threadId === parentThreadId).length; + const wokenBefore = wakes(yield* SubscriptionRef.get(offers)); + yield* Ref.set(thread.laterReply, "The slow suite passes too."); + yield* Deferred.succeed(thread.laterFinished, undefined); + expect(yield* taskResult(a, followUp.taskId!)).toMatchObject({ + status: "completed", + result: "The slow suite passes too.", + }); + const offered = yield* SubscriptionRef.changes(offers).pipe( + Stream.filter((seen) => wakes(seen) > wokenBefore), + Stream.runHead, + ); + expect(Option.isSome(offered)).toBe(true); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); @@ -1759,11 +2039,12 @@ it.effect("a delayed Stop acknowledgement leaves a newer Stop owed", () => }); yield* Deferred.await(thread.stopStarted); // Work starts after the first Stop landed there, but before its acknowledgement returns. - yield* a.call("t3_thread_send", { + const sent = yield* a.call("t3_thread_send", { environmentId: box.environmentId, threadId: delegated.remoteChild.threadId, message: "Run another check.", }); + const followUpId = (sent.structuredContent as { taskId: NodeId }).taskId; yield* a.threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: CommandId.make("command:stop:delayed-second"), @@ -1777,7 +2058,9 @@ it.effect("a delayed Stop acknowledgement leaves a newer Stop owed", () => status: "completed", result: "All green.", }); - expect(yield* Ref.get(thread.interrupted)).toBe(2); + // The follow-up the work became is stopped there too, as its own task. + expect(yield* stoppedThere(a, followUpId, null)).toMatchObject({ status: "interrupted" }); + expect(yield* Ref.get(thread.interrupted)).toBe(3); expect(yield* a.projections.getOpenRemoteDelegatedTasks).toEqual([]); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), diff --git a/apps/server/src/peer/RemoteDelegation.ts b/apps/server/src/peer/RemoteDelegation.ts index 1222f029eec51..cced5b0b4eb39 100644 --- a/apps/server/src/peer/RemoteDelegation.ts +++ b/apps/server/src/peer/RemoteDelegation.ts @@ -6,6 +6,8 @@ import { type OrchestratorMcpDelegateTaskInput, type OrchestratorMcpTaskCancelResult, type OrchestratorMcpThreadRun, + type OrchestratorMcpThreadSendInput, + type OrchestratorMcpThreadSendResult, type OrchestratorMcpThreadTimelineItem, type OrchestrationV2RemoteTaskChild, type OrchestrationV2Subagent, @@ -17,6 +19,7 @@ import { } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -34,6 +37,7 @@ import { resolveRuntimeMode, taskPrompt, } from "../mcp/delegatedTaskModes.ts"; +import { followUpOwnerRun } from "../orchestration-v2/CommandPolicy.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; @@ -79,6 +83,18 @@ export class RemoteDelegation extends Context.Service< }; }, ) => Effect.Effect<{ readonly taskId: NodeId }, OrchestratorMcpFailure>; + /** + * A `t3_thread_send` there that started or queued a run on the thread of + * one of this thread's tasks that has its result: like a follow-up to a + * finished child here, that run is a new task, whose id the send returns. + * Any other send is returned as it came. + */ + readonly followUp: ( + scope: McpInvocationContext.McpInvocationScope, + environmentId: EnvironmentId, + request: Pick, + sent: OrchestratorMcpThreadSendResult, + ) => Effect.Effect; /** * Stops the task's thread there, then completes it here as cancelled. A * task that already has its result keeps it; its thread there is still @@ -359,6 +375,90 @@ const make = Effect.gen(function* () { }, ); + const followUp: RemoteDelegation["Service"]["followUp"] = Effect.fn("RemoteDelegation.followUp")( + function* (scope, environmentId, request, sent) { + // A steer joins a run that is already some task's, or no one's. + if (scope.thread === undefined || (sent.delivery !== "started" && sent.delivery !== "queued")) + return sent; + const parentThreadId = scope.thread.threadId; + const parent = yield* threads + .getThreadRecords(parentThreadId, ["runs", "subagents"]) + .pipe(Effect.orElseSucceed(() => undefined)); + const isThere = (task: OrchestrationV2Subagent) => + task.remoteChild?.environmentId === environmentId && + task.remoteChild.threadId === sent.threadId; + const finished = parent?.subagents.find((task) => isThere(task) && task.result !== null); + // Bound as a follow-up here is: a background caller's foreground run may have ended. + const parentRun = parent === undefined ? null : followUpOwnerRun(parent.runs); + if ( + finished?.remoteChild === undefined || + finished.model === null || + parentRun === null || + parentRun.rootNodeId === null + ) + return sent; + // The message id there is the send's, so a retry that reached the same send records once. + const commandId = CommandId.make( + `command:remote-followup:${encodeURIComponent(parentThreadId)}:${encodeURIComponent(environmentId)}:${encodeURIComponent(sent.messageId)}`, + ); + const recorded = yield* threads + .dispatch({ + type: "delegated_task.remote.request", + commandId, + parentThreadId, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId, + task: request.message, + ...(finished.title === null ? {} : { title: finished.title }), + driver: finished.driver, + modelSelection: { instanceId: finished.providerInstanceId, model: finished.model }, + remoteChild: { + environmentId, + threadId: sent.threadId, + label: finished.remoteChild.label, + runId: sent.runId, + }, + completionWake: "always", + }) + .pipe( + Effect.tapError((cause) => + Effect.logWarning("remote-delegation.followup-record-failed", { + parentThreadId, + cause, + }), + ), + Effect.mapError( + () => + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: + request.clientRequestId === undefined + ? "The message was sent, but its task was not recorded; read the thread for its answer instead of sending it again." + : "The message was sent, but its task was not recorded; send it again with the same clientRequestId to record it.", + }), + ), + ); + const taskEvent = recorded.storedEvents.find( + (stored) => stored.event.type === "subagent.updated", + ); + const taskId = + taskEvent?.event.type === "subagent.updated" + ? taskEvent.event.payload.id + : // A replayed request recorded the task the first time. + yield* threads.getThreadRecords(parentThreadId, ["subagents"]).pipe( + Effect.map( + ({ subagents }) => + subagents.find((task) => isThere(task) && task.remoteChild?.runId === sent.runId) + ?.id, + ), + Effect.orElseSucceed(() => undefined), + ); + if (taskId === undefined) return sent; + yield* followOne(parentThreadId, taskId).pipe(Effect.forkIn(followers)); + return { ...sent, taskId }; + }, + ); + /** * Completes `task` here with its thread there's final state. Each attempt is its own * command, so a failed one never blocks the next; a report refused because the task already @@ -563,7 +663,9 @@ const make = Effect.gen(function* () { ((task.status === "cancelled" || task.status === "interrupted") && remote.stoppedThere !== true) ) { - const key = remote.stopCount === undefined ? "stop" : `stop-${remote.stopCount}`; + const count = remote.stopCount === undefined ? "stop" : `stop-${remote.stopCount}`; + // Named for its run too: a follow-up task shares the thread there and counts its own stops. + const key = remote.runId === undefined ? count : `${count}:${remote.runId}`; yield* stopThere(scope, remote, key).pipe( // Its thread there now runs above what this side may touch, say // because the parent here was lowered since; no retry changes that. @@ -632,10 +734,31 @@ const make = Effect.gen(function* () { return yield* settled(parentThreadId, taskId); } if (!isTerminal(waited.status)) return false; - const resultRun = waited.resultRun ?? { - runId: remote.runId ?? waited.runId, - status: waited.status, - }; + // A later run's answer there may be another open follow-up's, or its restart, which no run id + // here names; concurrent sends may record here out of their order there. Then this task's + // answer is its own run's latest restart, the one waited on. + const sharedThread = + waited.resultRun !== undefined && + waited.resultRun.runId !== waited.runId && + (yield* threads.getThreadRecords(parentThreadId, ["subagents"]).pipe( + Effect.map(({ subagents }) => { + const recordedAt = subagents.find((task) => task.id === taskId)?.startedAt ?? null; + return subagents.some( + (other) => + other.id !== taskId && + other.remoteChild?.environmentId === remote.environmentId && + other.remoteChild.threadId === remote.threadId && + // One that settled before this was recorded ran before it there. + (recordedAt === null || + other.completedAt === null || + DateTime.isGreaterThan(other.completedAt, recordedAt)), + ); + }), + )); + const resultRun = + waited.resultRun !== undefined && !sharedThread + ? waited.resultRun + : { runId: waited.runId, status: waited.status }; const result = yield* lastReply(scope, remote, resultRun.runId, resultRun.status === "failed"); yield* complete( parentThreadId, @@ -793,7 +916,7 @@ const make = Effect.gen(function* () { }).pipe(Effect.ignoreCause({ log: true })), ); - return RemoteDelegation.of({ delegate, cancel, start }); + return RemoteDelegation.of({ delegate, followUp, cancel, start }); }); const isTerminal = (status: string) => From ea3e20a0e283ba3bf7c3d6004142d8f13b603319 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 15:39:18 -0800 Subject: [PATCH 011/128] fix(web): double-clicking another thread in the sidebar renames it instead of focusing its composer (#27287) --- apps/web/src/components/ChatView.tsx | 16 ++++----- ...FocusComposerOnThreadOpen.browser.test.tsx | 36 +++++++++++++++++++ .../chat/useFocusComposerOnThreadOpen.ts | 21 +++++++++++ 3 files changed, 63 insertions(+), 10 deletions(-) create mode 100644 apps/web/src/components/chat/useFocusComposerOnThreadOpen.browser.test.tsx create mode 100644 apps/web/src/components/chat/useFocusComposerOnThreadOpen.ts diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 36d4e7b63b548..f1fcdf2d77a4a 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -5,6 +5,7 @@ import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit"; import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays"; import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer"; +import { useFocusComposerOnThreadOpen } from "./chat/useFocusComposerOnThreadOpen"; import { configuredHostedAppUrl } from "../hostedPairing"; import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnouncement"; import { @@ -2116,16 +2117,11 @@ export default function ChatView(props: ChatViewProps) { setTimelineAnchor, }); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- schedules a frame to focus the composer DOM element when a thread opens with the terminal closed - useEffect(() => { - if (embedded || !activeThread?.id || terminalUiState.terminalOpen) return; - const frame = window.requestAnimationFrame(() => { - focusComposerStable(); - }); - return () => { - window.cancelAnimationFrame(frame); - }; - }, [activeThread?.id, embedded, focusComposerStable, terminalUiState.terminalOpen]); + useFocusComposerOnThreadOpen( + activeThread?.id, + !embedded && !terminalUiState.terminalOpen, + focusComposerStable, + ); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window focus listener that refocuses the composer after the window regains focus useEffect(() => { diff --git a/apps/web/src/components/chat/useFocusComposerOnThreadOpen.browser.test.tsx b/apps/web/src/components/chat/useFocusComposerOnThreadOpen.browser.test.tsx new file mode 100644 index 0000000000000..864f4c7079497 --- /dev/null +++ b/apps/web/src/components/chat/useFocusComposerOnThreadOpen.browser.test.tsx @@ -0,0 +1,36 @@ +import { useRef } from "react"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, fakeTimers, render } from "../../../test/render"; +import { useFocusComposerOnThreadOpen } from "./useFocusComposerOnThreadOpen"; + +function ThreadProbe(props: { threadId: string }) { + const composerRef = useRef(null); + useFocusComposerOnThreadOpen(props.threadId, true, () => composerRef.current?.focus()); + return ( + <> +

+ +
+