Date: Wed, 11 Nov 2026 17:16:54 -0800
Subject: [PATCH 047/253] fix(web): mouse back/forward over the right panel no
longer moves the main chat (#30882)
---
apps/web/src/browser/HostedBrowserWebview.tsx | 12 ++
.../RightPanelTabs.browser.test.tsx | 117 +++++++++++++++++-
apps/web/src/components/RightPanelTabs.tsx | 9 ++
.../components/preview/PreviewPanelShell.tsx | 5 +
.../src/components/preview/PreviewView.tsx | 6 +
.../components/preview/previewActionBus.ts | 2 +
.../src/components/preview/thumbButtons.ts | 19 +++
apps/web/src/components/ui/input-group.tsx | 1 +
...ntextMenuFallback.keyboard.browser.test.ts | 12 ++
apps/web/src/contextMenuFallback.ts | 7 ++
10 files changed, 189 insertions(+), 1 deletion(-)
create mode 100644 apps/web/src/components/preview/thumbButtons.ts
diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx
index 34c7978b7b40b..44de1196b2b7c 100644
--- a/apps/web/src/browser/HostedBrowserWebview.tsx
+++ b/apps/web/src/browser/HostedBrowserWebview.tsx
@@ -7,6 +7,10 @@ import { useShallow } from "zustand/react/shallow";
import { useEffect, useEffectEvent, useRef, useState } from "react";
import { previewBridge } from "~/components/preview/previewBridge";
+import {
+ preventThumbButtonFocus,
+ takeThumbButtonNavigation,
+} from "~/components/preview/thumbButtons";
import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
import { useClientSettingsHydrated } from "~/hooks/useSettings";
import { cn, isMacPlatform } from "~/lib/utils";
@@ -302,6 +306,12 @@ export function HostedBrowserWebview(props: {
if (!clientSettingsHydrated || !config) return null;
+ // This fixed wrapper sits outside the right panel shell, so it takes thumb presses itself.
+ const navigateThumb = (direction: "back" | "forward") => {
+ if (direction === "back") void previewBridge?.goBack(runtimeTabId);
+ else void previewBridge?.goForward(runtimeTabId);
+ };
+
const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
active,
@@ -320,6 +330,8 @@ export function HostedBrowserWebview(props: {
className="fixed overflow-hidden bg-muted/35"
style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
onScroll={syncContentPresentation}
+ onMouseDown={preventThumbButtonFocus}
+ onMouseUp={(event) => takeThumbButtonNavigation(event, navigateThumb)}
data-preview-rendering={renderingActive ? "active" : "suspended"}
data-preview-viewport={runtimeTabId}
>
diff --git a/apps/web/src/components/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx
index 4a7617bb1abd8..cceb8c22c707b 100644
--- a/apps/web/src/components/RightPanelTabs.browser.test.tsx
+++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx
@@ -1,11 +1,14 @@
import "~/index.css";
+import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";
+import { InputGroup, InputGroupAddon, InputGroupInput } from "~/components/ui/input-group";
import type { RightPanelSurface } from "~/rightPanelStore";
import { render, stubGlobal } from "../../test/render";
import { HistorySwipeNavigation } from "./HistorySwipeNavigation";
-import { RightPanelTabs } from "./RightPanelTabs";
+import { RightPanelTabs, type RightPanelTabsProps } from "./RightPanelTabs";
+import { subscribePreviewAction } from "./preview/previewActionBus";
const navigateHistory = vi.hoisted(() => vi.fn());
vi.mock("../navigationHistory", () => ({ canNavigateHistory: () => true, navigateHistory }));
@@ -134,3 +137,115 @@ describe("RightPanelTabs", () => {
expect(navigateHistory).toHaveBeenCalledExactlyOnceWith("back");
});
});
+
+const BROWSER_SURFACE: RightPanelSurface = {
+ id: "browser:tab-1",
+ kind: "preview",
+ resourceId: "tab-1",
+};
+const DIFF_SURFACE: RightPanelSurface = { id: "diff", kind: "diff" };
+
+function panel(activeSurface: RightPanelSurface) {
+ const noop = () => {};
+ const props: RightPanelTabsProps = {
+ mode: "inline",
+ keybindings: [],
+ getShortcutContext: () => ({
+ terminalFocus: false,
+ terminalOpen: false,
+ previewFocus: false,
+ previewOpen: true,
+ isWeb: true,
+ isDesktop: false,
+ }),
+ surfaces: [BROWSER_SURFACE, DIFF_SURFACE],
+ environmentId: EnvironmentId.make("environment-local"),
+ activeSurfaceId: activeSurface.id,
+ pendingSurfaceIds: new Set(),
+ previewSessions: {},
+ desktopByTabId: {},
+ terminalLabelsById: new Map(),
+ onActivate: noop,
+ onCloseSurface: noop,
+ onCloseOtherSurfaces: noop,
+ onCloseSurfacesToRight: noop,
+ onCloseAllSurfaces: noop,
+ onCopyFilePath: noop,
+ onAddBrowser: noop,
+ onAddBrowserInProfile: noop,
+ onAddTerminal: noop,
+ onAddDiff: noop,
+ onAddFiles: noop,
+ onAddPullRequest: noop,
+ onAddPullRequests: noop,
+ onAddDevice: noop,
+ browserAvailable: true,
+ terminalAvailable: true,
+ diffAvailable: true,
+ filesAvailable: true,
+ pullRequestAvailable: true,
+ pullRequestsAvailable: true,
+ deviceAvailable: true,
+ children: (
+
+ {/* Stands in for ServerBrowserSurface, whose page canvas handles thumb buttons itself. */}
+
+ ),
+ };
+ return
;
+}
+
+// Chromium focuses on an uncancelled mousedown and runs history back/forward on an
+// uncancelled button 3/4 mouseup.
+function releaseThumbButton(
+ target: Element,
+ button: 3 | 4,
+): { focusMoved: boolean; routerMoved: boolean } {
+ const focused = document.activeElement;
+ const down = new MouseEvent("mousedown", { bubbles: true, cancelable: true, button });
+ const up = new MouseEvent("mouseup", { bubbles: true, cancelable: true, button });
+ target.dispatchEvent(down);
+ target.dispatchEvent(up);
+ return {
+ focusMoved: !down.defaultPrevented || document.activeElement !== focused,
+ routerMoved: !up.defaultPrevented,
+ };
+}
+
+const STAYS_PUT = { focusMoved: false, routerMoved: false };
+
+describe("right panel thumb buttons", () => {
+ it("keep the app router still over a surface that is not a browser", async () => {
+ await using screen = await render(panel(DIFF_SURFACE));
+ const tabStrip = screen.container.querySelector("[data-right-panel-tabbar]")!;
+ const content = screen.getByTestId("surface-content").element();
+
+ expect(releaseThumbButton(tabStrip, 3)).toEqual(STAYS_PUT);
+ expect(releaseThumbButton(tabStrip, 4)).toEqual(STAYS_PUT);
+ expect(releaseThumbButton(content, 3)).toEqual(STAYS_PUT);
+ expect(releaseThumbButton(content, 4)).toEqual(STAYS_PUT);
+ });
+
+ it("go back and forward in the active browser tab instead of the app router", async () => {
+ const actions: string[] = [];
+ using _subscription = { [Symbol.dispose]: subscribePreviewAction((a) => actions.push(a)) };
+ await using screen = await render(panel(BROWSER_SURFACE));
+ const tabStrip = screen.container.querySelector("[data-right-panel-tabbar]")!;
+ const content = screen.getByTestId("surface-content").element();
+
+ expect(releaseThumbButton(tabStrip, 3)).toEqual(STAYS_PUT);
+ expect(releaseThumbButton(content, 4)).toEqual(STAYS_PUT);
+ // The address addon focuses its input on press; a thumb press must leave focus alone.
+ expect(releaseThumbButton(screen.getByTestId("address-addon").element(), 3)).toEqual(STAYS_PUT);
+ expect(actions).toEqual(["back", "forward", "back"]);
+
+ // The page canvas already went back in the tab; the panel must not go back a second time.
+ releaseThumbButton(screen.getByTestId("page-canvas").element(), 3);
+ expect(actions).toEqual(["back", "forward", "back"]);
+ });
+});
diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx
index f3066201f71ec..223799efb26f6 100644
--- a/apps/web/src/components/RightPanelTabs.tsx
+++ b/apps/web/src/components/RightPanelTabs.tsx
@@ -99,6 +99,8 @@ import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
import { FaviconImage } from "./preview/PreviewFaviconIcon";
import { previewBridge } from "./preview/previewBridge";
+import { dispatchPreviewAction } from "./preview/previewActionBus";
+import { preventThumbButtonFocus, takeThumbButtonNavigation } from "./preview/thumbButtons";
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
import { resolvePullRequestState } from "./pullRequest/pullRequestPresentation";
import { PullRequestGlyph } from "~/components/pullRequest/pullRequestIcons";
@@ -1335,6 +1337,13 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
{...(props.widthStorageKey !== undefined ? { widthStorageKey: props.widthStorageKey } : {})}
{...(props.defaultWidth !== undefined ? { defaultWidth: props.defaultWidth } : {})}
{...(props.inlineSize ? { inlineSize: props.inlineSize } : {})}
+ onMouseDown={preventThumbButtonFocus}
+ onMouseUp={(event) =>
+ takeThumbButtonNavigation(
+ event,
+ focusedSurface?.kind === "preview" ? dispatchPreviewAction : undefined,
+ )
+ }
>
;
+ onMouseUp?: MouseEventHandler;
children: ReactNode;
}
@@ -153,6 +156,8 @@ function PreviewPanelShellFrame(
{...(props.workspaceArea ? panelArea : {})}
data-workspace-focus-key={props.workspaceFocusKey}
data-workspace-unavailable={collapsible && !open ? "true" : undefined}
+ onMouseDown={props.onMouseDown}
+ onMouseUp={props.onMouseUp}
className={cn(
"relative flex h-full min-h-0 min-w-0 max-w-full flex-col self-stretch bg-background",
isInline
diff --git a/apps/web/src/components/preview/PreviewView.tsx b/apps/web/src/components/preview/PreviewView.tsx
index 33fd2fa8511b4..5629352f38c80 100644
--- a/apps/web/src/components/preview/PreviewView.tsx
+++ b/apps/web/src/components/preview/PreviewView.tsx
@@ -895,6 +895,12 @@ export function PreviewView({
case "refresh":
handleRefresh();
return;
+ case "back":
+ handleBack();
+ return;
+ case "forward":
+ handleForward();
+ return;
case "focus-url":
urlInputRef.current?.focus();
return;
diff --git a/apps/web/src/components/preview/previewActionBus.ts b/apps/web/src/components/preview/previewActionBus.ts
index e15ff351fa43e..3c99f1b13c758 100644
--- a/apps/web/src/components/preview/previewActionBus.ts
+++ b/apps/web/src/components/preview/previewActionBus.ts
@@ -1,6 +1,8 @@
export type PreviewAction =
| "toggle-panel"
| "refresh"
+ | "back"
+ | "forward"
| "focus-url"
| "zoom-in"
| "zoom-out"
diff --git a/apps/web/src/components/preview/thumbButtons.ts b/apps/web/src/components/preview/thumbButtons.ts
new file mode 100644
index 0000000000000..18ac40aa92c67
--- /dev/null
+++ b/apps/web/src/components/preview/thumbButtons.ts
@@ -0,0 +1,19 @@
+import type { MouseEvent as ReactMouseEvent } from "react";
+
+const isThumbButton = (event: ReactMouseEvent) => event.button === 3 || event.button === 4;
+
+// A thumb press would otherwise focus the URL bar, which then stops tracking the page.
+export function preventThumbButtonFocus(event: ReactMouseEvent) {
+ if (isThumbButton(event)) event.preventDefault();
+}
+
+// Chromium runs app-router history on a thumb-button mouseup unless it is cancelled.
+// Page content that already stepped its own history cancels it first.
+export function takeThumbButtonNavigation(
+ event: ReactMouseEvent,
+ navigate: ((direction: "back" | "forward") => void) | undefined,
+) {
+ if (!isThumbButton(event) || event.defaultPrevented) return;
+ event.preventDefault();
+ navigate?.(event.button === 3 ? "back" : "forward");
+}
diff --git a/apps/web/src/components/ui/input-group.tsx b/apps/web/src/components/ui/input-group.tsx
index 1e41a8b878717..789b5211ca74f 100644
--- a/apps/web/src/components/ui/input-group.tsx
+++ b/apps/web/src/components/ui/input-group.tsx
@@ -93,6 +93,7 @@ function InputGroupAddon({
data-align={align}
data-slot="input-group-addon"
onMouseDown={(e) => {
+ if (e.button !== 0) return;
const target = e.target as HTMLElement;
const isInteractive = target.closest(
"button, a, input, select, textarea, [role='button'], [role='combobox'], [role='listbox'], [data-slot='select-trigger']",
diff --git a/apps/web/src/contextMenuFallback.keyboard.browser.test.ts b/apps/web/src/contextMenuFallback.keyboard.browser.test.ts
index bfd74dedfbc95..078d9f2539e4b 100644
--- a/apps/web/src/contextMenuFallback.keyboard.browser.test.ts
+++ b/apps/web/src/contextMenuFallback.keyboard.browser.test.ts
@@ -104,3 +104,15 @@ it("closes without taking focus back when focus moves elsewhere", async () => {
await expect(result).resolves.toBeNull();
expect(document.activeElement).toBe(destination);
});
+
+it("takes thumb Back and Forward presses so the app router stays put", () => {
+ using _fixture = setup();
+ void showContextMenuFallback(items);
+ for (const button of [3, 4]) {
+ const event = new MouseEvent("mouseup", { button, bubbles: true, cancelable: true });
+ document.activeElement!.dispatchEvent(event);
+ // Chromium runs history back/forward on a thumb-button mouseup nobody cancelled.
+ expect(event.defaultPrevented).toBe(true);
+ }
+ expect(isContextMenuOpen()).toBe(true);
+});
diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts
index 55041deb60dfb..2649e09a50a01 100644
--- a/apps/web/src/contextMenuFallback.ts
+++ b/apps/web/src/contextMenuFallback.ts
@@ -586,6 +586,13 @@ export function showContextMenuFallback(
menu.addEventListener("mouseenter", () => {
closeMenusFromLevel(level + 1);
});
+ // Like a native menu, take thumb Back/Forward presses instead of letting Chromium
+ // run the app router's history underneath.
+ const swallowThumbButton = (event: MouseEvent) => {
+ if (event.button === 3 || event.button === 4) event.preventDefault();
+ };
+ menu.addEventListener("mousedown", swallowThumbButton);
+ menu.addEventListener("mouseup", swallowThumbButton);
document.body.appendChild(menu);
menuStack[level] = menu;
From af2421f23a81c4bc7e197bfe3ecf6e34036b58a0 Mon Sep 17 00:00:00 2001
From: maria
Date: Thu, 12 Nov 2026 01:20:06 +0000
Subject: [PATCH 048/253] fix(github): the PR limits sweep retries a failed
read (#34671)
---
.github/scripts/pr-limits.cjs | 37 +++++++++++++++++++++++++++++------
1 file changed, 31 insertions(+), 6 deletions(-)
diff --git a/.github/scripts/pr-limits.cjs b/.github/scripts/pr-limits.cjs
index e63174950e126..77c09785e4104 100644
--- a/.github/scripts/pr-limits.cjs
+++ b/.github/scripts/pr-limits.cjs
@@ -8,9 +8,13 @@ const NOTICE_MS = 72 * HOUR_MS;
// limit on how fast a token may comment.
const MAX_REQUESTS_PER_RUN = 100;
const MAX_CLOSES_PER_RUN = 50;
+// A last look that ends in "not today" closes nothing, so the looks need a cap of their own.
+const MAX_RECHECKS_PER_RUN = 150;
const WRITE_PAUSE_MS = 1_000;
// Measured here: about two and a half minutes until every open PR has an answer.
const MERGEABLE_WAIT_MS = 150_000;
+const READ_ATTEMPTS = 4;
+const READ_RETRY_MS = 5_000;
// GitHub stamps a label event and the PR's updatedAt a second or two apart.
const SAME_MOMENT_MS = 15_000;
@@ -27,7 +31,7 @@ const LOGIN_PATTERN = /^github:([A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38
const SWEEP_QUERY = `
query ($owner: String!, $repo: String!, $labels: [String!], $cursor: String) {
repository(owner: $owner, name: $repo) {
- pullRequests(states: OPEN, labels: $labels, first: 100, after: $cursor) {
+ pullRequests(states: OPEN, labels: $labels, first: 50, after: $cursor) {
pageInfo { hasNextPage endCursor }
nodes {
number
@@ -63,6 +67,22 @@ const AUTHOR_OPEN_PRS_QUERY = `
}
}`;
+const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// GitHub answers a heavy list request with a 502 now and then, and one of those must not end the
+// run. Only reads go through here: repeating a read is safe, repeating a comment is not.
+async function read(github, query, variables) {
+ for (let attempt = 1; ; attempt += 1) {
+ try {
+ return await github.graphql(query, variables);
+ } catch (error) {
+ const transient = typeof error.status === "number" && error.status >= 500;
+ if (attempt === READ_ATTEMPTS || !transient) throw error;
+ await pause(attempt * READ_RETRY_MS);
+ }
+ }
+}
+
// Fails closed: a missing, empty, or malformed list must never read as "nobody is exempt".
function parseExemptions(text) {
const logins = new Set();
@@ -141,13 +161,12 @@ async function closeWithComment(github, context, number, body) {
async function sweep({ github, context, core, dryRun }) {
const exemptions = parseExemptions(fs.readFileSync(EXEMPTIONS_PATH, "utf8"));
const repo = { owner: context.repo.owner, repo: context.repo.repo };
- const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const list = async () => {
const prs = [];
for (let cursor = null; ;) {
const page = (
- await github.graphql(SWEEP_QUERY, {
+ await read(github, SWEEP_QUERY, {
...repo,
cursor,
labels: [UNVOUCHED_LABEL, REBASE_LABEL, CLOSING_LABEL],
@@ -167,7 +186,12 @@ async function sweep({ github, context, core, dryRun }) {
}
const now = Date.now();
+ // Start further down the list each day. The step is no larger than a run's cap, so a cap that
+ // is reached cannot leave the same PRs waiting behind the same others every day.
+ const start = (Math.floor(now / (24 * HOUR_MS)) * MAX_RECHECKS_PER_RUN) % (prs.length || 1);
+ prs = [...prs.slice(start), ...prs.slice(0, start)];
const count = {};
+ let rechecks = 0;
for (const pr of prs) {
const { number } = pr;
let action = decide(pr, exemptions, now);
@@ -181,9 +205,10 @@ async function sweep({ github, context, core, dryRun }) {
if ((count["close-conflict"] ?? 0) + (count["close-notice"] ?? 0) >= MAX_CLOSES_PER_RUN) {
continue;
}
+ if (rechecks >= MAX_RECHECKS_PER_RUN) continue;
+ rechecks += 1;
// The list is minutes old by now. Closing is the one step worth a second look.
- const fresh = (await github.graphql(RECHECK_QUERY, { ...repo, number })).repository
- .pullRequest;
+ const fresh = (await read(github, RECHECK_QUERY, { ...repo, number })).repository.pullRequest;
if (fresh.state !== "OPEN") continue;
// A merge to the base can resolve a conflict without touching the PR, so this is re-read
// too. An answer that is not ready yet reads as "not conflicting" and waits for tomorrow.
@@ -265,7 +290,7 @@ async function enforceOpenLimit({ github, context, core, dryRun }) {
if (reopened && context.payload.sender.login.toLowerCase() !== author.toLowerCase()) return;
const q = `repo:${context.repo.owner}/${context.repo.repo} is:pr is:open author:${author} sort:created-asc`;
- const { search } = await github.graphql(AUTHOR_OPEN_PRS_QUERY, { q });
+ const { search } = await read(github, AUTHOR_OPEN_PRS_QUERY, { q });
// A new PR counts only the older ones, so two opened together cannot close each other.
const others = search.nodes.filter(
(node) => node.number && (reopened ? node.number !== pr.number : node.number < pr.number),
From 82143423858d31b861fd7f225805e3af05e318f8 Mon Sep 17 00:00:00 2001
From: Saikrishna Ambeti
Date: Thu, 12 Nov 2026 06:53:53 +0530
Subject: [PATCH 049/253] fix(web): collapsed PR comments no longer show raw
HTML (#32283)
---
.../pullRequest/PullRequestSummaryTab.tsx | 10 +---
.../pullRequestMarkdown.logic.test.ts | 30 +++++++++-
.../pullRequest/pullRequestMarkdown.logic.ts | 58 ++++++++++++++++++-
3 files changed, 88 insertions(+), 10 deletions(-)
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
index a78cdfbd6f06f..4b706ef7eafd5 100644
--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
@@ -1,3 +1,4 @@
+import { pullRequestCommentPreview } from "./pullRequestMarkdown.logic";
import { parsePullRequestAnchor } from "@t3tools/shared/pullRequestAnchor";
import { holdLinkedNodeInView } from "./holdLinkedNodeInView";
import { useAtomValue } from "@effect/atom-react";
@@ -314,14 +315,7 @@ function CollapsedComment({
className="mt-2 block w-full truncate text-left text-xs text-muted-foreground hover:text-foreground"
onClick={() => statusTriggerRef.current?.focus({ preventScroll: true })}
>
- {body
- .replace(//gu, "")
- .replace(/^\s*>?\s*\[!\w+\]\s*$/gmu, "")
- .replace(/!?(\[([^\]]+)\])\([^)]*\)/gu, "$2")
- .replace(/^[\s>#*-]+/gmu, "")
- .replace(/[*`]/gu, "")
- .replace(/\s+/g, " ")
- .trim()}
+ {pullRequestCommentPreview(body)}
) : null}
diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts
index 19c2e9038449b..c78617f221c1e 100644
--- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts
+++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts
@@ -3,7 +3,7 @@ import remarkParse from "remark-parse";
import { unified } from "unified";
import { describe, expect, it } from "vite-plus/test";
-import { remarkPullRequestAutolinks } from "./pullRequestMarkdown.logic";
+import { pullRequestCommentPreview, remarkPullRequestAutolinks } from "./pullRequestMarkdown.logic";
type Node = {
type: string;
@@ -44,3 +44,31 @@ describe("remarkPullRequestAutolinks", () => {
]);
});
});
+
+describe("pullRequestCommentPreview", () => {
+ it.each([
+ ["\n> [!WARNING]\n**Guard** [this](https://example.com).", "Guard this."],
+ [
+ '

\n
Tasks keep the wrong computer',
+ "Tasks keep the wrong computer",
+ ],
+ [
+ "
Review & fixes
First
Second
",
+ "Review & fixes First Second",
+ ],
+ ['
Keep this readable.
', "Keep this readable."],
+ [
+ "Use `
` and `Promise
`.\n\n```html\nexample\n```",
+ "Use and Promise
. example",
+ ],
+ [" **Review**", "badge Review"],
+ ["```md\n[!TIP]\n> [!WARNING]\n```\n\n [!NOTE]", "[!TIP] > [!WARNING] [!NOTE]"],
+ [
+ "Review :codex-file-citation{purpose='output'} safely.",
+ "Review :codex-file-citation{purpose='output'} safely.",
+ ],
+ [":codex-followup[Prepare **print** version]", ":codex-followup[Prepare **print** version]"],
+ ])("extracts readable text from %s", (body, expected) => {
+ expect(pullRequestCommentPreview(body)).toBe(expected);
+ });
+});
diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts
index adf90dbec4e58..40dc1473660de 100644
--- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts
+++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts
@@ -6,7 +6,14 @@ import {
sourceControlClients,
type ReferenceAutolink,
} from "@t3tools/client-runtime/source-control-clients";
-import type { PluggableList } from "unified";
+import {
+ CHAT_MARKDOWN_REHYPE_PLUGINS,
+ CHAT_MARKDOWN_REMARK_PLUGINS,
+} from "@t3tools/shared/markdownPipeline";
+import type { Nodes } from "hast";
+import remarkParse from "remark-parse";
+import remarkRehype from "remark-rehype";
+import { unified, type PluggableList } from "unified";
export {
splitPullRequestBody,
@@ -95,3 +102,52 @@ export function pullRequestMarkdownPlugins(
}
return plugins;
}
+
+const commentPreviewProcessor = unified()
+ .use(remarkParse)
+ .use(CHAT_MARKDOWN_REMARK_PLUGINS)
+ .use(remarkRehype, { allowDangerousHtml: true })
+ .use(CHAT_MARKDOWN_REHYPE_PLUGINS)
+ .freeze();
+
+const PREVIEW_BLOCK_TAGS = new Set([
+ "blockquote",
+ "br",
+ "dd",
+ "details",
+ "div",
+ "dl",
+ "dt",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "hr",
+ "li",
+ "ol",
+ "p",
+ "pre",
+ "summary",
+ "table",
+ "td",
+ "th",
+ "tr",
+ "ul",
+]);
+
+function commentPreviewText(node: Nodes): string {
+ if (node.type === "text") return node.value;
+ if (node.type === "element" && node.tagName === "img") {
+ return typeof node.properties.alt === "string" ? node.properties.alt : "";
+ }
+ if (!("children" in node)) return "";
+ const text = node.children.map(commentPreviewText).join("");
+ return node.type === "element" && PREVIEW_BLOCK_TAGS.has(node.tagName) ? ` ${text} ` : text;
+}
+
+export function pullRequestCommentPreview(body: string): string {
+ const tree = commentPreviewProcessor.runSync(commentPreviewProcessor.parse(body), body);
+ return commentPreviewText(tree).replace(/\s+/gu, " ").trim();
+}
From 34e7b6601ba735b979d5484347a185b8f2cde0d6 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 11 Nov 2026 17:26:46 -0800
Subject: [PATCH 050/253] fix(server): t3_thread_list counts threads waiting on
background work as live (#34674)
---
.../src/mcp/OrchestratorMcpService.test.ts | 21 +++++++++++++++++++
apps/server/src/mcp/OrchestratorMcpService.ts | 15 +++++++++----
2 files changed, 32 insertions(+), 4 deletions(-)
diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.ts
index e0bb1aa96e2f3..862263b3a4c6f 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts
@@ -3886,6 +3886,13 @@ describe("OrchestratorMcpService thread list", () => {
shell("thread:a-snoozed", "project:a", true),
shell("thread:a-awake", "project:a", false),
shell("thread:b-snoozed", "project:b", true),
+ {
+ ...shell("thread:a-awaiting-command", "project:a", false),
+ activityRunStatus: null,
+ pendingBackgroundTasks: [
+ { taskId: "sleep-600", kind: "command" as const, awaited: true as const },
+ ],
+ },
];
const service = layerOrchestratorService.pipe(
Layer.provide(
@@ -3932,6 +3939,20 @@ describe("OrchestratorMcpService thread list", () => {
}).pipe(Effect.provide(service)),
);
+ it.effect("counts a thread holding awaited background work as live in the status filter", () =>
+ Effect.gen(function* () {
+ const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
+ const listed = yield* mcp.listThreads(client, {
+ projectId: ProjectId.make("project:a"),
+ statuses: ["preparing", "queued", "starting", "running", "waiting"],
+ });
+ assert.deepStrictEqual(
+ listed.threads.map((thread) => thread.threadId),
+ ["thread:a-awaiting-command"],
+ );
+ }).pipe(Effect.provide(service)),
+ );
+
it.effect("points a caller outside any thread at allProjects when it omits projectId", () =>
Effect.gen(function* () {
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts
index 960253adc3982..e03e0209f6812 100644
--- a/apps/server/src/mcp/OrchestratorMcpService.ts
+++ b/apps/server/src/mcp/OrchestratorMcpService.ts
@@ -68,6 +68,7 @@ import {
SECRET_REQUEST_UNSAVED_NOTE,
} from "@t3tools/contracts";
import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model";
+import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
import { formatThreadLink } from "@t3tools/shared/threadLinks";
import {
@@ -814,6 +815,14 @@ function threadPullRequests(
}));
}
+// Awaited background work keeps a thread live after its turn ends, as auto-settle and the sidebar treat it.
+function listedThreadStatus(shell: OrchestrationV2ThreadShell) {
+ if (shell.activityRunStatus != null) return shell.activityRunStatus;
+ return backgroundWorkHoldsCompletion(shell.pendingBackgroundTasks ?? [])
+ ? "waiting"
+ : shell.status;
+}
+
function listItemFromShell(
scope: McpInvocationScope,
shell: OrchestrationV2ThreadShell,
@@ -826,7 +835,7 @@ function listItemFromShell(
link: threadLinkFor(scope, shell.id, shell.title),
createdBy: shell.createdBy,
creationSource: shell.creationSource,
- status: shell.activityRunStatus ?? shell.status,
+ status: listedThreadStatus(shell),
latestRunId: shell.latestRunId,
providerInstanceId: shell.modelSelection.instanceId,
model: shell.modelSelection.model,
@@ -2978,9 +2987,7 @@ const make = Effect.gen(function* () {
: new Set(input.statuses);
const titleContains = input.titleContains?.toLocaleLowerCase();
const filtered = projectThreads
- .filter(
- (thread) => statuses === null || statuses.has(thread.activityRunStatus ?? thread.status),
- )
+ .filter((thread) => statuses === null || statuses.has(listedThreadStatus(thread)))
.filter(
(thread) =>
input.settled === undefined || threadSettlement(thread).settled === input.settled,
From 7d71f852a8edd298ffde67c295760c286a71a27c Mon Sep 17 00:00:00 2001
From: shivam <91240327+shivamhwp@users.noreply.github.com>
Date: Thu, 12 Nov 2026 06:58:49 +0530
Subject: [PATCH 051/253] fix(mobile): screen readers hear when the open thread
needs you or finishes (#34431)
Co-authored-by: Claude Opus 5.5
---
.../features/threads/ThreadRouteScreen.tsx | 20 +++++
.../threads/threadStatusAnnouncement.test.ts | 82 ++++++++++++++++++
.../threads/threadStatusAnnouncement.ts | 53 ++++++++++++
.../threads/useThreadStatusAnnouncements.ts | 85 +++++++++++++++++++
.../src/state/use-thread-composer-state.ts | 15 ++++
apps/web/src/components/ChatView.tsx | 5 +-
.../backgroundThreadAnnouncement.ts | 5 +-
.../chat/ThreadActivityAnnouncer.tsx | 2 +-
.../components/chat/usePromptSuggestion.ts | 2 +-
packages/client-runtime/package.json | 4 +
.../state}/threadActivityAnnouncement.test.ts | 2 +-
.../src/state}/threadActivityAnnouncement.ts | 0
12 files changed, 270 insertions(+), 5 deletions(-)
create mode 100644 apps/mobile/src/features/threads/threadStatusAnnouncement.test.ts
create mode 100644 apps/mobile/src/features/threads/threadStatusAnnouncement.ts
create mode 100644 apps/mobile/src/features/threads/useThreadStatusAnnouncements.ts
rename {apps/web/src/components/chat => packages/client-runtime/src/state}/threadActivityAnnouncement.test.ts (99%)
rename {apps/web/src/components/chat => packages/client-runtime/src/state}/threadActivityAnnouncement.ts (100%)
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index 96c10b127b48e..6205fd1281797 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -28,6 +28,7 @@ import {
AuthTerminalReadScope,
DEFAULT_SERVER_SETTINGS,
EnvironmentId,
+ isProviderNativeSubagentThread,
MessageId,
ThreadId,
type ProjectScript,
@@ -122,6 +123,7 @@ import {
type ThreadInspectorPresentation,
} from "./thread-inspector-preview";
import { useStartSideChat } from "./useStartSideChat";
+import { useThreadStatusAnnouncements } from "./useThreadStatusAnnouncements";
import type { ThreadInspectorMode, ThreadInspectorTarget } from "./thread-inspector-navigation";
import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspaceDetail";
@@ -377,6 +379,24 @@ function ThreadRouteContent(
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
+ useThreadStatusAnnouncements({
+ threadKey:
+ selectedThread === null || isProviderNativeSubagentThread(selectedThread.source)
+ ? null
+ : scopedThreadKey(selectedThread.environmentId, selectedThread.id),
+ // A preview beside its host names its thread, so the two threads' statuses can't be confused.
+ subject:
+ props.inspectorPresentation !== undefined && "onMaximize" in props.inspectorPresentation
+ ? (selectedThread?.title ?? null)
+ : null,
+ approvalRequestId: requests.activePendingApproval?.requestId ?? null,
+ userInputRequestId: requests.activePendingUserInput?.requestId ?? null,
+ shellRequestId: selectedThread?.source.pendingRuntimeRequest?.id ?? null,
+ shellPendingUserInput: selectedThread?.hasPendingUserInput === true,
+ working: composer.activeWorkStartedAt !== null || composer.isCompacting,
+ run: composer.selectedThreadAnnouncedRun,
+ detailBehind: composer.selectedThreadDetailBehindShell,
+ });
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, {
label: "resume queue",
diff --git a/apps/mobile/src/features/threads/threadStatusAnnouncement.test.ts b/apps/mobile/src/features/threads/threadStatusAnnouncement.test.ts
new file mode 100644
index 0000000000000..fa8814602cec7
--- /dev/null
+++ b/apps/mobile/src/features/threads/threadStatusAnnouncement.test.ts
@@ -0,0 +1,82 @@
+import {
+ nextThreadAnnouncement,
+ type ThreadAnnouncementMemory,
+} from "@t3tools/client-runtime/state/thread-activity-announcement";
+import { RunId } from "@t3tools/contracts";
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ nextThreadActivitySnapshot,
+ type ThreadActivityInput,
+ type ThreadActivityMemory,
+} from "./threadStatusAnnouncement";
+
+const run = RunId.make("run-1");
+
+/** A frame of a working turn: what the question card shows and what the shell holds. */
+function frame(card: string | null, shell: string | null): ThreadActivityInput {
+ return {
+ approvalRequestId: null,
+ userInputRequestId: card,
+ shellRequestId: shell,
+ shellPendingUserInput: shell !== null,
+ working: true,
+ run: { runId: run, status: "running" },
+ };
+}
+
+const idle: ThreadActivityInput = { ...frame(null, null), working: false, run: null };
+const done: ThreadActivityInput = {
+ ...frame(null, null),
+ working: false,
+ run: { runId: run, status: "completed" },
+};
+
+function announcements(frames: ReadonlyArray): ReadonlyArray {
+ let activity: ThreadActivityMemory | null = null;
+ let memory: ThreadAnnouncementMemory | null = null;
+ return frames.map((input) => {
+ activity = nextThreadActivitySnapshot(activity, input);
+ const next = nextThreadAnnouncement(memory, activity.snapshot);
+ memory = next.memory;
+ return next.announcement;
+ });
+}
+
+describe("nextThreadActivitySnapshot", () => {
+ it("says each question once while the card and the shell catch up at different times", () => {
+ expect(
+ announcements([
+ idle,
+ frame(null, null),
+ // The card shows question A before the shell has it.
+ frame("a", null),
+ frame("a", "a"),
+ // Answered: the card hides A at once, the shell still holds it.
+ frame(null, "a"),
+ // Question B reaches the card while the shell still holds A, and is answered before the shell has B.
+ frame("b", "a"),
+ frame(null, "a"),
+ frame(null, "b"),
+ frame(null, null),
+ // A secret request shows only in the shell.
+ frame(null, "secret"),
+ frame(null, null),
+ done,
+ ]),
+ ).toEqual([
+ null,
+ "Working",
+ "Needs your input",
+ null,
+ null,
+ "Needs your input",
+ null,
+ null,
+ null,
+ "Needs your input",
+ null,
+ "Done",
+ ]);
+ });
+});
diff --git a/apps/mobile/src/features/threads/threadStatusAnnouncement.ts b/apps/mobile/src/features/threads/threadStatusAnnouncement.ts
new file mode 100644
index 0000000000000..ddaabb08d6c05
--- /dev/null
+++ b/apps/mobile/src/features/threads/threadStatusAnnouncement.ts
@@ -0,0 +1,53 @@
+import type { ThreadActivitySnapshot } from "@t3tools/client-runtime/state/thread-activity-announcement";
+import type { RunId, OrchestrationV2RunStatus } from "@t3tools/contracts";
+
+export interface ThreadActivityInput {
+ readonly approvalRequestId: string | null;
+ readonly userInputRequestId: string | null;
+ /** The thread shell's pending request, which secret and link cards have only there. */
+ readonly shellRequestId: string | null;
+ readonly shellPendingUserInput: boolean;
+ readonly working: boolean;
+ readonly run: { readonly runId: RunId; readonly status: OrchestrationV2RunStatus } | null;
+}
+
+export interface ThreadActivityMemory {
+ readonly snapshot: ThreadActivitySnapshot;
+ /** Requests the thread screen has shown as a card. */
+ readonly cardRequestIds: ReadonlySet;
+}
+
+/** What the open thread's screen reader status follows, from the same sources the thread screen shows. */
+export function nextThreadActivitySnapshot(
+ previous: ThreadActivityMemory | null,
+ input: ThreadActivityInput,
+): ThreadActivityMemory {
+ const { approvalRequestId, userInputRequestId, shellRequestId } = input;
+ const cardRequestId = approvalRequestId ?? userInputRequestId;
+ const seen = previous?.cardRequestIds ?? new Set();
+ // A card leaves as soon as it is answered, before the shell; a shell request the card
+ // already showed is that answered one, so the request stays the one last announced.
+ // Secret and link requests never show as a card and come from the shell alone.
+ const requestId =
+ cardRequestId ??
+ (shellRequestId !== null && seen.has(shellRequestId)
+ ? (previous?.snapshot.requestId ?? null)
+ : shellRequestId);
+ return {
+ snapshot: {
+ status:
+ approvalRequestId !== null
+ ? "approval"
+ : userInputRequestId !== null || input.shellPendingUserInput
+ ? "input"
+ : input.working
+ ? "working"
+ : "idle",
+ requestId,
+ runId: input.run?.runId ?? null,
+ runStatus: input.run?.status ?? null,
+ },
+ cardRequestIds:
+ cardRequestId === null || seen.has(cardRequestId) ? seen : new Set([...seen, cardRequestId]),
+ };
+}
diff --git a/apps/mobile/src/features/threads/useThreadStatusAnnouncements.ts b/apps/mobile/src/features/threads/useThreadStatusAnnouncements.ts
new file mode 100644
index 0000000000000..c3e14809b39f9
--- /dev/null
+++ b/apps/mobile/src/features/threads/useThreadStatusAnnouncements.ts
@@ -0,0 +1,85 @@
+import { useIsFocused } from "@react-navigation/native";
+import {
+ nextThreadAnnouncement,
+ type ThreadAnnouncementMemory,
+} from "@t3tools/client-runtime/state/thread-activity-announcement";
+import { useEffect, useRef } from "react";
+import { AccessibilityInfo } from "react-native";
+
+import { useAppActive } from "../../lib/appState";
+import {
+ nextThreadActivitySnapshot,
+ type ThreadActivityInput,
+ type ThreadActivityMemory,
+} from "./threadStatusAnnouncement";
+
+/** Tells VoiceOver and TalkBack when the open thread starts working, needs the user, or finishes. */
+export function useThreadStatusAnnouncements({
+ threadKey,
+ subject,
+ detailBehind,
+ approvalRequestId,
+ userInputRequestId,
+ shellRequestId,
+ shellPendingUserInput,
+ working,
+ run,
+}: ThreadActivityInput & {
+ /** Null when nothing should be announced, such as a provider subagent's thread. */
+ readonly threadKey: string | null;
+ /** The thread's title, said after each status when another thread is on screen beside it. */
+ readonly subject: string | null;
+ /** See isDetailBehindShell. */
+ readonly detailBehind: boolean;
+}) {
+ // A retained route stays mounted under the screen above it; it speaks only while shown,
+ // and starts from a silent baseline when it is shown again.
+ const focused = useIsFocused();
+ const appActive = useAppActive();
+ const activeKey = focused && appActive ? threadKey : null;
+ const memoryRef = useRef<{
+ threadKey: string;
+ activity: ThreadActivityMemory;
+ announcement: ThreadAnnouncementMemory;
+ } | null>(null);
+ const runId = run?.runId ?? null;
+ const runStatus = run?.status ?? null;
+
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- speaks committed status changes through the platform screen reader
+ useEffect(() => {
+ if (activeKey === null) {
+ memoryRef.current = null;
+ return;
+ }
+ if (detailBehind) return;
+ const previous = memoryRef.current?.threadKey === activeKey ? memoryRef.current : null;
+ const activity = nextThreadActivitySnapshot(previous?.activity ?? null, {
+ approvalRequestId,
+ userInputRequestId,
+ shellRequestId,
+ shellPendingUserInput,
+ working,
+ run: runId === null || runStatus === null ? null : { runId, status: runStatus },
+ });
+ const next = nextThreadAnnouncement(previous?.announcement ?? null, activity.snapshot);
+ memoryRef.current = { threadKey: activeKey, activity, announcement: next.memory };
+ // Queued, like the web's polite region, so VoiceOver doesn't cut off what it is reading.
+ if (next.announcement !== null) {
+ AccessibilityInfo.announceForAccessibilityWithOptions(
+ subject === null ? next.announcement : `${next.announcement}: ${subject}`,
+ { queue: true },
+ );
+ }
+ }, [
+ activeKey,
+ subject,
+ detailBehind,
+ approvalRequestId,
+ userInputRequestId,
+ shellRequestId,
+ shellPendingUserInput,
+ working,
+ runId,
+ runStatus,
+ ]);
+}
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index 8a762e88c97c6..8b88e489620ef 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -8,10 +8,15 @@ import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows";
import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
+import {
+ announcedRun,
+ isDetailBehindShell,
+} from "@t3tools/client-runtime/state/thread-activity-announcement";
import {
deriveProviderSubagentStatus,
deriveProviderExtensionStatuses,
deriveResumableRunId,
+ deriveLatestThreadRun,
deriveRunlessWorkStartedAt,
deriveThreadActivityRun,
deriveThreadRuntime,
@@ -335,6 +340,14 @@ export function useThreadComposerState(input: {
const selectedThreadActivityRun = selectedThreadProjection
? deriveThreadActivityRun(selectedThreadProjection.projection)
: (selectedThreadShell?.latestRun ?? null);
+ const selectedThreadAnnouncedRun = announcedRun(
+ selectedThreadActivityRun,
+ selectedThreadProjection?.projection.runs ?? [],
+ );
+ const selectedThreadDetailBehindShell = isDetailBehindShell(
+ selectedThreadProjection ? deriveLatestThreadRun(selectedThreadProjection.projection) : null,
+ selectedThreadShell?.latestRun ?? null,
+ );
const activeRunId =
selectedThreadRuntime?.activeRunId && threadRuntimeIsActive(selectedThreadRuntime)
@@ -881,6 +894,8 @@ export function useThreadComposerState(input: {
dismissFeedback,
selectedThreadFeed,
selectedThreadActivityRun,
+ selectedThreadAnnouncedRun,
+ selectedThreadDetailBehindShell,
selectedThreadQueueCount,
selectedThreadQueuedMessages,
dispatchingQueuedMessageId,
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 156c2f8f94327..d3f3f9125df5e 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -7,7 +7,10 @@ import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOver
import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer";
import { useFocusComposerOnThreadOpen } from "./chat/useFocusComposerOnThreadOpen";
import { configuredHostedAppUrl } from "../hostedPairing";
-import { announcedRun, isDetailBehindShell } from "./chat/threadActivityAnnouncement";
+import {
+ announcedRun,
+ isDetailBehindShell,
+} from "@t3tools/client-runtime/state/thread-activity-announcement";
import {
deriveAvailableRevertTurnCounts,
deriveThreadPendingBackgroundTasks,
diff --git a/apps/web/src/components/backgroundThreadAnnouncement.ts b/apps/web/src/components/backgroundThreadAnnouncement.ts
index 10ca422d0f3cb..e7ad9b0c08103 100644
--- a/apps/web/src/components/backgroundThreadAnnouncement.ts
+++ b/apps/web/src/components/backgroundThreadAnnouncement.ts
@@ -1,7 +1,10 @@
import type { OrchestrationV2RunStatus, RunId } from "@t3tools/contracts";
import type { SidebarThreadSummary } from "../types";
-import { runOutcomeText, THREAD_STATUS_TEXT } from "./chat/threadActivityAnnouncement";
+import {
+ runOutcomeText,
+ THREAD_STATUS_TEXT,
+} from "@t3tools/client-runtime/state/thread-activity-announcement";
export interface BackgroundThreadSnapshot {
readonly key: string;
diff --git a/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx b/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx
index 0dc54f3f2df00..5d367cf851d75 100644
--- a/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx
+++ b/apps/web/src/components/chat/ThreadActivityAnnouncer.tsx
@@ -8,7 +8,7 @@ import {
nextThreadAnnouncement,
type ThreadActivitySnapshot,
type ThreadAnnouncementMemory,
-} from "./threadActivityAnnouncement";
+} from "@t3tools/client-runtime/state/thread-activity-announcement";
import {
nextTurnDetailAnnouncement,
NO_TURN_DETAIL,
diff --git a/apps/web/src/components/chat/usePromptSuggestion.ts b/apps/web/src/components/chat/usePromptSuggestion.ts
index b3f52b2a7dc78..595841629c023 100644
--- a/apps/web/src/components/chat/usePromptSuggestion.ts
+++ b/apps/web/src/components/chat/usePromptSuggestion.ts
@@ -6,7 +6,7 @@ import { useMediaQuery } from "../../hooks/useMediaQuery";
import { useServerConfigs } from "../../state/entities";
import { orchestrationEnvironment } from "../../state/orchestration";
import { useEnvironmentQuery } from "../../state/query";
-import { announcedRun } from "./threadActivityAnnouncement";
+import { announcedRun } from "@t3tools/client-runtime/state/thread-activity-announcement";
// Dismissed suggestions, keyed by environment and run, shared by every mounted composer and kept
// across remounts. Run ids derive from thread ids, which can repeat across environments.
diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json
index 7c5b8ef1cb27b..d1e74151e53e3 100644
--- a/packages/client-runtime/package.json
+++ b/packages/client-runtime/package.json
@@ -335,6 +335,10 @@
"types": "./src/state/threads.ts",
"default": "./src/state/threads.ts"
},
+ "./state/thread-activity-announcement": {
+ "types": "./src/state/threadActivityAnnouncement.ts",
+ "default": "./src/state/threadActivityAnnouncement.ts"
+ },
"./state/subagent-display": {
"types": "./src/state/subagentDisplay.ts",
"default": "./src/state/subagentDisplay.ts"
diff --git a/apps/web/src/components/chat/threadActivityAnnouncement.test.ts b/packages/client-runtime/src/state/threadActivityAnnouncement.test.ts
similarity index 99%
rename from apps/web/src/components/chat/threadActivityAnnouncement.test.ts
rename to packages/client-runtime/src/state/threadActivityAnnouncement.test.ts
index b47895426306e..f40613b9910af 100644
--- a/apps/web/src/components/chat/threadActivityAnnouncement.test.ts
+++ b/packages/client-runtime/src/state/threadActivityAnnouncement.test.ts
@@ -13,7 +13,7 @@ import {
nextThreadAnnouncement,
type ThreadActivitySnapshot,
type ThreadAnnouncementMemory,
-} from "./threadActivityAnnouncement";
+} from "./threadActivityAnnouncement.ts";
const firstRun = RunId.make("run-1");
const secondRun = RunId.make("run-2");
diff --git a/apps/web/src/components/chat/threadActivityAnnouncement.ts b/packages/client-runtime/src/state/threadActivityAnnouncement.ts
similarity index 100%
rename from apps/web/src/components/chat/threadActivityAnnouncement.ts
rename to packages/client-runtime/src/state/threadActivityAnnouncement.ts
From d47f2e03ff4b394b5fe48aa67cacd732a6c5ba02 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 11 Nov 2026 17:36:31 -0800
Subject: [PATCH 052/253] fix(server): providers keep their saved status until
the first check finishes (#34678)
---
.../src/provider/ProviderRegistry.test.ts | 98 +++++++++++++++++++
apps/server/src/provider/ProviderRegistry.ts | 52 +++++++---
.../src/server/managedProvider.test.ts | 2 +
.../src/server/managedProvider.ts | 5 +-
packages/provider-core/src/server/snapshot.ts | 2 +
5 files changed, 144 insertions(+), 15 deletions(-)
diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts
index 1cf9eb26b03c0..5882611e073ed 100644
--- a/apps/server/src/provider/ProviderRegistry.test.ts
+++ b/apps/server/src/provider/ProviderRegistry.test.ts
@@ -1270,6 +1270,9 @@ it.layer(
}),
),
getSnapshot: Ref.get(currentProvider),
+ isAwaitingFirstCheck: Ref.get(currentProvider).pipe(
+ Effect.map((provider) => provider === pendingProvider),
+ ),
refresh: Ref.get(nextProvider).pipe(
Effect.tap((provider) => Ref.set(currentProvider, provider)),
),
@@ -1303,6 +1306,23 @@ it.layer(
? retainedModels
: [customModel, ...cachedProvider.models];
assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, expectedModels);
+ if (!restarted) {
+ const probeFields = ({ status, installed, auth, version }: ServerProvider) => ({
+ status,
+ installed,
+ auth,
+ version,
+ });
+ // Boot reads the probe state from the cache, not the pending snapshot, and never persists the pending one.
+ assert.deepStrictEqual(
+ probeFields((yield* registry.getProviders)[0]!),
+ probeFields(cachedProvider),
+ );
+ assert.deepStrictEqual(
+ probeFields((yield* readProviderStatusCache(filePath))!),
+ probeFields(cachedProvider),
+ );
+ }
yield* registry.refreshInstance(instance.instanceId);
assert.deepStrictEqual(
@@ -1335,6 +1355,84 @@ it.layer(
),
),
);
+ it.effect("keeps a check that finished before boot over the cached status", () =>
+ Effect.gen(function* () {
+ const config = yield* ServerConfig.ServerConfig;
+ const filePath = yield* resolveProviderStatusCachePath({
+ cacheDir: config.providerStatusCacheDir,
+ instanceId: cachedProvider.instanceId,
+ });
+ const instance = {
+ instanceId: cachedProvider.instanceId,
+ driverKind: cachedProvider.driver,
+ continuationIdentity: {
+ driverKind: cachedProvider.driver,
+ continuationKey: "codex:instance:codex-personal",
+ },
+ displayName: undefined,
+ enabled: true,
+ snapshot: {
+ resolveMaintenance: () =>
+ Effect.succeed(
+ makeManualOnlyProviderMaintenanceCapabilities({
+ provider: cachedProvider.driver,
+ packageName: null,
+ }),
+ ),
+ getSnapshot: Effect.succeed(failedProvider),
+ isAwaitingFirstCheck: Effect.succeed(false),
+ refresh: Effect.succeed(failedProvider),
+ streamChanges: Stream.empty,
+ applyUsageLimits: () => Effect.void,
+ },
+ orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
+ textGeneration: {} as ProviderInstance["textGeneration"],
+ } satisfies ProviderInstance;
+ const layerInstanceRegistry = Layer.succeed(
+ ProviderInstanceRegistry.ProviderInstanceRegistry,
+ {
+ getInstance: (id) =>
+ Effect.succeed(id === instance.instanceId ? instance : undefined),
+ listInstances: Effect.succeed([instance]),
+ listUnavailable: Effect.succeed([]),
+ streamChanges: Stream.empty,
+ subscribeChanges: Effect.flatMap(PubSub.unbounded(), PubSub.subscribe),
+ },
+ );
+
+ // First boot has no cache file; the second has a stale ready one.
+ for (const hasCache of [false, true]) {
+ if (hasCache) {
+ yield* writeProviderStatusCache({
+ filePath,
+ provider: { ...cachedProvider, status: "ready" },
+ });
+ }
+ yield* Effect.gen(function* () {
+ const registry = yield* ProviderRegistry.ProviderRegistry;
+ assert.strictEqual((yield* registry.getProviders)[0]?.status, failedProvider.status);
+ assert.strictEqual(
+ (yield* readProviderStatusCache(filePath))?.status,
+ failedProvider.status,
+ );
+ }).pipe(
+ Effect.provide(
+ ProviderRegistry.layer.pipe(
+ Layer.provide(layerInstanceRegistry),
+ Layer.provide(layerUnusedMutator),
+ ),
+ ),
+ Effect.scoped,
+ );
+ }
+ }).pipe(
+ Effect.provide(
+ ServerConfig.layerTest(process.cwd(), {
+ prefix: "t3-codex-probed-before-boot-",
+ }).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
+ ),
+ ),
+ );
});
describe("Antigravity model inventories", () => {
diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts
index fe5375136dc25..b36363de36f3a 100644
--- a/apps/server/src/provider/ProviderRegistry.ts
+++ b/apps/server/src/provider/ProviderRegistry.ts
@@ -386,10 +386,17 @@ export const layer = Layer.effect(
}
fallbackByInstance.set(source.instanceId, provider);
}
+ // Read after the snapshots: a snapshot read as awaiting is the pre-check placeholder.
+ const awaitingBootInstances = new Set();
+ for (const instance of bootInstances) {
+ if (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false)) {
+ awaitingBootInstances.add(instance);
+ }
+ }
- const cachedProviders = yield* Effect.forEach(
+ const bootProviders = yield* Effect.forEach(
bootSources,
- (source) =>
+ (source, index) =>
Effect.gen(function* () {
const filePath = yield* resolveProviderStatusCachePath({
cacheDir: config.providerStatusCacheDir,
@@ -399,11 +406,15 @@ export const layer = Layer.effect(
if (fallbackProvider === undefined) {
return undefined;
}
+ // A completed check is seeded by the boot upsert instead, which persists it.
+ const placeholder = awaitingBootInstances.has(bootInstances[index]!)
+ ? fallbackProvider
+ : undefined;
return yield* readProviderStatusCache(filePath).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.flatMap((cachedProvider) => {
if (cachedProvider === undefined) {
- return Effect.void.pipe(Effect.as(undefined as ServerProvider | undefined));
+ return Effect.succeed(placeholder);
}
const correlation = {
cachedProvider,
@@ -416,7 +427,7 @@ export const layer = Layer.effect(
cachedInstanceId: cachedProvider.instanceId ?? null,
driver: source.driverKind,
cachedDriver: cachedProvider.driver ?? null,
- }).pipe(Effect.as(undefined as ServerProvider | undefined));
+ }).pipe(Effect.as(placeholder));
}
return Effect.succeed(hydrateCachedProvider(correlation));
}),
@@ -441,7 +452,7 @@ export const layer = Layer.effect(
ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility,
);
const providersRef = yield* Ref.make>(
- cachedProviders.map((provider) => classifyCompatibility(provider, initialManifest)),
+ bootProviders.map((provider) => classifyCompatibility(provider, initialManifest)),
);
const workspaceRefreshesRef = yield* Ref.make<
ReadonlyMap>>
@@ -551,14 +562,8 @@ export const layer = Layer.effect(
});
const compatibilityRefreshRunning = yield* Ref.make(false);
- const syncProvider = Effect.fn("syncProvider")(function* (
- provider: ServerProvider,
- options?: {
- readonly publish?: boolean;
- },
- ) {
- const providers = yield* upsertProviders([provider], options);
- // Reclassify the current model after fetch; republishing the old probe could overwrite newer health results.
+ // Reclassify the current model after fetch; republishing the old probe could overwrite newer health results.
+ const refreshCompatibility = Effect.gen(function* () {
if (!(yield* Ref.getAndSet(compatibilityRefreshRunning, true))) {
yield* manifestService.refresh.pipe(
Effect.andThen(upsertProviders([], { persist: false })),
@@ -566,6 +571,15 @@ export const layer = Layer.effect(
Effect.forkIn(serviceScope),
);
}
+ });
+ const syncProvider = Effect.fn("syncProvider")(function* (
+ provider: ServerProvider,
+ options?: {
+ readonly publish?: boolean;
+ },
+ ) {
+ const providers = yield* upsertProviders([provider], options);
+ yield* refreshCompatibility;
return providers;
});
@@ -861,6 +875,13 @@ export const layer = Layer.effect(
Effect.gen(function* () {
const source = buildSnapshotSource(instance);
const provider = yield* source.getSnapshot;
+ // Boot shows the cached status until this instance's first check publishes a result.
+ if (
+ awaitingBootInstances.has(instance) &&
+ (yield* instance.snapshot.isAwaitingFirstCheck ?? Effect.succeed(false))
+ ) {
+ return yield* refreshCompatibility;
+ }
yield* correlateSnapshotWithSource(source, provider).pipe(
Effect.flatMap(syncProvider),
);
@@ -918,7 +939,10 @@ export const layer = Layer.effect(
Scope.provide(serviceScope),
);
- yield* upsertProviders(fallbackProviders, { publish: false });
+ yield* upsertProviders(
+ fallbackProviders.filter((_, index) => !awaitingBootInstances.has(bootInstances[index]!)),
+ { publish: false },
+ );
const instanceChanges = yield* instanceRegistry.subscribeChanges;
yield* syncLiveSources;
yield* Stream.runForEach(
diff --git a/packages/provider-core/src/server/managedProvider.test.ts b/packages/provider-core/src/server/managedProvider.test.ts
index c9e5a6e01390d..7a7e08ceddfb7 100644
--- a/packages/provider-core/src/server/managedProvider.test.ts
+++ b/packages/provider-core/src/server/managedProvider.test.ts
@@ -272,6 +272,7 @@ describe("makeManagedServerProvider", () => {
const initial = yield* provider.getSnapshot;
assert.deepStrictEqual(initial, initialSnapshot);
+ assert.strictEqual(yield* provider.isAwaitingFirstCheck!, true);
const updatesFiber = yield* Stream.take(provider.streamChanges, 1).pipe(
Stream.runCollect,
@@ -287,6 +288,7 @@ describe("makeManagedServerProvider", () => {
assert.deepStrictEqual(updates, [refreshedSnapshot]);
assert.deepStrictEqual(latest, refreshedSnapshot);
+ assert.strictEqual(yield* provider.isAwaitingFirstCheck!, false);
assert.strictEqual(yield* Ref.get(checkCalls), 1);
}),
).pipe(Effect.provide(layerAlwaysRunTest)),
diff --git a/packages/provider-core/src/server/managedProvider.ts b/packages/provider-core/src/server/managedProvider.ts
index a766c95d62535..03cd1491806fe 100644
--- a/packages/provider-core/src/server/managedProvider.ts
+++ b/packages/provider-core/src/server/managedProvider.ts
@@ -28,6 +28,7 @@ interface ProviderSnapshotState {
readonly enrichmentGeneration: number;
// null preserves an explicitly cleared plan across probes and enrichment.
readonly usageAuthLabel: string | null | undefined;
+ readonly checked: boolean;
}
function withUsageLimits(
@@ -79,6 +80,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
snapshot: initialSnapshot,
enrichmentGeneration: 0,
usageAuthLabel: undefined,
+ checked: false,
});
const settingsRef = yield* Ref.make(initialSettings);
const enrichmentFiberRef = yield* Ref.make | null>(null);
@@ -218,7 +220,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
);
return [
{ snapshot, generation },
- { snapshot, enrichmentGeneration: generation, usageAuthLabel },
+ { snapshot, enrichmentGeneration: generation, usageAuthLabel, checked: true },
] as const;
},
);
@@ -425,6 +427,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
return {
resolveMaintenance: input.resolveMaintenance,
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
+ isAwaitingFirstCheck: Ref.get(snapshotStateRef).pipe(Effect.map((state) => !state.checked)),
refresh: input
.resolveMaintenance({ fresh: true })
.pipe(Effect.andThen(refreshSnapshot), Effect.tapError(Effect.logError), Effect.orDie),
diff --git a/packages/provider-core/src/server/snapshot.ts b/packages/provider-core/src/server/snapshot.ts
index 6cb7ea15c5b10..2af61f3adcd07 100644
--- a/packages/provider-core/src/server/snapshot.ts
+++ b/packages/provider-core/src/server/snapshot.ts
@@ -21,6 +21,8 @@ export interface ManagedServerProvider {
readonly fresh?: boolean;
}) => Effect.Effect;
readonly getSnapshot: Effect.Effect;
+ /** True while getSnapshot still returns the placeholder from before the first completed check. */
+ readonly isAwaitingFirstCheck?: Effect.Effect;
readonly refresh: Effect.Effect;
readonly refreshUsage?: Effect.Effect;
readonly streamChanges: Stream.Stream;
From a21b43fc70fe1c835dc817cb0281befbea95a58c Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 11 Nov 2026 17:36:42 -0800
Subject: [PATCH 053/253] fix(mobile): choosing a project for a draft whose
project is gone keeps the draft (#26800)
---
.../features/threads/NewTaskDraftScreen.tsx | 18 +++++++++----
.../features/threads/NewTaskRouteScreen.tsx | 25 ++++++++++++++++++-
.../threads/new-task-flow-provider.tsx | 18 ++++++++-----
.../threads/new-task-flow-state.test.ts | 7 ++++--
.../features/threads/new-task-flow-state.ts | 5 +++-
.../src/state/use-composer-drafts.test.ts | 25 +++++++++++++++++++
apps/mobile/src/state/use-composer-drafts.ts | 11 ++++++++
7 files changed, 94 insertions(+), 15 deletions(-)
diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
index 2bc26707324e2..e10fdc64649f9 100644
--- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx
@@ -281,11 +281,15 @@ export function NewTaskDraftScreen(props: {
),
);
// A route naming a draft that is gone, or whose project is gone, also
- // returns to the picker.
- const isRouteDraftMissing =
- props.draftId !== undefined && flow.missingRouteDraftId === props.draftId;
+ // returns to the picker; a draft that survives goes along with it.
+ const unopenableRouteDraftKind =
+ props.draftId !== undefined && flow.unopenableRouteDraft?.draftId === props.draftId
+ ? flow.unopenableRouteDraft.kind
+ : null;
+ const pickerDraftId = unopenableRouteDraftKind === "pickProject" ? props.draftId : undefined;
const isProjectPickerReturnActive =
- (isReturningToProjectPicker && !requestedInitialProjectAvailable) || isRouteDraftMissing;
+ (isReturningToProjectPicker && !requestedInitialProjectAvailable) ||
+ unopenableRouteDraftKind !== null;
const isIncomingShareAwaitingServerConfig = Boolean(
incomingShare?.attachments.some((attachment) => attachment.type === "file") &&
selectedEnvironmentServerConfig === null,
@@ -388,7 +392,10 @@ export function NewTaskDraftScreen(props: {
// Wait for usePreventRemove to disable before replacing, or the transfer guard swallows the fallback.
const frame = requestAnimationFrame(() => {
navigation.dispatch(
- StackActions.replace("NewTaskProject", { incomingShareId: props.incomingShareId }),
+ StackActions.replace("NewTaskProject", {
+ incomingShareId: props.incomingShareId,
+ draftId: pickerDraftId,
+ }),
);
});
return () => cancelAnimationFrame(frame);
@@ -396,6 +403,7 @@ export function NewTaskDraftScreen(props: {
isProjectPickerReturnActive,
isReturningToProjectPicker,
navigation,
+ pickerDraftId,
props.incomingShareId,
requestedInitialProjectAvailable,
]);
diff --git a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
index d904c3c67c543..ac9e2ce813636 100644
--- a/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/NewTaskRouteScreen.tsx
@@ -29,6 +29,7 @@ import { ProjectFavicon } from "../../components/ProjectFavicon";
import { useProjects, useServerConfigs } from "../../state/entities";
import { projectEnvironment } from "../../state/projects";
import { useAtomCommand } from "../../state/use-atom-command";
+import { retargetSavedNewTaskDraft } from "../../state/use-composer-drafts";
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import type { WorkspaceState } from "../../state/workspaceModel";
import { useWorkspaceState } from "../../state/workspace";
@@ -44,6 +45,8 @@ import { useSelectWorkspaceDetail } from "../layout/workspace/useSelectWorkspace
type NewTaskRouteParams = {
readonly incomingShareId?: string | string[];
+ /** An existing draft whose project is gone; the chosen project takes it over. */
+ readonly draftId?: string | string[];
readonly prompt?: string | string[];
readonly repo?: string | string[];
readonly pr?: string | string[];
@@ -164,6 +167,9 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps found,
+ () => null,
+ );
+ if (retargeted === null) {
+ Dialog.alert("Could not change project", "Saved drafts could not be loaded. Try again.");
+ return;
+ }
+ const draftId = retargeted ? routeDraftId : undefined;
selectDetail({
name: "Thread",
params: {
draft: {
environmentId: String(project.environmentId),
projectId: String(project.id),
+ draftId,
incomingShareId: incomingShare?.id,
},
},
diff --git a/apps/mobile/src/features/threads/new-task-flow-provider.tsx b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
index 5b42c28adc518..0e0bd6dea208e 100644
--- a/apps/mobile/src/features/threads/new-task-flow-provider.tsx
+++ b/apps/mobile/src/features/threads/new-task-flow-provider.tsx
@@ -168,11 +168,14 @@ type NewTaskFlowContextValue = {
/** The flow's project, read when a continuation resumes after an await. */
readonly getSelectedProjectKey: () => string | null;
/**
- * The draft id of the route this flow serves when that draft, or its
- * project, is gone. Only the topmost draft route is served, so a screen
- * compares this with its own draft id.
+ * The route this flow serves when its draft cannot open: the draft is gone
+ * (`missing`) or only its project is (`pickProject`). Only the topmost draft
+ * route is served, so a screen compares `draftId` with its own draft id.
*/
- readonly missingRouteDraftId: string | null;
+ readonly unopenableRouteDraft: {
+ readonly draftId: string;
+ readonly kind: "missing" | "pickProject";
+ } | null;
readonly selectEnvironment: (environmentId: EnvironmentId) => void;
readonly switchEnvironment: (environmentId: EnvironmentId) => Promise;
readonly switchingToEnvironmentId: EnvironmentId | null;
@@ -851,8 +854,11 @@ export function NewTaskFlowProvider(
providerGroups,
setProject,
getSelectedProjectKey: () => readFlow().projectKey,
- missingRouteDraftId:
- routeDraftResolution.kind === "missing" ? (props.routeDraftId ?? null) : null,
+ unopenableRouteDraft:
+ props.routeDraftId !== undefined &&
+ (routeDraftResolution.kind === "missing" || routeDraftResolution.kind === "pickProject")
+ ? { draftId: props.routeDraftId, kind: routeDraftResolution.kind }
+ : null,
selectEnvironment,
switchEnvironment,
switchingToEnvironmentId,
diff --git a/apps/mobile/src/features/threads/new-task-flow-state.test.ts b/apps/mobile/src/features/threads/new-task-flow-state.test.ts
index 73d2a2af4cb36..d0783714882f6 100644
--- a/apps/mobile/src/features/threads/new-task-flow-state.test.ts
+++ b/apps/mobile/src/features/threads/new-task-flow-state.test.ts
@@ -111,11 +111,14 @@ describe("resolveRouteDraft", () => {
).toMatchObject({ kind: "open", flow: { environmentId: environmentB } });
});
- it("reports a draft that is gone or whose project is gone", () => {
+ it("reports a draft that is gone", () => {
expect(resolveRouteDraft({ ...base, stamp: undefined })).toEqual({ kind: "missing" });
+ });
+
+ it("asks for a project for the same draft when its project is gone", () => {
expect(
resolveRouteDraft({ ...base, projects: [{ environmentId, id: ProjectId.make("other") }] }),
- ).toEqual({ kind: "missing" });
+ ).toEqual({ kind: "pickProject" });
});
});
diff --git a/apps/mobile/src/features/threads/new-task-flow-state.ts b/apps/mobile/src/features/threads/new-task-flow-state.ts
index 5b5fff2b2af18..256a2022997e9 100644
--- a/apps/mobile/src/features/threads/new-task-flow-state.ts
+++ b/apps/mobile/src/features/threads/new-task-flow-state.ts
@@ -75,6 +75,8 @@ export type RouteDraftResolution =
| { readonly kind: "none" }
| { readonly kind: "pending" }
| { readonly kind: "missing" }
+ /** The draft survives but its project is gone: pick another for it. */
+ | { readonly kind: "pickProject" }
| { readonly kind: "open"; readonly flow: NewTaskFlowState };
export function resolveRouteDraft(input: {
@@ -101,7 +103,8 @@ export function resolveRouteDraft(input: {
const loaded = input.projects.some(
(project) => project.environmentId === stamp.environmentId && project.id === stamp.projectId,
);
- if (!loaded) return input.stampedEnvironmentLoading ? { kind: "pending" } : { kind: "missing" };
+ if (!loaded)
+ return input.stampedEnvironmentLoading ? { kind: "pending" } : { kind: "pickProject" };
return {
kind: "open",
flow: {
diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.ts
index f8a14977acca9..f7fe9ebbcf57c 100644
--- a/apps/mobile/src/state/use-composer-drafts.test.ts
+++ b/apps/mobile/src/state/use-composer-drafts.test.ts
@@ -205,6 +205,7 @@ import {
restoreComposerDraftSnapshotState,
restoreCloudComposerDrafts,
retargetNewTaskDraft,
+ retargetSavedNewTaskDraft,
setComposerDraftText,
insertComposerDraftContext,
insertComposerDraftText,
@@ -1933,6 +1934,30 @@ describe("mobile composer drafts", () => {
expect(findNewTaskDraftKeys(appAtomRegistry.get(composerDraftsAtom), to)).toEqual([key]);
});
+ it("retargets a saved new-task draft only after drafts load", async () => {
+ const from = {
+ environmentId: EnvironmentId.make("environment-1"),
+ projectId: ProjectId.make("project-1"),
+ };
+ const to = {
+ environmentId: EnvironmentId.make("environment-1"),
+ projectId: ProjectId.make("project-2"),
+ };
+ const key = createNewTaskDraft(from);
+ setComposerDraftText(key, "kept through a cold start");
+ await flushComposerDrafts();
+ appAtomRegistry.set(composerDraftsAtom, {});
+ resetComposerDraftsLoadState();
+
+ await expect(retargetSavedNewTaskDraft(key, to)).resolves.toBe(true);
+ expect(getComposerDraftSnapshot(key)).toMatchObject({
+ text: "kept through a cold start",
+ project: to,
+ });
+ await expect(retargetSavedNewTaskDraft(`${key}-gone`, to)).resolves.toBe(false);
+ expect(appAtomRegistry.get(composerDraftsAtom)[`${key}-gone`]).toBeUndefined();
+ });
+
it("merges persisted option memory without replacing newer choices", async () => {
composerDraftFileMocks.setDocument({
schemaVersion: 1,
diff --git a/apps/mobile/src/state/use-composer-drafts.ts b/apps/mobile/src/state/use-composer-drafts.ts
index b233034c5cf84..2e4e53ef6dd45 100644
--- a/apps/mobile/src/state/use-composer-drafts.ts
+++ b/apps/mobile/src/state/use-composer-drafts.ts
@@ -1999,6 +1999,17 @@ export function retargetNewTaskDraft(
});
}
+/** Retargets a saved draft once drafts load; an absent one is not created. */
+export async function retargetSavedNewTaskDraft(
+ draftKey: string,
+ project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
+): Promise {
+ await waitForComposerDraftsLoaded();
+ if (appAtomRegistry.get(composerDraftsAtom)[draftKey] === undefined) return false;
+ retargetNewTaskDraft(draftKey, project);
+ return true;
+}
+
export function findNewTaskDraftKeys(
drafts: Readonly>,
project: { readonly environmentId: EnvironmentId; readonly projectId: ProjectId },
From d63db064363e3ba9c12310ed5efb5c86c35d1caf Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 11 Nov 2026 17:58:54 -0800
Subject: [PATCH 054/253] fix(contracts): side chats open after an abandoned
worktree setup (#34686)
---
.../src/state/use-thread-composer-state.ts | 2 +-
.../src/orchestration-v2/Orchestrator.ts | 2 +-
.../ThreadFork.execution.test.ts | 62 ++++++++++++++++++-
apps/web/src/components/ChatView.tsx | 2 +-
packages/contracts/src/orchestrationV2.ts | 18 ------
.../shared/src/orchestrationV2ThreadError.ts | 19 ++++++
6 files changed, 83 insertions(+), 22 deletions(-)
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index 8b88e489620ef..11b38251cec77 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -29,7 +29,6 @@ import {
DEFAULT_PROVIDER_INTERACTION_MODE,
MessageId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
- orchestrationV2WorktreePending,
type EnvironmentId,
type ModelSelection,
type RuntimeMode,
@@ -90,6 +89,7 @@ import {
useComposerDraftSettings,
} from "./use-composer-drafts";
import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger";
+import { orchestrationV2WorktreePending } from "@t3tools/shared/orchestrationV2ThreadError";
import {
compactionBlocksSteering,
resolveComposerDispatchMode,
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 295bdde820e61..851715cb091bc 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -8,6 +8,7 @@ import type {
import {
latestExecutedRun,
latestRootProviderFailure,
+ orchestrationV2WorktreePending,
runRanAfter,
usageLimitBlockedRun,
} from "@t3tools/shared/orchestrationV2ThreadError";
@@ -62,7 +63,6 @@ import {
latestProviderTurnForAttempt,
parseGoalCommand,
orchestrationV2RunWorkStartedAt,
- orchestrationV2WorktreePending,
ProviderInstanceId,
ProviderInteractionMode,
isRuntimeModeAbove,
diff --git a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
index fa6fcea911388..7cc040403ae9f 100644
--- a/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadFork.execution.test.ts
@@ -727,7 +727,12 @@ const writeParentRun = (input: {
queuePosition: null,
requestedAt: now,
startedAt: now,
- completedAt: input.status === "completed" ? now : null,
+ completedAt:
+ input.status === "preparing" ||
+ input.status === "running" ||
+ input.status === "queued"
+ ? null
+ : now,
checkpointId: input.stable ? CheckpointId.make(`${input.runId}:checkpoint`) : null,
contextHandoffId: null,
...(input.status === "preparing" ||
@@ -1029,6 +1034,61 @@ it.effect("a side chat waits for the parent's new worktree, also after its setup
}).pipe(Effect.provide(forkCases[0]!.layer)),
);
+it.effect("a side chat opens once a later run has worked in the project checkout", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const parentId = ThreadId.make("side-chat-worktree-abandoned-parent");
+ const sideChatId = ThreadId.make("side-chat-worktree-abandoned-child");
+ yield* createParent(parentId);
+ yield* writeParentRun({
+ threadId: parentId,
+ runId: RunId.make("side-chat-worktree-abandoned-run-1"),
+ ordinal: 1,
+ status: "interrupted",
+ text: "Stopped during setup",
+ });
+ yield* writeParentRun({
+ threadId: parentId,
+ runId: RunId.make("side-chat-worktree-abandoned-run-2"),
+ ordinal: 2,
+ status: "completed",
+ text: "Worked in the project checkout",
+ stable: true,
+ });
+
+ yield* forkSideChat("side-chat-worktree-abandoned-fork", parentId, sideChatId);
+ assert.isNull((yield* orchestrator.getThreadProjection(sideChatId)).thread.deletedAt);
+
+ // A retried setup that is running again, or failed again, comes after the later run.
+ for (const status of ["preparing", "failed"] as const) {
+ const retriedParentId = ThreadId.make(`side-chat-worktree-retried-parent-${status}`);
+ yield* createParent(retriedParentId);
+ yield* writeParentRun({
+ threadId: retriedParentId,
+ runId: RunId.make(`side-chat-worktree-retried-run-2-${status}`),
+ ordinal: 2,
+ status: "completed",
+ text: "Worked in the project checkout",
+ stable: true,
+ });
+ yield* TestClock.adjust("1 second");
+ yield* writeParentRun({
+ threadId: retriedParentId,
+ runId: RunId.make(`side-chat-worktree-retried-run-1-${status}`),
+ ordinal: 1,
+ status,
+ text: "Retried setup",
+ });
+ const rejected = yield* forkSideChat(
+ `side-chat-worktree-retried-fork-${status}`,
+ retriedParentId,
+ ThreadId.make(`side-chat-worktree-retried-child-${status}`),
+ ).pipe(Effect.flip);
+ assert.include(String(rejected.cause), "has no worktree yet", status);
+ }
+ }).pipe(Effect.provide(forkCases[0]!.layer)),
+);
+
it.effect("closing a side chat deletes it only while unused; a deleted parent takes no more", () =>
Effect.gen(function* () {
const orchestrator = yield* Orchestrator.OrchestratorV2;
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index d3f3f9125df5e..153428f2b6755 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -64,7 +64,6 @@ import {
type AssistantCitation,
type ChatFileAttachment,
isProviderNativeSubagentThread,
- orchestrationV2WorktreePending,
type EnvironmentId,
type MessageId,
type ModelSelection,
@@ -117,6 +116,7 @@ import {
import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
import { projectScriptCwd, resolveProjectScripts } from "@t3tools/shared/projectScripts";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
+import { orchestrationV2WorktreePending } from "@t3tools/shared/orchestrationV2ThreadError";
import { resolveThreadReferenceCopyTarget } from "@t3tools/client-runtime/thread-reference";
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
import { useAtomValue } from "@effect/atom-react";
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index 4cb4984b74baa..afe8802139a52 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -728,24 +728,6 @@ export function orchestrationV2RunWorkStartedAt(
return run.workStartedAt ?? run.startedAt ?? run.requestedAt;
}
-/**
- * Work started now would run in the project checkout, not the worktree the thread asked for. A
- * failed or interrupted setup leaves the request standing until a worktree exists.
- */
-export function orchestrationV2WorktreePending(
- worktreePath: string | null,
- runs: ReadonlyArray>,
-): boolean {
- return (
- worktreePath === null &&
- runs.some(
- (run) =>
- (run.status === "preparing" || run.status === "failed" || run.status === "interrupted") &&
- run.workspacePreparation?.type === "worktree",
- )
- );
-}
-
export const OrchestrationV2RunAttempt = Schema.Struct({
id: RunAttemptId,
// Provider-thread rows can be reused after recovery; retain the native input destination.
diff --git a/packages/shared/src/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.ts
index 5b9940729e2e1..3ba3ba2bf3247 100644
--- a/packages/shared/src/orchestrationV2ThreadError.ts
+++ b/packages/shared/src/orchestrationV2ThreadError.ts
@@ -64,6 +64,25 @@ export function latestExecutedRun(
return latest;
}
+/**
+ * Work started now would run in the project checkout, not the worktree the thread asked for. A
+ * failed or interrupted setup leaves the request standing until a worktree exists or later work
+ * has run past it.
+ */
+export function orchestrationV2WorktreePending(
+ worktreePath: string | null,
+ runs: ReadonlyArray,
+): boolean {
+ const latest = latestExecutedRun(runs);
+ return (
+ worktreePath === null &&
+ (latest?.status === "preparing" ||
+ latest?.status === "failed" ||
+ latest?.status === "interrupted") &&
+ latest.workspacePreparation?.type === "worktree"
+ );
+}
+
/** Held queues can execute out of ordinal order; unfinished runs count as latest. */
export function runRanAfter(
run: Pick,
From 32882540fb1296bd1870253f3fe32bc8369f8a17 Mon Sep 17 00:00:00 2001
From: Pouya Rezvani <32917154+pouyarezvani@users.noreply.github.com>
Date: Wed, 11 Nov 2026 18:11:40 -0800
Subject: [PATCH 055/253] fix(web): interruption footer label sits on the
reason's baseline (#34685)
---
apps/web/src/components/chat/TimelineSystemDivider.tsx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/apps/web/src/components/chat/TimelineSystemDivider.tsx b/apps/web/src/components/chat/TimelineSystemDivider.tsx
index 503c30d2add7b..cb0489998f04a 100644
--- a/apps/web/src/components/chat/TimelineSystemDivider.tsx
+++ b/apps/web/src/components/chat/TimelineSystemDivider.tsx
@@ -19,7 +19,7 @@ export function TimelineSystemDivider(props: {
<>
From 4ae66e2e86deb303cc1728cece1b5a68f1073721 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 11 Nov 2026 18:28:51 -0800
Subject: [PATCH 056/253] fix(opencode): project-defined models appear in that
project's picker (#24585)
---
.../settings/ScheduledTaskPickerScreens.tsx | 1 +
.../features/threads/NewTaskDraftScreen.tsx | 8 +-
.../src/features/threads/ThreadComposer.tsx | 8 +-
.../features/threads/ThreadSettingsSheet.tsx | 75 ++++++-
.../threads/new-task-flow-provider.tsx | 14 +-
.../threads/use-composer-command-menu.ts | 8 +-
apps/mobile/src/lib/modelOptions.ts | 11 +
.../provider-workspace-snapshot-refresh.ts | 9 +
.../src/provider/ProviderRegistry.test.ts | 187 +++++++++++++++++
apps/server/src/provider/ProviderRegistry.ts | 45 ++++-
apps/web/src/components/ChatView.tsx | 23 ++-
apps/web/src/components/chat/ChatComposer.tsx | 1 +
.../components/chat/ComposerControlsBar.tsx | 2 +
.../components/chat/ModelPickerContent.tsx | 12 +-
.../components/chat/ProviderModelPicker.tsx | 2 +
.../useProviderWorkspaceSnapshotRefresh.ts | 10 +-
docs/user/providers-opencode.md | 4 +
.../client-runtime/src/providerSkills.test.ts | 41 ++++
packages/client-runtime/src/providerSkills.ts | 31 ++-
packages/client-runtime/src/state/server.ts | 1 +
packages/contracts/src/server.ts | 10 +
packages/provider-core/src/server/driver.ts | 7 +-
.../src/server/OpenCodeRuntime.ts | 56 +++---
.../src/server/driver.test.ts | 190 ++++++++++++++++++
.../provider-opencode/src/server/driver.ts | 97 ++++++---
.../src/server/openCode2Catalog.ts | 46 +++--
.../provider-opencode/src/server/status.ts | 128 ++++++++----
27 files changed, 861 insertions(+), 166 deletions(-)
create mode 100644 apps/mobile/src/state/provider-workspace-snapshot-refresh.ts
diff --git a/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx b/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx
index 182b2804b8402..1ea4602da9241 100644
--- a/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx
+++ b/apps/mobile/src/features/settings/ScheduledTaskPickerScreens.tsx
@@ -67,6 +67,7 @@ export function ScheduledTaskModelPickerRouteScreen() {
1 ? (["cycleHost"] as const) : [];
useHardwareKeyboardCommand(cycleEnvironmentCommands, cycleEnvironment);
- const composerWorkspaceCwd =
- (flow.workspaceMode === "worktree"
- ? selectedProject?.workspaceRoot
- : (flow.selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
const preventRemove =
(isIncomingShareHoldingRoute && !isProjectPickerReturnActive) || flow.submitting;
usePreventRemove(preventRemove, () => undefined);
@@ -971,7 +967,7 @@ export function NewTaskDraftScreen(props: {
+
}
draftMode={{
content: heroViewport,
@@ -1012,7 +1008,7 @@ export function NewTaskDraftScreen(props: {
onCancelQueuedRunEdit={() => {}}
onRemoveQueuedEditAttachment={() => {}}
projectWorkspaceRoot={selectedProject.workspaceRoot}
- threadCwd={composerWorkspaceCwd}
+ threadCwd={flow.workspaceCwd}
selectedThreadQueueCount={0}
queuedMessages={[]}
dispatchingMessageId={null}
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index e36900736e8e2..9c2eb6d4c38df 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -86,7 +86,11 @@ import {
composerStripAttachments,
type DraftComposerFileAttachment,
} from "../../lib/composerImages";
-import { buildModelOptions, isModelSelectionUnavailable } from "../../lib/modelOptions";
+import {
+ buildModelOptions,
+ isModelSelectionUnavailable,
+ serverConfigForCwd,
+} from "../../lib/modelOptions";
import { useScaledTextRole, type ScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
@@ -715,7 +719,7 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
? undefined
: currentModelSelection.instanceId;
const modelOptions = buildModelOptions(
- props.serverConfig,
+ serverConfigForCwd(props.serverConfig, props.projectCwd),
currentModelSelection,
lockedProviderInstanceId,
props.selectedThread.projectId,
diff --git a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
index 48325d9477d2e..2ddf85a88138a 100644
--- a/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
+++ b/apps/mobile/src/features/threads/ThreadSettingsSheet.tsx
@@ -5,7 +5,7 @@ import {
import * as Dialog from "../../components/ui/Dialog";
import { createV5StackNavigator as createNativeStackNavigator } from "../../native/createV5StackNavigator";
import { useSheetStackOptions } from "../layout/nested-stacks";
-import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
+import { DEFAULT_SERVER_SETTINGS, ProviderInstanceId } from "@t3tools/contracts";
import {
modelPreferencesMigrationPatch,
resolveModelPreferences,
@@ -14,7 +14,6 @@ import type {
EnvironmentId,
ModelSelection,
ProjectId,
- ProviderInstanceId,
ProviderOptionDescriptor,
ProviderOptionSelection,
RuntimeMode,
@@ -22,7 +21,7 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import type { LegendListRenderItemProps } from "@legendapp/list/react-native";
-import { RegistryContext, useAtomValue } from "@effect/atom-react";
+import { RegistryContext, useAtomMount, useAtomValue } from "@effect/atom-react";
import { AnimatedLegendList } from "@legendapp/list/reanimated";
import {
getProviderOptionCurrentLabel,
@@ -65,6 +64,7 @@ import { useReduceMotionEnabled } from "../../lib/appState";
import {
buildModelOptions,
groupByProvider,
+ serverConfigForCwd,
type ModelOption,
type ProviderGroup,
} from "../../lib/modelOptions";
@@ -89,6 +89,8 @@ import { useQuietThreadStructure } from "../../state/use-thread-detail";
import { activeComposerDraftKey, useQueuedRunEdit } from "../../state/queued-run-edit";
import { selectThreadModel } from "../../state/thread-model-selection";
import { useThreadSelection } from "../../state/use-thread-selection";
+import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
+import { providerWorkspaceSnapshotRefresh } from "../../state/provider-workspace-snapshot-refresh";
import { threadAllowsProviderSwitch } from "../../state/thread-provider-switching";
import { environmentServerConfigsAtom, serverEnvironment } from "../../state/server";
import { mobilePreferencesAtom } from "../../state/preferences";
@@ -257,6 +259,7 @@ type ThreadSettingsSubmenuPage =
type ThreadSettingsSessionProps = {
readonly environmentId: EnvironmentId | null;
readonly projectId: ProjectId | null;
+ readonly cwd: string | null;
readonly providerInstanceId?: ProviderInstanceId;
readonly lockedProviderInstanceId?: ProviderInstanceId;
readonly providerGroups: ReadonlyArray;
@@ -312,6 +315,8 @@ type ThreadSettingsSessionValue = {
readonly setSearchQuery: (query: string) => void;
readonly setShowLegacy: (showLegacy: boolean) => void;
readonly toggleProvider: (providerKey: string) => void;
+ /** The provider whose catalog for this folder the picker keeps fresh. */
+ readonly workspaceScan: { readonly instanceId: ProviderInstanceId; readonly cwd: string } | null;
};
const ThreadSettingsSessionContext = createContext(null);
@@ -338,7 +343,7 @@ function ThreadSettingsSessionProvider(
manageHidden && config
? groupByProvider(
buildModelOptions(
- config,
+ serverConfigForCwd(config, props.cwd),
props.selectedModel,
props.lockedProviderInstanceId,
props.projectId,
@@ -589,8 +594,17 @@ function ThreadSettingsSessionProvider(
);
};
+ const environmentId = props.environmentId;
+ // Like the web picker's open tab: scanning every provider would spawn a probe per provider.
+ const scannedInstanceId =
+ providerFilter !== null && providerFilter !== FAVORITES_PROVIDER_FILTER
+ ? ProviderInstanceId.make(providerFilter)
+ : props.providerInstanceId;
+ const workspaceScan =
+ props.cwd && scannedInstanceId ? { instanceId: scannedInstanceId, cwd: props.cwd } : null;
+
const value = {
- environmentId: props.environmentId,
+ environmentId,
providerInstanceId: props.providerInstanceId,
providerGroups,
manageHidden,
@@ -622,15 +636,34 @@ function ThreadSettingsSessionProvider(
setShowLegacy: setShowLegacyToggle,
toggleProvider,
toggleFavorite,
+ workspaceScan,
} satisfies ThreadSettingsSessionValue;
return (
+ {environmentId && workspaceScan ? (
+
+ ) : null}
{props.children}
);
}
+/** A project's own provider config can add models only its workspace scan lists. */
+function ProviderWorkspaceSnapshotScan(props: {
+ readonly environmentId: EnvironmentId;
+ readonly instanceId: ProviderInstanceId;
+ readonly cwd: string;
+}) {
+ useAtomMount(providerWorkspaceSnapshotRefresh(props));
+ return null;
+}
+
function useThreadSettingsSession() {
const value = use(ThreadSettingsSessionContext);
if (!value) {
@@ -927,11 +960,25 @@ function ThreadSettingsMainContent(props: {
const refreshProviders = () => {
if (!session.environmentId || isRefreshingProviders) return;
setIsRefreshingProviders(true);
- void refreshProviderCatalog(session.environmentId).then((result) => {
- setIsRefreshingProviders(false);
- const error = providerCatalogRefreshError(result);
- if (error) Dialog.alert("Could not refresh models", error);
- });
+ const environmentId = session.environmentId;
+ const workspaceScan = session.workspaceScan;
+ void refreshProviderCatalog(environmentId)
+ .then(async (result) => {
+ // A project's own models are read per folder, so the machine refresh alone keeps them stale.
+ // A failed folder read keeps its previous models and retries, so only the machine result alerts.
+ if (result._tag === "Success" && workspaceScan) {
+ await refreshProvidersCommand({
+ environmentId,
+ input: { ...workspaceScan, fresh: true },
+ });
+ }
+ return result;
+ })
+ .then((result) => {
+ setIsRefreshingProviders(false);
+ const error = providerCatalogRefreshError(result);
+ if (error) Dialog.alert("Could not refresh models", error);
+ });
};
const [listLoaded, setListLoaded] = useState(false);
// Android can drop the first frame of a reduced-motion fade, leaving rows invisible.
@@ -1313,6 +1360,7 @@ export function ExistingThreadSettingsRouteScreen({
// Reads the same environmentId/threadId params as the Thread route beneath it.
const { selectedThread, selectedThreadDetailRef, selectedEnvironmentRuntime } =
useThreadSelection();
+ const { selectedThreadCwd } = useSelectedThreadWorktree();
// Streamed text would otherwise re-render the whole model picker on every delta.
const structure = useQuietThreadStructure(selectedThreadDetailRef);
const reportedModelSelection = useThreadReportedModelSelection(selectedThreadDetailRef);
@@ -1327,7 +1375,10 @@ export function ExistingThreadSettingsRouteScreen({
return ;
}
- const serverConfig = selectedEnvironmentRuntime?.serverConfig ?? null;
+ const serverConfig = serverConfigForCwd(
+ selectedEnvironmentRuntime?.serverConfig ?? null,
+ selectedThreadCwd,
+ );
const modelSelection = draftSettings.modelSelection ?? selectedThread.modelSelection;
const lockedProviderInstanceId = threadAllowsProviderSwitch({
thread: selectedThread,
@@ -1354,6 +1405,7 @@ export function ExistingThreadSettingsRouteScreen({
ComposerDraftWorkspaceSelection;
@@ -324,7 +327,6 @@ export function NewTaskFlowProvider(
const storedStickyModelSelection = useStickyComposerModelSelection();
const modelSelectionNow = useNowMinuteMs();
const projectDefaults = useNewTaskProjectDefaults(selectedProject);
- const selectedEnvironmentServerConfig = projectDefaults.serverConfig;
const isScratchDraft = projectDefaults.isScratch;
const serverConfigs = useServerConfigs();
const { connectedEnvironments } = useRemoteConnectionStatus();
@@ -404,6 +406,15 @@ export function NewTaskFlowProvider(
const workspaceMode = workspaceSelection.mode;
const selectedBranchName = workspaceSelection.branch;
const selectedWorktreePath = workspaceSelection.worktreePath;
+ // A new worktree does not exist yet, so the project root stands in for it.
+ const workspaceCwd =
+ (workspaceMode === "worktree"
+ ? selectedProject?.workspaceRoot
+ : (selectedWorktreePath ?? selectedProject?.workspaceRoot)) || null;
+ const selectedEnvironmentServerConfig = serverConfigForCwd(
+ projectDefaults.serverConfig,
+ workspaceCwd,
+ );
// Keep the user's explicit choice separate from the resolved display value:
// only the explicit flag is ever written back to the draft, so the resolved
// value keeps tracking the server setting when the config loads late.
@@ -831,6 +842,7 @@ export function NewTaskFlowProvider(
canChooseWorkspace,
selectedBranchName,
selectedWorktreePath,
+ workspaceCwd,
resolveWorkspaceSelection,
startFromOrigin,
draftKey: selectedProjectDraftKey,
diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts
index 4bc5c2b257ffe..1e66bf4ee2c8e 100644
--- a/apps/mobile/src/features/threads/use-composer-command-menu.ts
+++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts
@@ -41,7 +41,6 @@ import {
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import {
- createProviderWorkspaceSnapshotRefreshAtomFamily,
dedupeProviderSkillsByName,
getProviderSkillsForSlashMenu,
getProviderSlashCommandsForSlashMenu,
@@ -58,7 +57,7 @@ import { Atom } from "effect/reactivity";
import { useEffect, useState } from "react";
import type { ComposerEditorSelection } from "../../components/ComposerEditor";
-import { serverEnvironment } from "../../state/server";
+import { providerWorkspaceSnapshotRefresh } from "../../state/provider-workspace-snapshot-refresh";
import {
useComposerPathSearch,
useComposerPullRequestSearch,
@@ -68,11 +67,6 @@ import type { ModelOption } from "../../lib/modelOptions";
import type { ComposerCommandItem } from "./ComposerCommandPopover";
import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";
-const providerWorkspaceSnapshotRefresh = createProviderWorkspaceSnapshotRefreshAtomFamily({
- providers: serverEnvironment.providersValueAtom,
- refreshProviders: serverEnvironment.refreshProviders,
-});
-
const idleWorkspaceSnapshotRefreshAtom: Atom.Atom = Atom.make(undefined).pipe(
Atom.withLabel("mobile:provider-workspace-snapshot-refresh:idle"),
);
diff --git a/apps/mobile/src/lib/modelOptions.ts b/apps/mobile/src/lib/modelOptions.ts
index 7771c738042d3..222d63a010408 100644
--- a/apps/mobile/src/lib/modelOptions.ts
+++ b/apps/mobile/src/lib/modelOptions.ts
@@ -22,6 +22,7 @@ import {
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import { resolveModelShortName } from "@t3tools/client-runtime/provider-clients";
+import { resolveProvidersForCwd } from "@t3tools/client-runtime/providerSkills";
export type ModelOption = {
readonly key: string;
@@ -159,6 +160,16 @@ function normalizeSelectionOptions(
};
}
+/** The config as a project at `cwd` sees it, with that project's own provider models. */
+export function serverConfigForCwd(
+ config: C,
+ cwd: string | null,
+): C {
+ if (!config) return config;
+ const providers = resolveProvidersForCwd(config.providers, cwd);
+ return providers === config.providers ? config : { ...config, providers };
+}
+
/** Require explicit projectId or null so omissions cannot bypass project provider disablement. */
export function isModelSelectionUnavailable(
config: T3ServerConfig | null | undefined,
diff --git a/apps/mobile/src/state/provider-workspace-snapshot-refresh.ts b/apps/mobile/src/state/provider-workspace-snapshot-refresh.ts
new file mode 100644
index 0000000000000..441b4101ff302
--- /dev/null
+++ b/apps/mobile/src/state/provider-workspace-snapshot-refresh.ts
@@ -0,0 +1,9 @@
+import { createProviderWorkspaceSnapshotRefreshAtomFamily } from "@t3tools/client-runtime/providerSkills";
+
+import { serverEnvironment } from "./server";
+
+/** Shared by the composer and the model picker so one cwd scans once. */
+export const providerWorkspaceSnapshotRefresh = createProviderWorkspaceSnapshotRefreshAtomFamily({
+ providers: serverEnvironment.providersValueAtom,
+ refreshProviders: serverEnvironment.refreshProviders,
+});
diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts
index 5882611e073ed..54421dd144e95 100644
--- a/apps/server/src/provider/ProviderRegistry.test.ts
+++ b/apps/server/src/provider/ProviderRegistry.test.ts
@@ -615,6 +615,60 @@ it.layer(
});
describe("ProviderRegistry.layer", () => {
+ it("marks folder catalogs pending when a machine refresh changes the machine models", () => {
+ const machineModel = {
+ slug: "opencode/big-pickle",
+ name: "Big Pickle",
+ isCustom: false,
+ capabilities: null,
+ } satisfies ServerProvider["models"][number];
+ const projectModel = { ...machineModel, slug: "uni/medium-gpt", name: "Medium GPT" };
+ const addedModel = { ...machineModel, slug: "opencode/new", name: "New" };
+ const provider = {
+ instanceId: ProviderInstanceId.make("opencode"),
+ driver: ProviderDriverKind.make("opencode"),
+ status: "ready",
+ enabled: true,
+ installed: true,
+ auth: { status: "authenticated" },
+ checkedAt: "2026-03-25T00:00:00.000Z",
+ version: "2.0.0",
+ models: [machineModel],
+ slashCommands: [],
+ skills: [],
+ } satisfies ServerProvider;
+ const withCatalog = ProviderRegistry.upsertProviderWorkspaceSnapshot(
+ ProviderRegistry.upsertProviderWorkspaceSnapshot(provider, "/project", {
+ ...provider,
+ workspaceModels: [machineModel, projectModel],
+ }),
+ "/plain",
+ provider,
+ );
+
+ const unchanged = ProviderRegistry.mergeProviderSnapshot(withCatalog, provider);
+ assert.deepStrictEqual(
+ unchanged.workspaceSnapshots?.map((snapshot) => snapshot.cwd),
+ ["/project", "/plain"],
+ );
+ const changed = ProviderRegistry.mergeProviderSnapshot(withCatalog, {
+ ...provider,
+ models: [machineModel, addedModel],
+ });
+ assert.deepStrictEqual(
+ changed.workspaceSnapshots?.map(({ cwd, models, modelsPending }) => ({
+ cwd,
+ models,
+ modelsPending,
+ })),
+ [
+ { cwd: "/project", models: [machineModel, projectModel], modelsPending: true },
+ // Its folder may define a model the machine catalog just dropped.
+ { cwd: "/plain", models: undefined, modelsPending: true },
+ ],
+ );
+ });
+
it("stores workspace skills, commands and options without changing machine metadata", () => {
const provider = {
instanceId: ProviderInstanceId.make("codex"),
@@ -629,11 +683,15 @@ it.layer(
slashCommands: [{ name: "global" }],
skills: [{ name: "global", path: "/global/SKILL.md", enabled: true }],
} satisfies ServerProvider;
+ const projectModels = [
+ { slug: "project-model", name: "Project Model", isCustom: false, capabilities: null },
+ ] satisfies ServerProvider["models"];
const scopedSnapshot = {
...provider,
checkedAt: "2026-03-25T00:01:00.000Z",
slashCommands: [{ name: "project" }],
skills: [{ name: "project", path: "/project/SKILL.md", enabled: true }],
+ workspaceModels: projectModels,
optionDescriptors: [
{
id: "agent",
@@ -661,6 +719,7 @@ it.layer(
slashCommands: scopedSnapshot.slashCommands,
skills: scopedSnapshot.skills,
optionDescriptors: scopedSnapshot.optionDescriptors,
+ models: projectModels,
},
]);
@@ -668,6 +727,7 @@ it.layer(
...scopedSnapshot,
slashCommands: [COMPACT_SLASH_COMMAND],
slashCommandsPending: true,
+ workspaceModelsPending: true,
} satisfies ProviderWorkspaceSnapshot;
const partial = ProviderRegistry.upsertProviderWorkspaceSnapshot(
result,
@@ -676,6 +736,8 @@ it.layer(
);
assert.deepStrictEqual(partial.workspaceSnapshots?.[0]?.slashCommands, [{ name: "project" }]);
assert.strictEqual(partial.workspaceSnapshots?.[0]?.slashCommandsPending, true);
+ assert.deepStrictEqual(partial.workspaceSnapshots?.[0]?.models, projectModels);
+ assert.strictEqual(partial.workspaceSnapshots?.[0]?.modelsPending, true);
const otherProject = ProviderRegistry.upsertProviderWorkspaceSnapshot(
partial,
"/other-project",
@@ -693,6 +755,14 @@ it.layer(
{ name: "replacement" },
]);
assert.strictEqual(recovered.workspaceSnapshots?.[0]?.slashCommandsPending, undefined);
+ assert.deepStrictEqual(recovered.workspaceSnapshots?.[0]?.models, projectModels);
+ assert.strictEqual(recovered.workspaceSnapshots?.[0]?.modelsPending, undefined);
+ const withoutModels = ProviderRegistry.upsertProviderWorkspaceSnapshot(
+ recovered,
+ "/project",
+ { ...scopedSnapshot, workspaceModels: undefined },
+ );
+ assert.strictEqual(withoutModels.workspaceSnapshots?.[0]?.models, undefined);
const { optionDescriptors, ...failedSnapshot } = scopedSnapshot;
const firstFailure = ProviderRegistry.upsertProviderWorkspaceSnapshot(
@@ -2092,6 +2162,123 @@ it.layer(
}),
);
+ it.effect("rescans a folder whose model catalog could not be read before its TTL", () =>
+ Effect.gen(function* () {
+ const driver = ProviderDriverKind.make("opencode");
+ const instanceId = ProviderInstanceId.make("opencode");
+ const machineModel = {
+ slug: "opencode/big-pickle",
+ name: "Big Pickle",
+ isCustom: false,
+ capabilities: null,
+ } satisfies ServerProvider["models"][number];
+ const projectModel = { ...machineModel, slug: "uni/medium-gpt", name: "Medium GPT" };
+ const provider = {
+ instanceId,
+ driver,
+ status: "ready",
+ enabled: true,
+ installed: true,
+ auth: { status: "authenticated" },
+ checkedAt: "2026-06-10T00:00:00.000Z",
+ version: "2.0.0",
+ models: [machineModel],
+ slashCommands: [],
+ skills: [],
+ } as const satisfies ServerProvider;
+ const machineProvider = yield* Ref.make(provider);
+ const scanResult = yield* Ref.make({
+ ...provider,
+ slashCommandsPending: false,
+ workspaceModelsPending: true,
+ });
+ const instance: ProviderInstance = {
+ instanceId,
+ driverKind: driver,
+ continuationIdentity: {
+ driverKind: driver,
+ continuationKey: "opencode:instance:opencode",
+ },
+ displayName: undefined,
+ enabled: true,
+ snapshot: {
+ resolveMaintenance: () =>
+ Effect.succeed(
+ makeManualOnlyProviderMaintenanceCapabilities({
+ provider: driver,
+ packageName: null,
+ }),
+ ),
+ getSnapshot: Ref.get(machineProvider),
+ refresh: Ref.get(machineProvider),
+ streamChanges: Stream.empty,
+ applyUsageLimits: () => Effect.void,
+ },
+ snapshotForCwd: () => Ref.get(scanResult),
+ orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
+ textGeneration: {} as ProviderInstance["textGeneration"],
+ };
+ const layerInstanceRegistry = Layer.succeed(
+ ProviderInstanceRegistry.ProviderInstanceRegistry,
+ {
+ getInstance: (requestedId) =>
+ Effect.succeed(requestedId === instanceId ? instance : undefined),
+ listInstances: Effect.succeed([instance]),
+ listUnavailable: Effect.succeed([]),
+ streamChanges: Stream.empty,
+ subscribeChanges: Effect.flatMap(PubSub.unbounded(), PubSub.subscribe),
+ },
+ );
+ const scope = yield* Scope.make();
+ yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
+ const runtimeServices = yield* Layer.build(
+ ProviderRegistry.layer.pipe(
+ Layer.provide(layerUnusedMutator),
+ Layer.provideMerge(layerInstanceRegistry),
+ Layer.provideMerge(
+ ServerConfig.layerTest(process.cwd(), {
+ prefix: "t3-provider-registry-pending-workspace-models-",
+ }),
+ ),
+ Layer.provideMerge(NodeServices.layer),
+ ),
+ ).pipe(Scope.provide(scope));
+
+ yield* Effect.gen(function* () {
+ const registry = yield* ProviderRegistry.ProviderRegistry;
+ const workspaceOf = Effect.map(
+ registry.getProviders,
+ (providers) => providers[0]?.workspaceSnapshots?.[0],
+ );
+ yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/project" });
+ const unread = yield* workspaceOf;
+ assert.strictEqual(unread?.models, undefined);
+ assert.strictEqual(unread?.modelsPending, true);
+
+ const workspaceModels = [machineModel, projectModel];
+ yield* Ref.set(scanResult, { ...provider, slashCommandsPending: false, workspaceModels });
+ yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/project" });
+ const recovered = yield* workspaceOf;
+ assert.deepStrictEqual(recovered?.models, workspaceModels);
+ assert.strictEqual(recovered?.modelsPending, undefined);
+
+ // A fresh refresh whose machine models change still publishes the folder read it ran.
+ const addedModel = { ...machineModel, slug: "opencode/new", name: "New" };
+ const nextWorkspaceModels = [machineModel, addedModel, projectModel];
+ yield* Ref.set(machineProvider, { ...provider, models: [machineModel, addedModel] });
+ yield* Ref.set(scanResult, {
+ ...provider,
+ slashCommandsPending: false,
+ workspaceModels: nextWorkspaceModels,
+ });
+ yield* registry.refreshWorkspaceSnapshot({ instanceId, cwd: "/project", fresh: true });
+ const rescanned = yield* workspaceOf;
+ assert.deepStrictEqual(rescanned?.models, nextWorkspaceModels);
+ assert.strictEqual(rescanned?.modelsPending, undefined);
+ }).pipe(Effect.provide(runtimeServices));
+ }),
+ );
+
it.effect("shares one in-flight pass between concurrent untargeted refreshes", () =>
Effect.gen(function* () {
const driver = ProviderDriverKind.make("codex");
diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts
index b36363de36f3a..15c48e176de9e 100644
--- a/apps/server/src/provider/ProviderRegistry.ts
+++ b/apps/server/src/provider/ProviderRegistry.ts
@@ -1,6 +1,7 @@
import {
defaultInstanceIdForDriver,
isProviderWorkspaceSnapshotCurrent,
+ isProviderWorkspaceSnapshotPending,
ProviderDriverKind,
type ProviderInstanceId,
type ServerProvider,
@@ -157,6 +158,9 @@ export function upsertProviderWorkspaceSnapshot(
): ServerProvider {
const previousSnapshot = provider.workspaceSnapshots?.find((snapshot) => snapshot.cwd === cwd);
const optionDescriptors = scopedSnapshot.optionDescriptors ?? previousSnapshot?.optionDescriptors;
+ const models = scopedSnapshot.workspaceModelsPending
+ ? previousSnapshot?.models
+ : scopedSnapshot.workspaceModels;
const workspaceSnapshot = {
cwd,
checkedAt: scopedSnapshot.checkedAt,
@@ -166,6 +170,8 @@ export function upsertProviderWorkspaceSnapshot(
...(scopedSnapshot.slashCommandsPending ? { slashCommandsPending: true } : {}),
skills: scopedSnapshot.skills,
...(optionDescriptors === undefined ? {} : { optionDescriptors }),
+ ...(models === undefined ? {} : { models }),
+ ...(scopedSnapshot.workspaceModelsPending ? { modelsPending: true } : {}),
} satisfies NonNullable[number];
return {
...provider,
@@ -296,14 +302,22 @@ export const mergeProviderSnapshot = (
}
const savedAccount = carrySavedAntigravityAccount(previousProvider, nextProvider);
const { message: _uncheckedMessage, ...nextWithoutMessage } = nextProvider;
+ const models = mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models);
+ // Folder catalogs were compared with the old machine catalog, so every folder rescans.
+ const previousWorkspaceSnapshots = Equal.equals(models, previousProvider.models)
+ ? previousProvider.workspaceSnapshots
+ : previousProvider.workspaceSnapshots?.map((snapshot) => ({
+ ...snapshot,
+ modelsPending: true,
+ }));
return {
...(savedAccount?.status === "ready" ? nextWithoutMessage : nextProvider),
...savedAccount,
- models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models),
+ models,
...(nextProvider.workspaceSnapshots !== undefined
? { workspaceSnapshots: nextProvider.workspaceSnapshots }
- : previousProvider.workspaceSnapshots !== undefined
- ? { workspaceSnapshots: previousProvider.workspaceSnapshots }
+ : previousWorkspaceSnapshots !== undefined
+ ? { workspaceSnapshots: previousWorkspaceSnapshots }
: {}),
...(shouldRetainMissingOpenCodeMetadata(nextProvider)
? {
@@ -1003,7 +1017,7 @@ export const layer = Layer.effect(
!provider.enabled ||
(!input.fresh &&
scannedFrom &&
- !scannedFrom.slashCommandsPending &&
+ !isProviderWorkspaceSnapshotPending(scannedFrom) &&
isProviderWorkspaceSnapshotCurrent(scannedFrom, DateTime.toEpochMillis(now)))
) {
return providers;
@@ -1011,17 +1025,30 @@ export const layer = Layer.effect(
// Use scan start for TTL, not checkedAt inherited from the machine health check.
const scannedAt = DateTime.formatIso(now);
const instance = yield* instanceRegistry.getInstance(input.instanceId);
- if (!instance?.snapshotForCwd) return providers;
+ const snapshotForCwd = instance?.snapshotForCwd;
+ if (!instance || !snapshotForCwd) return providers;
const token = yield* Deferred.make();
+ // A machine refresh can change this cwd's snapshot, so the scan publishes against the result.
const refreshMachineSnapshot = input.fresh
? (instance.invalidateCaches ?? Effect.void).pipe(
Effect.andThen(refreshInstance(input.instanceId)),
+ Effect.andThen(Ref.get(providersRef)),
+ Effect.map((current) =>
+ workspaceSnapshotOf(
+ current.find((candidate) => candidate.instanceId === input.instanceId),
+ ),
+ ),
)
- : Effect.void;
+ : Effect.succeed(scannedFrom);
const runScan = refreshMachineSnapshot.pipe(
- Effect.andThen(instance.snapshotForCwd(input.scanCwd ?? input.cwd)),
+ Effect.flatMap((scanBase) =>
+ Effect.map(snapshotForCwd(input.scanCwd ?? input.cwd), (scopedSnapshot) => ({
+ scanBase,
+ scopedSnapshot,
+ })),
+ ),
// Scans fail on error; returned inventory remains valid even when provider health reports an error.
- Effect.flatMap((scopedSnapshot) =>
+ Effect.flatMap(({ scanBase, scopedSnapshot }) =>
instanceRegistry.getInstance(input.instanceId).pipe(
Effect.flatMap((currentInstance) => {
if (currentInstance !== instance) return Ref.get(providersRef);
@@ -1032,7 +1059,7 @@ export const layer = Layer.effect(
}
return currentProviders.map((candidate) =>
candidate.instanceId === input.instanceId &&
- Equal.equals(workspaceSnapshotOf(candidate), scannedFrom)
+ Equal.equals(workspaceSnapshotOf(candidate), scanBase)
? upsertProviderWorkspaceSnapshot(candidate, input.cwd, {
...scopedSnapshot,
checkedAt: scannedAt,
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index 153428f2b6755..63736bc1aa350 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -241,7 +241,10 @@ import { useEnvironmentScope } from "~/state/session";
import { primaryServerKeybindingsAtom, serverEnvironment } from "../state/server";
import { hostEnvironmentIdAtom } from "../state/primaryEnvironment";
import { threadEnvironment } from "../state/threads";
-import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
+import {
+ resolveProviderSkillsForCwd,
+ resolveProvidersForCwd,
+} from "@t3tools/client-runtime/providerSkills";
import { chatGitStatusAtom, NO_CHAT_GIT_STATUS_ATOM, vcsEnvironment } from "../state/vcs";
import {
type EnvironmentPresentation,
@@ -1221,10 +1224,18 @@ export default function ChatView(props: ChatViewProps) {
: (primaryEnvironment?.serverConfig ?? null);
const providerEnvironmentId = (activeThread ? activeEnvironment : primaryEnvironment)
?.environmentId;
- const providerStatuses =
+ const gitCwd = activeProject
+ ? projectScriptCwd({
+ project: { cwd: activeProject.workspaceRoot },
+ worktreePath: activeThread?.worktreePath ?? null,
+ })
+ : null;
+ const providerStatuses = resolveProvidersForCwd(
(providerEnvironmentId === undefined
? undefined
- : providersByEnvironment.get(providerEnvironmentId)) ?? EMPTY_PROVIDERS;
+ : providersByEnvironment.get(providerEnvironmentId)) ?? EMPTY_PROVIDERS,
+ gitCwd,
+ );
const selectedProviderByThreadId = composerActiveProvider ?? null;
const threadProvider =
activeThread?.modelSelection.instanceId ??
@@ -1601,12 +1612,6 @@ export default function ChatView(props: ChatViewProps) {
turnDiffSummaries.at(-1)?.completedAt ?? null,
);
- const gitCwd = activeProject
- ? projectScriptCwd({
- project: { cwd: activeProject.workspaceRoot },
- worktreePath: activeThread?.worktreePath ?? null,
- })
- : null;
const gitStatusCwd = activeThread?.worktreePath ?? gitCwd;
const gitStatusAtom =
gitStatusCwd === null
diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx
index fae55b8923d56..2a62be45f041f 100644
--- a/apps/web/src/components/chat/ChatComposer.tsx
+++ b/apps/web/src/components/chat/ChatComposer.tsx
@@ -2404,6 +2404,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const composerControls = (
;
@@ -435,6 +438,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
return hasPickableFavorite ? "favorites" : props.activeInstanceId;
},
);
+ const { scanning: workspaceModelsScanning } = useProviderWorkspaceSnapshotRefresh({
+ environmentId: props.environmentId,
+ gitCwd: props.workspaceCwd ?? null,
+ instanceId: selectedInstanceId === "favorites" ? undefined : selectedInstanceId,
+ });
const favoritesSet = new Set(favorites.map((fav) => providerModelKey(fav.provider, fav.model)));
const [expandedLegacyInstances, setExpandedLegacyInstances] = useState(
() =>
@@ -1063,7 +1071,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
emptyLabel={
selectedInstanceId === "favorites" && !isSearching
? "No favorites yet"
- : "No models found"
+ : workspaceModelsScanning
+ ? "Searching project models..."
+ : "No models found"
}
onRequestClose={onRequestClose}
onOpenProviderSetup={onOpenProviderSetup}
diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx
index e05736b0d412d..dc24671c301ba 100644
--- a/apps/web/src/components/chat/ProviderModelPicker.tsx
+++ b/apps/web/src/components/chat/ProviderModelPicker.tsx
@@ -88,6 +88,7 @@ export const DockedPickerContext = createContext<{ modelLabel: string }>({ model
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
environmentId: EnvironmentId | null;
+ workspaceCwd?: string | null;
activeInstanceId: ProviderInstanceId;
model: string;
selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>;
@@ -280,6 +281,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
(undefined).pipe(Atom.withLabel("provider-workspace-snapshot-refresh:idle"));
/**
- * Keeps the selected provider's workspace snapshot fresh for the composer's
- * cwd while mounted. Returns a check to run when the user types, and whether
- * the cwd's skills are still being scanned.
+ * Keeps a provider's workspace snapshot fresh for the composer's cwd while
+ * mounted. Returns a check to run when the user types, and whether the cwd's
+ * skills are still being scanned.
*/
export function useProviderWorkspaceSnapshotRefresh(input: {
- readonly environmentId: EnvironmentId;
+ readonly environmentId: EnvironmentId | null;
readonly gitCwd: string | null;
readonly instanceId: ProviderInstanceId | undefined;
}): { readonly refresh: () => void; readonly scanning: boolean } {
const { environmentId, gitCwd, instanceId } = input;
const atom =
- gitCwd && instanceId
+ environmentId && gitCwd && instanceId
? providerWorkspaceSnapshotRefresh({ environmentId, instanceId, cwd: gitCwd })
: idleRefreshAtom;
return {
diff --git a/docs/user/providers-opencode.md b/docs/user/providers-opencode.md
index b73d4d93e5207..624f21a6e9067 100644
--- a/docs/user/providers-opencode.md
+++ b/docs/user/providers-opencode.md
@@ -75,5 +75,9 @@ refreshes or text-generation work, then refresh again to reload the files. Repea
refreshes keep the helper alive. An external server may need its own reload or
restart before T3 Code can see configuration changes.
+Models defined in a project's own `opencode.json` appear only in that project's
+model picker, after T3 Code reads the project's catalog the first time the picker
+opens there.
+
Existing threads keep their selected model and options even when it disappears
from the catalog. If OpenCode rejects that model, select an available one and retry.
diff --git a/packages/client-runtime/src/providerSkills.test.ts b/packages/client-runtime/src/providerSkills.test.ts
index d8a088a63bf70..acd4a4904c1d4 100644
--- a/packages/client-runtime/src/providerSkills.test.ts
+++ b/packages/client-runtime/src/providerSkills.test.ts
@@ -15,6 +15,7 @@ import {
isProviderWorkspaceSnapshotScanning,
resolveProviderSkillsForCwd,
resolveProviderSlashCommandsForCwd,
+ resolveProvidersForCwd,
} from "./providerSkills.ts";
const provider = {
@@ -120,6 +121,30 @@ describe("workspace provider snapshots", () => {
expect(hasCompleteProviderWorkspaceSnapshot(undefined, "/workspace/project-a")).toBe(false);
expect(hasCompleteProviderWorkspaceSnapshot(provider, null)).toBe(false);
});
+
+ it("lists a project's own models only for that project", () => {
+ const projectModel = {
+ slug: "uni/medium-gpt",
+ name: "Medium GPT",
+ isCustom: false,
+ capabilities: null,
+ } satisfies ServerProvider["models"][number];
+ const withProjectModels = {
+ ...provider,
+ workspaceSnapshots: provider.workspaceSnapshots.map((snapshot) => ({
+ ...snapshot,
+ models: [projectModel],
+ })),
+ } satisfies ServerProvider;
+ const providers = [provider, withProjectModels];
+
+ expect(resolveProvidersForCwd(providers, "/workspace/project-a").map((p) => p.models)).toEqual([
+ [],
+ [projectModel],
+ ]);
+ expect(resolveProvidersForCwd(providers, "/workspace/project-a")[0]).toBe(provider);
+ expect(resolveProvidersForCwd(providers, "/workspace/project-b")).toBe(providers);
+ });
});
describe("provider workspace snapshot refresh atom", () => {
@@ -273,6 +298,22 @@ describe("provider workspace snapshot refresh atom", () => {
expect(vi.getTimerCount()).toBe(0);
});
+ it("rescans a current snapshot whose commands are complete but models are pending", () => {
+ vi.useFakeTimers({ now: Date.parse("2026-01-01T00:00:00.000Z") });
+ const [current] = withSnapshot("2026-01-01T00:00:00.000Z");
+ const { run, unmount } = setup([
+ {
+ ...current!,
+ workspaceSnapshots: current!.workspaceSnapshots!.map((snapshot) => ({
+ ...snapshot,
+ modelsPending: true,
+ })),
+ },
+ ]);
+ expect(run).toHaveBeenCalledTimes(1);
+ unmount();
+ });
+
it("stops retrying after three failed scans until the TTL lapses", async () => {
vi.useFakeTimers({ now: Date.parse("2026-01-01T00:00:00.000Z") });
const { registry, atom, run, unmount } = setup(withSnapshot("2026-01-01T00:00:00.000Z", true));
diff --git a/packages/client-runtime/src/providerSkills.ts b/packages/client-runtime/src/providerSkills.ts
index 2598c895c5053..0f91fc29f74e5 100644
--- a/packages/client-runtime/src/providerSkills.ts
+++ b/packages/client-runtime/src/providerSkills.ts
@@ -1,6 +1,7 @@
import {
type EnvironmentId,
isProviderWorkspaceSnapshotCurrent,
+ isProviderWorkspaceSnapshotPending,
PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS,
type ProviderInstanceId,
type ServerProvider,
@@ -102,7 +103,7 @@ export function hasCompleteProviderWorkspaceSnapshot(
cwd: string | null | undefined,
): boolean {
const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd);
- return Boolean(snapshot && !snapshot.slashCommandsPending);
+ return Boolean(snapshot && !isProviderWorkspaceSnapshotPending(snapshot));
}
function hasCurrentProviderWorkspaceSnapshot(
@@ -113,7 +114,7 @@ function hasCurrentProviderWorkspaceSnapshot(
const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd);
return Boolean(
snapshot &&
- !snapshot.slashCommandsPending &&
+ !isProviderWorkspaceSnapshotPending(snapshot) &&
isProviderWorkspaceSnapshotCurrent(snapshot, nowMs),
);
}
@@ -132,6 +133,26 @@ export function resolveProviderSlashCommandsForCwd(
return resolveProviderWorkspaceSnapshot(provider, cwd)?.slashCommands ?? provider.slashCommands;
}
+/** A project's own provider config can add models that only its workspace snapshot lists. */
+function resolveProviderModelsForCwd(
+ provider: ServerProvider,
+ cwd: string | null | undefined,
+): ServerProvider["models"] {
+ return resolveProviderWorkspaceSnapshot(provider, cwd)?.models ?? provider.models;
+}
+
+/** Providers keep their identity unless the cwd has its own catalog. */
+export function resolveProvidersForCwd(
+ providers: ReadonlyArray
,
+ cwd: string | null | undefined,
+): ReadonlyArray
{
+ const resolved = providers.map((provider) => {
+ const models = resolveProviderModelsForCwd(provider, cwd);
+ return models === provider.models ? provider : { ...provider, models };
+ });
+ return resolved.every((provider, index) => provider === providers[index]) ? providers : resolved;
+}
+
const WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS = 10_000;
// A cwd that never scans, such as a deleted worktree, would otherwise retry forever.
const WORKSPACE_SNAPSHOT_MAX_ATTEMPTS = 3;
@@ -175,8 +196,8 @@ function planProviderWorkspaceSnapshotRefresh(
readonly recheckAt: number | null;
} {
const hasSnapshot = hasCompleteProviderWorkspaceSnapshot(provider, cwd);
- const pending =
- (provider && resolveProviderWorkspaceSnapshot(provider, cwd)?.slashCommandsPending) === true;
+ const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd);
+ const pending = Boolean(snapshot && isProviderWorkspaceSnapshotPending(snapshot));
// Losing a snapshot (the server dropped it) lifts both the TTL and the retry
// cooldown so the scan happens at once.
const lost = previous.hadSnapshot && !hasSnapshot;
@@ -252,7 +273,7 @@ function resolveWorkspaceSnapshotStatus(
): WorkspaceSnapshotStatus {
const snapshot = provider && resolveProviderWorkspaceSnapshot(provider, cwd);
if (!snapshot) return "absent";
- return snapshot.slashCommandsPending ? "pending" : "complete";
+ return isProviderWorkspaceSnapshotPending(snapshot) ? "pending" : "complete";
}
interface ProviderWorkspaceSnapshotRefreshTarget {
diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts
index 40256c327b29e..a935272d3d40f 100644
--- a/packages/client-runtime/src/state/server.ts
+++ b/packages/client-runtime/src/state/server.ts
@@ -680,6 +680,7 @@ type ServerProviderEntry = ServerConfig["providers"][number];
const snapshotBasis = (provider: ServerProviderEntry | undefined) =>
provider && {
enabled: provider.enabled,
+ models: provider.models,
slashCommands: provider.slashCommands,
skills: provider.skills,
};
diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts
index 40a1aa8b2ca86..e14c91860aea3 100644
--- a/packages/contracts/src/server.ts
+++ b/packages/contracts/src/server.ts
@@ -129,6 +129,9 @@ export const ServerProviderWorkspaceSnapshot = Schema.Struct({
slashCommandsPending: Schema.optional(Schema.Boolean),
skills: Schema.Array(ServerProviderSkill),
optionDescriptors: Schema.optional(Schema.Array(ProviderOptionDescriptor)),
+ // Absent means the provider's machine `models`, which keeps most snapshots small.
+ models: Schema.optional(Schema.Array(ServerProviderModel)),
+ modelsPending: Schema.optional(Schema.Boolean),
});
export type ServerProviderWorkspaceSnapshot = typeof ServerProviderWorkspaceSnapshot.Type;
@@ -141,6 +144,13 @@ export function isProviderWorkspaceSnapshotCurrent(
return nowMs - Date.parse(snapshot.checkedAt) < PROVIDER_WORKSPACE_SNAPSHOT_TTL_MS;
}
+/** A pending snapshot keeps what it found before and is rescanned before its TTL. */
+export function isProviderWorkspaceSnapshotPending(
+ snapshot: Pick