From 5d3d78ab932bc71535d3155dad7f68fef39c5c16 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 2 Nov 2026 22:56:36 -0800 Subject: [PATCH 01/22] feat(web): ask for a GitHub star when idle, and star in one click (#29922) Co-authored-by: Claude Opus 5.5 --- .../src/observability/RpcInstrumentation.ts | 1 + .../src/sourceControl/SourceControlSignIn.ts | 6 + apps/server/src/ws.ts | 1 + .../src/components/GitHubStarPrompt.test.ts | 106 +++++++++++++++++- apps/web/src/components/GitHubStarPrompt.tsx | 88 +++++++++++---- .../client-runtime/src/state/sourceControl.ts | 4 + .../contracts/src/clientRpcPermissions.ts | 1 + packages/contracts/src/rpc.ts | 9 ++ .../source-control-core/src/server/driver.ts | 2 + .../src/server/driver.test.ts | 20 +++- .../src/server/driver.ts | 29 ++++- 11 files changed, 231 insertions(+), 36 deletions(-) diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 7bb8bf8a34c18..17940b83717cf 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -142,6 +142,7 @@ const RPC_AGGREGATES = { [WS_METHODS.sourceControlSignInCancel]: "source-control", [WS_METHODS.sourceControlAppAccess]: "source-control", [WS_METHODS.sourceControlStarred]: "source-control", + [WS_METHODS.sourceControlStar]: "source-control", [WS_METHODS.projectCloneStart]: "source-control", [WS_METHODS.projectCloneCancel]: "source-control", [WS_METHODS.projectCloneRetry]: "source-control", diff --git a/apps/server/src/sourceControl/SourceControlSignIn.ts b/apps/server/src/sourceControl/SourceControlSignIn.ts index 3dd9ca03e2062..31f7837322fec 100644 --- a/apps/server/src/sourceControl/SourceControlSignIn.ts +++ b/apps/server/src/sourceControl/SourceControlSignIn.ts @@ -28,6 +28,7 @@ export class SourceControlSignIn extends Context.Service< ) => Effect.Effect; readonly access: (input: SourceControlAppAccessInput) => Effect.Effect; readonly starred: (input: SourceControlStarredInput) => Effect.Effect; + readonly star: (input: SourceControlStarredInput) => Effect.Effect; } >()("t3/sourceControl/SourceControlSignIn") {} @@ -70,6 +71,11 @@ const make = Effect.gen(function* () { .isRepositoryStarred; return isStarred === undefined ? false : yield* isStarred(input.host, input.repository); }), + star: Effect.fn("SourceControlSignIn.star")(function* (input) { + const star = drivers.find(({ driver }) => driver.kind === input.provider)?.instance + .starRepository; + return star === undefined ? false : yield* star(input.host, input.repository); + }), }); }); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 0016aa0063be4..492764c6ae5c8 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2749,6 +2749,7 @@ export const layerWsRpc = ( [WS_METHODS.sourceControlSignInCancel]: (input) => sourceControlSignIn.cancel(input), [WS_METHODS.sourceControlAppAccess]: (input) => sourceControlSignIn.access(input), [WS_METHODS.sourceControlStarred]: (input) => sourceControlSignIn.starred(input), + [WS_METHODS.sourceControlStar]: (input) => sourceControlSignIn.star(input), [WS_METHODS.projectCloneStart]: (input) => projectCloneTracker.start(input, { createProject: (project) => diff --git a/apps/web/src/components/GitHubStarPrompt.test.ts b/apps/web/src/components/GitHubStarPrompt.test.ts index 9dbe023b2d56f..f45229d5ce85e 100644 --- a/apps/web/src/components/GitHubStarPrompt.test.ts +++ b/apps/web/src/components/GitHubStarPrompt.test.ts @@ -3,29 +3,54 @@ import { describe, expect, it, vi } from "vite-plus/test"; import type { toastManager } from "./ui/toast"; -const { add, starred } = vi.hoisted(() => ({ +const { add, update, openExternal, commands, starred, page } = vi.hoisted(() => ({ add: vi.fn(), - starred: { value: false, failed: false, duringCheck: () => {} }, + update: vi.fn(), + openExternal: vi.fn(async (_url: string) => {}), + commands: { checkStarred: {}, star: {} }, + starred: { value: false, failed: false, starWorks: true, duringCheck: () => {} }, + page: { + focused: true, + activeElement: null as { matches: (selector: string) => boolean } | null, + events: new EventTarget(), + }, })); -vi.mock("./ui/toast", () => ({ toastManager: { add, close: vi.fn() } })); +vi.mock("./ui/toast", () => ({ toastManager: { add, update, close: vi.fn() } })); +vi.mock("../localApi", () => ({ readLocalApi: () => ({ shell: { openExternal } }) })); vi.mock("../rpc/atomRegistry", () => ({ appAtomRegistry: {} })); -vi.mock("../state/sourceControl", () => ({ sourceControlEnvironment: { checkStarred: {} } })); +vi.mock("../state/sourceControl", () => ({ sourceControlEnvironment: commands })); vi.mock("@t3tools/client-runtime/state/runtime", () => ({ - runAtomCommand: async () => { + runAtomCommand: async (_registry: unknown, command: unknown) => { + if (command === commands.star) return { _tag: "Success", value: starred.starWorks }; starred.duringCheck(); return starred.failed ? { _tag: "Failure" } : { _tag: "Success", value: starred.value }; }, })); const environmentId = EnvironmentId.make("environment-1"); +const IDLE_MS = 30_000; function setup({ sent = 0, writable = true, alreadyStarred = false } = {}) { add.mockReset(); + update.mockReset(); + openExternal.mockClear(); starred.value = alreadyStarred; starred.failed = false; + starred.starWorks = true; starred.duringCheck = () => {}; + page.focused = true; + page.activeElement = null; + page.events = new EventTarget(); const store = new Map([["t3code:github-star-prompt:sent", String(sent)]]); + vi.stubGlobal("document", { + hasFocus: () => page.focused, + get activeElement() { + return page.activeElement; + }, + }); vi.stubGlobal("window", { + addEventListener: page.events.addEventListener.bind(page.events), + removeEventListener: page.events.removeEventListener.bind(page.events), localStorage: { getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => { @@ -41,10 +66,48 @@ function setup({ sent = 0, writable = true, alreadyStarred = false } = {}) { async function startSession() { vi.resetModules(); const session = await import("./GitHubStarPrompt"); - return { send: () => session.recordPromptSent(environmentId) }; + return { + // Sends a prompt, then leaves the page idle long enough to ask. + send: async () => { + const sent = session.recordPromptSent(environmentId); + await vi.advanceTimersByTimeAsync(IDLE_MS); + await sent; + }, + sendWithoutWaiting: () => void session.recordPromptSent(environmentId), + }; } +// The toast's handlers ignore their click event. +const click = (props: unknown) => (props as { onClick: () => unknown }).onClick(); + describe("recordPromptSent", () => { + vi.useFakeTimers(); + + it("asks only after the focused page is idle", async () => { + setup({ sent: 5 }); + (await startSession()).sendWithoutWaiting(); + await vi.advanceTimersByTimeAsync(IDLE_MS - 1); + page.events.dispatchEvent(new Event("keydown")); + await vi.advanceTimersByTimeAsync(IDLE_MS - 1); + expect(add).not.toHaveBeenCalled(); + + page.focused = false; + await vi.advanceTimersByTimeAsync(IDLE_MS); + expect(add).not.toHaveBeenCalled(); + + page.focused = true; + page.activeElement = { matches: (selector) => selector.includes("iframe") }; + page.events.dispatchEvent(new Event("focus")); + await vi.advanceTimersByTimeAsync(IDLE_MS); + expect(add).not.toHaveBeenCalled(); + + page.activeElement = null; + page.events.dispatchEvent(new Event("pointerdown")); + await vi.advanceTimersByTimeAsync(IDLE_MS); + expect(add).toHaveBeenCalledOnce(); + vi.unstubAllGlobals(); + }); + it("asks after five prompts, once per session, and never again once closed", async () => { setup(); let session = await startSession(); @@ -101,4 +164,35 @@ describe("recordPromptSent", () => { expect(add).not.toHaveBeenCalled(); vi.unstubAllGlobals(); }); + it("stars on click, opens GitHub when starring fails, and asks for a click once the click expired", async () => { + setup({ sent: 5 }); + await (await startSession()).send(); + click(add.mock.lastCall?.[0].actionProps); + await vi.advanceTimersByTimeAsync(0); + expect(add.mock.lastCall?.[0].title).toBe("Thanks for the star!"); + expect(openExternal).not.toHaveBeenCalled(); + + setup({ sent: 5 }); + starred.starWorks = false; + await (await startSession()).send(); + click(add.mock.lastCall?.[0].actionProps); + await vi.advanceTimersByTimeAsync(0); + expect(openExternal).toHaveBeenCalledWith("https://github.com/pingdotgg/t3code"); + expect(update.mock.lastCall?.[1]).not.toMatchObject({ + actionProps: { children: "Open GitHub" }, + }); + + setup({ sent: 5 }); + starred.starWorks = false; + vi.stubGlobal("navigator", { userActivation: { isActive: false } }); + await (await startSession()).send(); + click(add.mock.lastCall?.[0].actionProps); + await vi.advanceTimersByTimeAsync(0); + const fallback = update.mock.lastCall?.[1]; + expect(fallback).toMatchObject({ actionProps: { children: "Open GitHub" } }); + expect(openExternal).not.toHaveBeenCalled(); + click(typeof fallback === "object" ? fallback.actionProps : undefined); + expect(openExternal).toHaveBeenCalledOnce(); + vi.unstubAllGlobals(); + }); }); diff --git a/apps/web/src/components/GitHubStarPrompt.tsx b/apps/web/src/components/GitHubStarPrompt.tsx index db8ddb4de2035..f79714d7a8939 100644 --- a/apps/web/src/components/GitHubStarPrompt.tsx +++ b/apps/web/src/components/GitHubStarPrompt.tsx @@ -14,6 +14,9 @@ const SENT_KEY = "t3code:github-star-prompt:sent"; const DISMISSED_KEY = "t3code:github-star-prompt:dismissed"; const REPOSITORY = "pingdotgg/t3code"; const PROMPTS_BEFORE_ASKING = 5; +const IDLE_MS = 30_000; +// User-driven actions (send, navigate, type, scroll) start with one of these; touch fires pointerdown. +const ACTIVITY_EVENTS = ["pointerdown", "keydown", "wheel", "focus"] as const; let shownThisSession = false; @@ -24,22 +27,32 @@ function dismiss() { } // Every close path, including both buttons, runs `onClose`, which saves the dismissal. -function showStarPrompt() { +function showStarPrompt(environmentId: EnvironmentId) { const close = () => toastManager.close(id); + const openInBrowser = () => { + close(); + void readLocalApi() + ?.shell.openExternal(`https://github.com/${REPOSITORY}`) + .catch(() => undefined); + }; + const starInPlace = async () => { + toastManager.update(id, { actionProps: { children: "Starring…", disabled: true } }); + if (await starRepository(environmentId)) { + close(); + toastManager.add({ type: "success", title: "Thanks for the star!", timeout: 4_000 }); + return; + } + // Browsers block new tabs once the click's activation expires; desktop opens through its bridge. + if (window.desktopBridge || navigator.userActivation?.isActive !== false) + return openInBrowser(); + toastManager.update(id, { actionProps: { children: "Open GitHub", onClick: openInBrowser } }); + }; const id = toastManager.add({ title: "Enjoying T3 Code?", description: "Give us a star on GitHub to let us know!", timeout: 0, onClose: dismiss, - actionProps: { - children: "Star on GitHub", - onClick: () => { - close(); - void readLocalApi() - ?.shell.openExternal(`https://github.com/${REPOSITORY}`) - .catch(() => undefined); - }, - }, + actionProps: { children: "Star on GitHub", onClick: () => void starInPlace() }, data: { actionLayout: "stacked-end", leadingIcon: , @@ -49,27 +62,59 @@ function showStarPrompt() { }); } +// Resolves after IDLE_MS without input while this window has focus. +function waitForIdle() { + return new Promise((resolve) => { + let timer: ReturnType | undefined; + const restart = () => { + clearTimeout(timer); + timer = setTimeout(() => { + // Input inside another app or an embedded frame never reaches us; the next focus restarts. + if (!document.hasFocus() || document.activeElement?.matches("iframe, webview")) return; + for (const type of ACTIVITY_EVENTS) window.removeEventListener(type, restart, true); + resolve(); + }, IDLE_MS); + }; + for (const type of ACTIVITY_EVENTS) { + window.addEventListener(type, restart, { capture: true, passive: true }); + } + restart(); + }); +} + // The server's GitHub account stands in for the user's; it may not be theirs on a shared server. +const starInput = (environmentId: EnvironmentId) => ({ + environmentId, + input: { + provider: SourceControlProviderKind.make("github"), + host: "github.com", + repository: REPOSITORY, + }, +}); + async function alreadyStarred(environmentId: EnvironmentId) { const result = await runAtomCommand( appAtomRegistry, sourceControlEnvironment.checkStarred, - { - environmentId, - input: { - provider: SourceControlProviderKind.make("github"), - host: "github.com", - repository: REPOSITORY, - }, - }, + starInput(environmentId), { label: "check GitHub star", reportFailure: false, reportDefect: false }, ); return result._tag === "Success" ? result.value : undefined; } +async function starRepository(environmentId: EnvironmentId) { + const result = await runAtomCommand( + appAtomRegistry, + sourceControlEnvironment.star, + starInput(environmentId), + { label: "star on GitHub", reportFailure: false, reportDefect: false }, + ); + return result._tag === "Success" && result.value; +} + /** * Counts a sent prompt. After more than five, asks once per session for a star until dismissed, - * unless the environment's GitHub account already starred the repo. + * unless the environment's GitHub account already starred the repo. Waits until the user is idle. */ export async function recordPromptSent(environmentId: EnvironmentId): Promise { if (shownThisSession) return; @@ -86,11 +131,12 @@ export async function recordPromptSent(environmentId: EnvironmentId): Promise( label: "environment-data:source-control:check-starred", tag: WS_METHODS.sourceControlStarred, }), + star: createEnvironmentRpcCommand(runtime, { + label: "environment-data:source-control:star", + tag: WS_METHODS.sourceControlStar, + }), repository: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:source-control:repository", tag: WS_METHODS.sourceControlLookupRepository, diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts index d3139f2eeff24..c2488226191dc 100644 --- a/packages/contracts/src/clientRpcPermissions.ts +++ b/packages/contracts/src/clientRpcPermissions.ts @@ -36,6 +36,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = { [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope, [WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope, [WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope, + [WS_METHODS.sourceControlStar]: AuthSourceControlWriteScope, // Signing in replaces the server's GitHub credential, as saving a token in Settings does. [WS_METHODS.sourceControlSignInStart]: AuthSettingsWriteScope, [WS_METHODS.sourceControlSignInWait]: AuthSettingsWriteScope, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 01989ff8a474f..737059e855768 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -595,6 +595,7 @@ export const WS_METHODS = { sourceControlSignInCancel: "sourceControl.signInCancel", sourceControlAppAccess: "sourceControl.appAccess", sourceControlStarred: "sourceControl.starred", + sourceControlStar: "sourceControl.star", projectCloneStart: "projectClone.start", projectCloneCancel: "projectClone.cancel", projectCloneRetry: "projectClone.retry", @@ -1252,6 +1253,13 @@ const WsSourceControlStarredRpc = Rpc.make(WS_METHODS.sourceControlStarred, { error: EnvironmentAuthorizationError, }); +// Stars the repository as the server's forge account. False when the forge refused or cannot star. +const WsSourceControlStarRpc = Rpc.make(WS_METHODS.sourceControlStar, { + payload: SourceControlStarredInput, + success: Schema.Boolean, + error: EnvironmentAuthorizationError, +}); + // Returns when the project exists and cloning starts; progress uses the subscription. const WsProjectCloneStartRpc = Rpc.make(WS_METHODS.projectCloneStart, { payload: ProjectCloneStartInput, @@ -2090,6 +2098,7 @@ export const WsRpcGroup = RpcGroup.make( WsSourceControlSignInCancelRpc, WsSourceControlAppAccessRpc, WsSourceControlStarredRpc, + WsSourceControlStarRpc, WsProjectCloneStartRpc, WsProjectCloneCancelRpc, WsProjectCloneRetryRpc, diff --git a/packages/source-control-core/src/server/driver.ts b/packages/source-control-core/src/server/driver.ts index d5fc3d45490c7..7226faad651cf 100644 --- a/packages/source-control-core/src/server/driver.ts +++ b/packages/source-control-core/src/server/driver.ts @@ -65,6 +65,8 @@ export interface SourceControlDriverInstance { readonly signIn?: SourceControlSignIn; /** Whether the server's account on `host` starred `repository` (`owner/name`). */ readonly isRepositoryStarred?: (host: string, repository: string) => Effect.Effect; + /** Stars `repository` as the server's account on `host`; false when the forge refused. */ + readonly starRepository?: (host: string, repository: string) => Effect.Effect; } /** What the server gives every driver. A driver builds anything else it needs itself. */ diff --git a/packages/source-control-github/src/server/driver.test.ts b/packages/source-control-github/src/server/driver.test.ts index b97300eceaff3..a16f7efca4e4d 100644 --- a/packages/source-control-github/src/server/driver.test.ts +++ b/packages/source-control-github/src/server/driver.test.ts @@ -2,17 +2,17 @@ import { assert, describe, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import { makeIsRepositoryStarred } from "./driver.ts"; +import { makeIsRepositoryStarred, makeStarRepository } from "./driver.ts"; import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts"; import * as GitHubRest from "./GitHubRest.ts"; -describe("makeIsRepositoryStarred", () => { - it.effect("is true only when GitHub answers 204 for the repository", () => { +describe("starred", () => { + it.effect("checks and stars only a valid repository, true only on 204", () => { const paths: Array = []; const starred = new Set(["user/starred/pingdotgg/t3code"]); const api = Layer.mock(GitHubRest.GitHubRest)({ rest: (input) => { - paths.push(input.path); + paths.push(`${input.method ?? "GET"} ${input.path}`); return starred.has(input.path) ? Effect.succeed({ status: 204, @@ -31,12 +31,20 @@ describe("makeIsRepositoryStarred", () => { }); return Effect.gen(function* () { const isStarred = yield* makeIsRepositoryStarred; + const star = yield* makeStarRepository; assert.isTrue(yield* isStarred("github.com", "pingdotgg/t3code")); assert.isFalse(yield* isStarred("github.com", "pingdotgg/uploadthing")); assert.isFalse(yield* isStarred("github.com", "pingdotgg/t3code/../../user")); + assert.isFalse(yield* isStarred("github.com", "../repos")); + assert.isTrue(yield* star("github.com", "pingdotgg/t3code")); + assert.isFalse(yield* star("github.com", "pingdotgg/uploadthing")); + assert.isFalse(yield* star("github.com", "pingdotgg/t3code/../../user")); + assert.isFalse(yield* star("github.com", "../repos")); assert.deepStrictEqual(paths, [ - "user/starred/pingdotgg/t3code", - "user/starred/pingdotgg/uploadthing", + "GET user/starred/pingdotgg/t3code", + "GET user/starred/pingdotgg/uploadthing", + "PUT user/starred/pingdotgg/t3code", + "PUT user/starred/pingdotgg/uploadthing", ]); }).pipe(Effect.provide(api)); }); diff --git a/packages/source-control-github/src/server/driver.ts b/packages/source-control-github/src/server/driver.ts index 351933ce551ca..45af994eca26e 100644 --- a/packages/source-control-github/src/server/driver.ts +++ b/packages/source-control-github/src/server/driver.ts @@ -53,17 +53,25 @@ const makeSignIn = Effect.gen(function* () { } satisfies SourceControlSignIn; }); +const starredPath = (repository: string) => { + const segments = repository.split("/"); + // "." and ".." survive encoding and would normalize the URL out of user/starred. + return segments.length === 2 && segments.every((segment) => !["", ".", ".."].includes(segment)) + ? `user/starred/${segments.map(encodeURIComponent).join("/")}` + : undefined; +}; + // Only 204 means starred. Tokens without star access, a missing login, and 404 all read as false. export const makeIsRepositoryStarred = Effect.gen(function* () { const api = yield* GitHubRest.GitHubRest; return Effect.fn("GitHubDriver.isRepositoryStarred")( function* (host: string, repository: string) { - const segments = repository.split("/"); - if (segments.length !== 2) return false; + const path = starredPath(repository); + if (path === undefined) return false; const response = yield* api.rest({ host, operation: "isRepositoryStarred", - path: `user/starred/${segments.map(encodeURIComponent).join("/")}`, + path, allowReserve: false, }); return response.status === 204; @@ -72,6 +80,20 @@ export const makeIsRepositoryStarred = Effect.gen(function* () { ); }); +// False on any failure, such as a token or app sign-in without permission to star. +export const makeStarRepository = Effect.gen(function* () { + const api = yield* GitHubRest.GitHubRest; + return Effect.fn("GitHubDriver.starRepository")( + function* (host: string, repository: string) { + const path = starredPath(repository); + if (path === undefined) return false; + const response = yield* api.rest({ host, operation: "starRepository", method: "PUT", path }); + return response.status === 204; + }, + Effect.orElseSucceed(() => false), + ); +}); + const makeInstance = Effect.all({ sourceControl: GitHubSourceControlProvider.make, discovery: GitHubSourceControlProvider.makeDiscovery, @@ -79,6 +101,7 @@ const makeInstance = Effect.all({ fetchMedia: GitHubMediaFetch.make, signIn: makeSignIn, isRepositoryStarred: makeIsRepositoryStarred, + starRepository: makeStarRepository, }); export const driver = defineSourceControlDriver({ From e2bb9e63e129001aa37fa1f9f51cb334d1a3db42 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 2 Nov 2026 22:58:33 -0800 Subject: [PATCH 02/22] fix(server): subagent questions reach a busy parent agent (#29909) Co-authored-by: Claude Opus 5.5 --- .../src/orchestration-v2/EffectWorker.ts | 9 +- .../src/orchestration-v2/Orchestrator.ts | 25 ++-- .../SteeringCompletion.integration.test.ts | 115 ++++++++++++++++-- .../orchestrator-mcp-server.md | 8 +- 4 files changed, 132 insertions(+), 25 deletions(-) diff --git a/apps/server/src/orchestration-v2/EffectWorker.ts b/apps/server/src/orchestration-v2/EffectWorker.ts index 534043aeb4eb8..c5b5ea9b383a9 100644 --- a/apps/server/src/orchestration-v2/EffectWorker.ts +++ b/apps/server/src/orchestration-v2/EffectWorker.ts @@ -278,6 +278,10 @@ export const layerExecutor: Layer.Layer< const message = projection.messages.find((item) => item.id === messageId); const run = projection.runs.find((item) => item.id === message?.runId); if (message === undefined || run === undefined) return yield* error; + // Notifications must be queued messages. + const queued = + message.delegatedCompletion !== undefined || + message.notification !== undefined; // Reuse message ids and receipts so retries cannot duplicate messages or follow-ups. yield* threads .dispatch({ @@ -292,10 +296,7 @@ export const layerExecutor: Layer.Layer< ? {} : { modelSelection: run.modelSelection }), dispatchMode: { - type: - message.delegatedCompletion === undefined - ? "start_immediately" - : "queue_after_active", + type: queued ? "queue_after_active" : "start_immediately", }, createdBy: message.createdBy, creationSource: message.creationSource, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 3dc0a65ae03a3..600764704e57f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4685,6 +4685,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio readonly senderThreadId?: OrchestrationV2ConversationMessage["senderThreadId"]; readonly idleCompaction?: OrchestrationV2ConversationMessage["idleCompaction"]; readonly delegatedCompletion?: OrchestrationV2ConversationMessage["delegatedCompletion"]; + readonly notification?: OrchestrationV2ConversationMessage["notification"]; readonly forceRestart: boolean; }) { const targetRun = input.projection.runs.find((candidate) => candidate.id === input.targetRunId); @@ -4838,6 +4839,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ...(input.delegatedCompletion === undefined ? {} : { delegatedCompletion: input.delegatedCompletion }), + ...(input.notification === undefined ? {} : { notification: input.notification }), ...(input.scheduledTaskId === undefined ? {} : { scheduledTaskId: input.scheduledTaskId }), @@ -4939,6 +4941,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio input.projection.thread.providerInstanceId !== input.modelSelection.instanceId; if ( input.delegatedCompletion === undefined && + input.notification === undefined && (instanceChanged || !modelSelectionsEqual(input.projection.thread.modelSelection, input.modelSelection)) ) { @@ -5729,13 +5732,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio taskIds: delivery.taskIds, }; } - // Route durable mailbox deliveries under the thread lock, using the live - // session's capabilities. Never interrupt/restart a turn for a notification. + // Route durable mailbox deliveries and delegated task questions under the + // thread lock, using the live session's capabilities. A question queued + // behind a long parent turn is never seen. Never interrupt/restart a turn + // for a notification. if ( - delegatedCompletion !== undefined && - delegatedCompletion.taskIds.every( - (id) => projection.subagents.find((task) => task.id === id)?.completionWake === "always", - ) + delegatedCompletion !== undefined + ? delegatedCompletion.taskIds.every( + (id) => + projection.subagents.find((task) => task.id === id)?.completionWake === "always", + ) + : command.notification?.source.kind === "delegated_task" ) { const active = projection.runs.find((run) => run.status === "running"); const providerThread = projection.providerThreads.find( @@ -5759,7 +5766,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if ( Option.isSome(session) && session.value.providerSession.capabilities.turns.supportsActiveSteering && - session.value.providerSession.capabilities.turns.activeSteeringInterruptsTools !== true + session.value.providerSession.capabilities.turns.activeSteeringInterruptsTools !== true && + !(yield* stopReachedRun(command, command.threadId, active.id)) ) { dispatchMode = { type: "steer_active", targetRunId: active.id }; } @@ -5826,11 +5834,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio effects, projection, modelSelection: - delegatedCompletion === undefined + delegatedCompletion === undefined && command.notification === undefined ? modelSelection : (projection.runs.find((run) => run.id === dispatchMode.targetRunId)?.modelSelection ?? modelSelection), delegatedCompletion, + ...(command.notification === undefined ? {} : { notification: command.notification }), targetRunId: dispatchMode.targetRunId, messageId: command.messageId, text: dispatchText, diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index e570c3ad81055..bd3f4e5b2e7d8 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -44,13 +44,16 @@ it.effect.each( [true, "with interrupting native steering"], [true, "settled only"], [false, "during continuation"], + ["question", "during delivery"], ] as const - ).map(([mailbox, timing]) => ({ - mailbox, + ).map(([kind, timing]) => ({ + mailbox: kind === true, + question: kind === "question", timing, - label: mailbox ? "mailbox notification" : "steering", + label: + kind === "question" ? "delegated task question" : kind ? "mailbox notification" : "steering", })), -)("delivers $label when completion wins $timing", ({ mailbox, timing }) => +)("delivers $label when completion wins $timing", ({ mailbox, question, timing }) => Effect.scoped( Effect.gen(function* () { const cwd = yield* checkpointWorkspace(`steering-completion-${timing.replaceAll(" ", "-")}`); @@ -255,6 +258,21 @@ it.effect.each( ], }); } + if (question) { + const { thread } = yield* orchestrator.getThreadProjection(threadId); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:composer-selection"), + type: "thread.model-selection-updated", + threadId, + providerInstanceId: instanceId, + occurredAt: yield* DateTime.now, + payload: { ...thread, modelSelection: composerSelection }, + }, + ], + }); + } const dispatchSteer = orchestrator.dispatch({ type: "message.dispatch", commandId: CommandId.make("steer"), @@ -270,11 +288,21 @@ it.effect.each( sizeBytes: 10, }, ], - dispatchMode: mailbox - ? { type: "queue_after_active" } - : { type: "steer_active", targetRunId: first.runId }, - createdBy: mailbox ? "agent" : "user", - creationSource: mailbox ? "server" : "web", + dispatchMode: + mailbox || question + ? { type: "queue_after_active" } + : { type: "steer_active", targetRunId: first.runId }, + createdBy: mailbox || question ? "agent" : "user", + creationSource: mailbox || question ? "server" : "web", + ...(question + ? { + notification: { + source: { kind: "delegated_task", taskIds: [taskId] }, + outcome: "updated", + summary: "Delegated task has a question", + }, + } + : {}), ...(mailbox ? { delegatedCompletion: { @@ -340,6 +368,8 @@ it.effect.each( if (delivery !== null) { yield* Deferred.succeed(rejectSteer, undefined); yield* Fiber.join(delivery); + } + if (delivery !== null && !question) { const requeued = yield* orchestrator.getThreadProjection(threadId); const item = requeued.turnItems.find( (item) => item.type === "user_message" && item.messageId === messageId, @@ -399,7 +429,11 @@ it.effect.each( ]); assert.equal(steerCalls, timing === "during delivery" ? 1 : 0); const final = yield* orchestrator.getThreadProjection(threadId); - if (!mailbox) { + if (question) { + assert.deepEqual(final.thread.modelSelection, composerSelection); + assert.deepEqual(started[1]?.modelSelection, composerSelection); + } + if (!mailbox && !question) { assert.equal( final.turnItems.find( (item) => item.type === "user_message" && item.messageId === messageId, @@ -414,7 +448,7 @@ it.effect.each( ); assert.equal( final.turnItems.filter((item) => - mailbox + mailbox || question ? item.type === "notification" : item.type === "user_message" && item.messageId === messageId, ).length, @@ -617,6 +651,65 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* return { cwd, events, started, steered, interrupted, layer, startFirstTurn }; }); +it.effect("steers a delegated task question notice into the running parent turn", () => + Effect.scoped( + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "delegated-question-steer", + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const { thread } = yield* orchestrator.getThreadProjection(threadId); + yield* (yield* EventSink.EventSinkV2).write({ + events: [ + { + id: EventId.make("event:composer-selection"), + type: "thread.model-selection-updated", + threadId, + providerInstanceId: instanceId, + occurredAt: yield* DateTime.now, + payload: { ...thread, modelSelection: composerSelection }, + }, + ], + }); + const messageId = MessageId.make("message:delegated-task-question:child-question"); + const notification = { + source: { + kind: "delegated_task" as const, + taskIds: [NodeId.make("task:question")], + childThreadId: ThreadId.make("thread:question-child"), + }, + outcome: "updated" as const, + summary: "Delegated task has a question", + }; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("question-wake"), + threadId, + messageId, + text: "Delegated task asked a question", + notification, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual(steered, ["Delegated task asked a question"]); + assert.lengthOf(started, 1); + assert.isFalse(after.runs.some((run) => run.status === "queued")); + const message = after.messages.find((candidate) => candidate.id === messageId); + assert.equal(message?.runId, started[0]?.runId); + assert.deepEqual(message?.notification, notification); + assert.deepEqual(after.thread.modelSelection, composerSelection); + }).pipe(Effect.provide(layer)); + }), + ), +); + it.effect("sends a selected held message once and preserves the remaining queue order", () => Effect.scoped( Effect.gen(function* () { diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 915fa59ab22d0..41146da1ed4c1 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -515,8 +515,12 @@ Users rarely watch child threads, so a child question would otherwise go unanswered. When a child opens a pending `user_input` request, the parent gets a notification message telling it to answer with the pending request tools or ask the user. The message says whether the child is blocked or, for a Codex -async question, still working. If the question is answered or dismissed before -the notification starts a turn, that queued turn is cancelled. Approvals are not +async question, still working. If the parent's turn is running and its provider +can steer without interrupting tools, the notification steers into that turn, +like a background task's completion. A queued notice would wait behind a +long-running orchestrator turn that may never end. Otherwise it queues. If the +question is answered or dismissed before a queued notification starts a turn, +that queued turn is cancelled. Approvals are not routed, because those tools cannot answer them. A parent still blocked in a `delegate_task` wait gets the blocking question through that wait instead. From cefb544af3c98224874419198c0359b652ca3c94 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Mon, 2 Nov 2026 23:26:12 -0800 Subject: [PATCH 03/22] feat(web): celebrate a GitHub star with confetti (#29987) Co-authored-by: Claude Opus 5.5 --- apps/web/package.json | 2 ++ .../src/components/GitHubStarPrompt.test.ts | 5 ++-- apps/web/src/components/GitHubStarPrompt.tsx | 30 +++++++++++++++++-- pnpm-lock.yaml | 16 ++++++++++ 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/apps/web/package.json b/apps/web/package.json index 3cb58dec9cd6c..1d79dc07cd2ed 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -54,6 +54,7 @@ "@tiptap/pm": "^3.31.3", "@tiptap/react": "^3.31.3", "@tiptap/starter-kit": "^3.31.3", + "canvas-confetti": "1.9.4", "class-variance-authority": "^0.7.1", "culori": "^4.0.2", "dompurify": "^3.4.16", @@ -97,6 +98,7 @@ "@effect/vitest": "catalog:", "@tailwindcss/vite": "^4.0.0", "@tanstack/router-plugin": "^1.161.0", + "@types/canvas-confetti": "1.9.0", "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/hast": "^3.0.4", diff --git a/apps/web/src/components/GitHubStarPrompt.test.ts b/apps/web/src/components/GitHubStarPrompt.test.ts index f45229d5ce85e..f748ec8b82209 100644 --- a/apps/web/src/components/GitHubStarPrompt.test.ts +++ b/apps/web/src/components/GitHubStarPrompt.test.ts @@ -165,11 +165,12 @@ describe("recordPromptSent", () => { vi.unstubAllGlobals(); }); it("stars on click, opens GitHub when starring fails, and asks for a click once the click expired", async () => { - setup({ sent: 5 }); + const store = setup({ sent: 5 }); await (await startSession()).send(); click(add.mock.lastCall?.[0].actionProps); await vi.advanceTimersByTimeAsync(0); - expect(add.mock.lastCall?.[0].title).toBe("Thanks for the star!"); + expect(update.mock.lastCall?.[1]).toMatchObject({ title: "Thanks for the star!" }); + expect(store.get("t3code:github-star-prompt:dismissed")).toBe("true"); expect(openExternal).not.toHaveBeenCalled(); setup({ sent: 5 }); diff --git a/apps/web/src/components/GitHubStarPrompt.tsx b/apps/web/src/components/GitHubStarPrompt.tsx index f79714d7a8939..679d61b1f3502 100644 --- a/apps/web/src/components/GitHubStarPrompt.tsx +++ b/apps/web/src/components/GitHubStarPrompt.tsx @@ -38,8 +38,17 @@ function showStarPrompt(environmentId: EnvironmentId) { const starInPlace = async () => { toastManager.update(id, { actionProps: { children: "Starring…", disabled: true } }); if (await starRepository(environmentId)) { - close(); - toastManager.add({ type: "success", title: "Thanks for the star!", timeout: 4_000 }); + // Thank them in place: a closing and opening toast would slide under the confetti. + dismiss(); + toastManager.update(id, { + type: "success", + title: "Thanks for the star!", + description: "It really helps T3 Code grow.", + timeout: 5_000, + actionProps: undefined, + data: {}, + }); + celebrate(); return; } // Browsers block new tabs once the click's activation expires; desktop opens through its bridge. @@ -62,6 +71,23 @@ function showStarPrompt(environmentId: EnvironmentId) { }); } +// One burst out of the toast. The library loads only here, and its canvas stops when done. +function celebrate() { + void import("canvas-confetti") + .then(({ default: confetti }) => + confetti({ + particleCount: 160, + spread: 360, + startVelocity: 38, + gravity: 1.6, + ticks: 140, + origin: { x: 0.83, y: 0.15 }, + disableForReducedMotion: true, + }), + ) + .catch(() => undefined); +} + // Resolves after IDLE_MS without input while this window has focus. function waitForIdle() { return new Promise((resolve) => { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 84a19021c78c8..755f2f95c2ed1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1143,6 +1143,9 @@ importers: '@tiptap/starter-kit': specifier: ^3.31.3 version: 3.31.3 + canvas-confetti: + specifier: 1.9.4 + version: 1.9.4 class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -1267,6 +1270,9 @@ importers: '@tanstack/router-plugin': specifier: ^1.161.0 version: 1.168.13(@tanstack/react-router@1.170.10(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(@voidzero-dev/vite-plus-core@1.4.0(@tsc-rs/typescript@0.8.0)(@types/node@24.12.4)(@volar/typescript@2.4.28(@tsc-rs/typescript@0.8.0))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(unrun@0.2.39)(yaml@2.9.0))(supports-color@8.1.1) + '@types/canvas-confetti': + specifier: 1.9.0 + version: 1.9.0 '@types/compression': specifier: ^1.8.1 version: 1.8.1 @@ -7008,6 +7014,9 @@ packages: '@types/cacheable-request@6.0.3': resolution: {integrity: sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==} + '@types/canvas-confetti@1.9.0': + resolution: {integrity: sha512-aBGj/dULrimR1XDZLtG9JwxX1b4HPRF6CX9Yfwh3NvstZEm1ZL7RBnel4keCPSqs1ANRu1u2Aoz9R+VmtjYuTg==} + '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} @@ -7947,6 +7956,9 @@ packages: caniuse-lite@1.0.30001810: resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==} + canvas-confetti@1.9.4: + resolution: {integrity: sha512-yxQbJkAVrFXWNbTUjPqjF7G+g6pDotOUHGbkZq2NELZUMDpiJ85rIEazVb8GTaAptNW2miJAXbs1BtioA251Pw==} + capnp-es@0.0.16: resolution: {integrity: sha512-pqhhnRqGfDdgHa+rz4JVO9j1jnkyqsHRYrD4RBtIwxCknYSRG7Mjs+x3IRfd20u+ZGS0IhW2L7cDv9ZcIkCYhQ==} hasBin: true @@ -16574,6 +16586,8 @@ snapshots: '@types/node': 24.12.4 '@types/responselike': 1.0.3 + '@types/canvas-confetti@1.9.0': {} + '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 @@ -17735,6 +17749,8 @@ snapshots: caniuse-lite@1.0.30001810: {} + canvas-confetti@1.9.4: {} + capnp-es@0.0.16(@tsc-rs/typescript@0.8.0): optionalDependencies: typescript: '@tsc-rs/typescript@0.8.0' From 8be19ed3f1f22837edb94dfd9324555fae042c24 Mon Sep 17 00:00:00 2001 From: astarktc <148526207+astarktc@users.noreply.github.com> Date: Tue, 3 Nov 2026 10:27:13 -0600 Subject: [PATCH 04/22] fix(pi): short-lived Pi processes no longer lose rotated OAuth tokens (#30187) --- .../provider-pi/src/server/adapter.test.ts | 4 +++ packages/provider-pi/src/server/adapter.ts | 1 + .../provider-pi/src/server/driver.test.ts | 11 +++++++ .../src/server/mcpInjection.test.ts | 11 +++++++ .../provider-pi/src/server/mcpInjection.ts | 4 +++ packages/provider-pi/src/server/status.ts | 1 + .../src/server/textGeneration.test.ts | 30 +++++++++++++++++++ .../provider-pi/src/server/textGeneration.ts | 1 + 8 files changed, 63 insertions(+) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 0afd6960485de..dc994f90cac5a 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -1591,6 +1591,9 @@ describe("PiAdapterV2", () => { arg === "--extension" ? [spawn.args[index + 1]] : [], ); assert.isFalse(spawn.args.includes("--no-extensions")); + // A thread's long-lived process keeps Pi's startup model refresh unless the user opts out. + assert.notInclude(spawn.args, "--offline"); + assert.isUndefined(spawn.env.PI_OFFLINE); assert.isTrue(extensions.some((path) => path?.endsWith("pi-t3-mcp-extension.ts"))); assert.equal(spawn.env.T3_MCP_URL, "http://127.0.0.1:43123/mcp"); assert.equal(spawn.env.T3_MCP_BEARER_TOKEN, "secret-pi-token"); @@ -1891,6 +1894,7 @@ describe("PiAdapterV2", () => { assert.equal(args[args.indexOf("--fork") + 1], FAKE_SESSION_FILE); assert.include(args, "--no-extensions"); assert.include(args, "--no-tools"); + assert.include(args, "--offline"); assert.notInclude(args, "--no-session"); assert.deepEqual( forkFake diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index b7045bcd64360..a8e140f02b784 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3103,6 +3103,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( environment: options.environment, mcpSession: undefined, extensionPath: undefined, + shortLived: true, disableExtensions: true, disableTools: true, }); diff --git a/packages/provider-pi/src/server/driver.test.ts b/packages/provider-pi/src/server/driver.test.ts index 087a8089aaee8..59586fdaedb39 100644 --- a/packages/provider-pi/src/server/driver.test.ts +++ b/packages/provider-pi/src/server/driver.test.ts @@ -169,6 +169,17 @@ it.layer(layerTest)("PiDriver workspace discovery", (it) => { ["--approve", "--skill", "extra skill", "--no-session"], ); assert.equal(workspaceLaunch!.options.env?.PI_CODING_AGENT_DIR, "/isolated-pi"); + // Discovery processes are stopped as soon as they answer, so neither may start Pi's + // network refresh at launch. + for (const cwd of ["/machine", "/first"]) { + const discovery = launches.find( + (launch) => launch.options.cwd === cwd && launch.args.includes("--mode"), + ); + assert.deepEqual( + discovery?.args.filter((arg) => arg === "--offline"), + ["--offline"], + ); + } }).pipe(Effect.scoped), ); diff --git a/packages/provider-pi/src/server/mcpInjection.test.ts b/packages/provider-pi/src/server/mcpInjection.test.ts index 2ca5f35d026f5..4e776058a66a4 100644 --- a/packages/provider-pi/src/server/mcpInjection.test.ts +++ b/packages/provider-pi/src/server/mcpInjection.test.ts @@ -102,6 +102,7 @@ describe("pi T3 MCP injection", () => { extensionPath: "/tmp/cache/pi-t3-mcp-extension.ts", sessionPath: "/fake/persisted.jsonl", ephemeral: true, + shortLived: true, disableExtensions: true, disableTools: true, }); @@ -111,9 +112,19 @@ describe("pi T3 MCP injection", () => { "--no-session", "--provider", "anthropic", + "--offline", "--no-extensions", "--no-tools", ]); + const alreadyOffline = buildPiRpcLaunch({ + launchArgs: ["--offline"], + environment: {}, + mcpSession: undefined, + extensionPath: undefined, + ephemeral: true, + shortLived: true, + }); + assert.deepEqual(alreadyOffline.args, ["--mode", "rpc", "--no-session", "--offline"]); assert.deepInclude(resolvePiLaunchArgs("--mode text"), { ok: false, message: "Pi launch argument '--mode' is controlled by T3 Code and cannot be overridden.", diff --git a/packages/provider-pi/src/server/mcpInjection.ts b/packages/provider-pi/src/server/mcpInjection.ts index 51848c424ca05..ab92ab73dde7a 100644 --- a/packages/provider-pi/src/server/mcpInjection.ts +++ b/packages/provider-pi/src/server/mcpInjection.ts @@ -244,6 +244,9 @@ export function buildPiRpcLaunch(input: { readonly extensionPath: string | undefined; readonly sessionPath?: string | undefined; readonly ephemeral?: boolean; + // T3 stops these processes as soon as they answer. They run --offline because Pi's startup + // catalog refresh renews expired OAuth tokens, and a stop mid-request loses the rotated one. + readonly shortLived?: boolean; readonly disableExtensions?: boolean; readonly disableTools?: boolean; readonly runtimeMode?: "approval-required" | "auto-accept-edits" | "auto" | "full-access"; @@ -268,6 +271,7 @@ export function buildPiRpcLaunch(input: { ? ["--session", input.sessionPath] : []), ...launchArgs, + ...(input.shortLived === true && !launchArgs.includes("--offline") ? ["--offline"] : []), // Restrictions must follow launch args so user flags cannot re-enable unattended tools/extensions. ...(input.disableExtensions === true ? ["--no-extensions"] : []), ...(input.disableTools === true ? ["--no-tools"] : []), diff --git a/packages/provider-pi/src/server/status.ts b/packages/provider-pi/src/server/status.ts index dfafa75ccd579..4775689c8c2b7 100644 --- a/packages/provider-pi/src/server/status.ts +++ b/packages/provider-pi/src/server/status.ts @@ -150,6 +150,7 @@ const makePiDiscoveryConnection = Effect.fnUntraced(function* ( mcpSession: undefined, extensionPath: undefined, ephemeral: true, + shortLived: true, }); const connection = yield* makePiRpcConnection({ command: piSettings.binaryPath || "pi", diff --git a/packages/provider-pi/src/server/textGeneration.test.ts b/packages/provider-pi/src/server/textGeneration.test.ts index ba693da18012b..0e6a8a3c07780 100644 --- a/packages/provider-pi/src/server/textGeneration.test.ts +++ b/packages/provider-pi/src/server/textGeneration.test.ts @@ -7,6 +7,7 @@ import * as Queue from "effect/Queue"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; +import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { makePiTextGeneration } from "./textGeneration.ts"; @@ -68,6 +69,35 @@ const makeFakePi = ( return { spawner, received }; }); +it.effect("runs Pi offline, since the process is stopped as soon as it answers", () => + Effect.gen(function* () { + const pi = yield* makeFakePi(JSON.stringify({ subject: "Update README", body: "" })); + const launches: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) launches.push(command.args.map(String)); + return pi.spawner.spawn(command); + }); + const textGeneration = yield* makePiTextGeneration( + { enabled: true, binaryPath: "pi", launchArgs: "", customModels: [] }, + {}, + ).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); + + const result = yield* textGeneration.generateCommitMessage({ + cwd: process.cwd(), + branch: "main", + stagedSummary: "M README.md", + stagedPatch: "diff --git a/README.md b/README.md", + modelSelection: createModelSelection(ProviderInstanceId.make("pi"), "default"), + }); + + assert.equal(result.subject, "Update README"); + assert.deepEqual( + launches.map((args) => args.filter((arg) => arg === "--offline")), + [["--offline"]], + ); + }), +); + it.effect("names the model and the disabled extensions when Pi cannot load it", () => Effect.gen(function* () { const pi = yield* makeFakePi("", "Model not found: demo/demo-model"); diff --git a/packages/provider-pi/src/server/textGeneration.ts b/packages/provider-pi/src/server/textGeneration.ts index 3fed9963b6cea..40697f2d4280a 100644 --- a/packages/provider-pi/src/server/textGeneration.ts +++ b/packages/provider-pi/src/server/textGeneration.ts @@ -47,6 +47,7 @@ export const makePiTextGeneration = Effect.fn("makePiTextGeneration")(function* mcpSession: undefined, extensionPath: undefined, ephemeral: true, + shortLived: true, disableExtensions: true, // Background naming/content helpers must never mutate the workspace. disableTools: true, From e27e12d9b4a408496be359e3e0db1844c6ea87af Mon Sep 17 00:00:00 2001 From: Utkarsh Patil <73941998+UtkarshUsername@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:57:58 +0530 Subject: [PATCH 05/22] feat(web): add refresh to provider status banners (#24861) --- apps/web/src/components/ChatView.tsx | 1 + .../src/components/chat/ChatBannerLane.tsx | 3 + .../components/chat/ProviderStatusBanner.tsx | 69 +++++++++++++++---- .../src/state/commandPermissions.test.ts | 34 +++++++++ .../contracts/src/clientRpcPermissions.ts | 1 + 5 files changed, 95 insertions(+), 13 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6ec89f8c36256..497ccfc877771 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3367,6 +3367,7 @@ export default function ChatView(props: ChatViewProps) { {isWorkspaceFileDragActive ? : null} >; @@ -41,6 +43,7 @@ export function ChatBannerLane(props: { return (
setDismissedProviderStatusBannerKey(providerStatusBannerKey)} onOpenProviderSetup={onOpenProviderSetup} diff --git a/apps/web/src/components/chat/ProviderStatusBanner.tsx b/apps/web/src/components/chat/ProviderStatusBanner.tsx index 0e258c10906ac..64afa55ed0d78 100644 --- a/apps/web/src/components/chat/ProviderStatusBanner.tsx +++ b/apps/web/src/components/chat/ProviderStatusBanner.tsx @@ -1,10 +1,18 @@ -import { type ProviderInstanceId, type ServerProvider } from "@t3tools/contracts"; -import { memo } from "react"; +import { + type EnvironmentId, + type ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import { memo, useRef, useState } from "react"; import { InfoIcon, XIcon } from "lucide-react"; import { Alert, AlertAction, AlertDescription, AlertTitle } from "../ui/alert"; import { Button, InlineButton } from "../ui/button"; import { formatProviderDriverKindLabel } from "../../providerModels"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { RefreshIcon } from "../ui/refresh-icon"; function getIncompatibleVersion(status: ServerProvider) { const compatibility = status.compatibilityAdvisory; @@ -86,14 +94,35 @@ export function getProviderStatusMessage(status: ServerProvider): string { } export const ProviderStatusBanner = memo(function ProviderStatusBanner({ + environmentId, onDismiss, onOpenProviderSetup, status, }: { + environmentId: EnvironmentId; onDismiss: () => void; onOpenProviderSetup?: (instanceId: ProviderInstanceId) => void; status: ServerProvider | null; }) { + const canRefresh = useAtomValue(serverEnvironment.refreshProviders.permissionAtom(environmentId)); + const refreshProviders = useAtomCommand(serverEnvironment.refreshProviders, { + label: "Refresh provider status", + }); + const refreshingRef = useRef(false); + const [isRefreshing, setIsRefreshing] = useState(false); + + const refresh = async () => { + if (!status || !canRefresh || refreshingRef.current) return; + refreshingRef.current = true; + setIsRefreshing(true); + await refreshProviders({ + environmentId, + input: { instanceId: status.instanceId, refreshModels: true }, + }); + refreshingRef.current = false; + setIsRefreshing(false); + }; + if (!status || getProviderStatusBannerKey(status) === null) { return null; } @@ -121,17 +150,31 @@ export const ProviderStatusBanner = memo(function ProviderStatusBanner({ {title} - - }>{message} - - {message} - - - {onOpenProviderSetup && hasProviderSetup(status) ? ( - onOpenProviderSetup(status.instanceId)}> - Open provider setup - - ) : null} +
+ + }>{message} + + {message} + + +
+ {onOpenProviderSetup && hasProviderSetup(status) ? ( + onOpenProviderSetup(status.instanceId)}> + Open provider setup + + ) : null} + +
+
+ {props.isSelected ?