From a6c69be8df7de0ba207a4e12ff3794f6edf9f7a6 Mon Sep 17 00:00:00 2001 From: William Craig Date: Tue, 24 Nov 2026 01:23:37 -0500 Subject: [PATCH 001/277] fix(web,mobile): a parent parked on subagents no longer reads as Thinking (#41927) Co-authored-by: Will Craig <24501963+WillCraig@users.noreply.github.com> Co-authored-by: William Craig Co-authored-by: Julius Marminge --- apps/mobile/src/lib/threadActivity.test.ts | 67 +++++++++++++++++++ apps/mobile/src/lib/threadActivity.ts | 9 +++ .../chat/MessagesTimeline.logic.test.ts | 14 ++++ .../components/chat/MessagesTimeline.logic.ts | 9 +++ 4 files changed, 99 insertions(+) diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 49597ca0fdd7c..41248bf9c1e88 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -1340,6 +1340,73 @@ describe("buildThreadFeed", () => { expect(presented.some((entry) => entry.type === "thinking")).toBe(false); }); + // regression: #40551 a finished status after the children is the parent parking, not new work + it("keeps waiting on running subagents after the parent's finished status", () => { + const child = ( + id: string, + ordinal: number, + status: "running" | "completed", + ): OrchestrationV2TurnItem => ({ + ...base(id, `2026-06-20T00:00:0${ordinal}.000Z`, ordinal), + status, + completedAt: + status === "running" ? null : DateTime.makeUnsafe(`2026-06-20T00:00:0${ordinal}.000Z`), + type: "subagent", + subagentId: NodeId.make(id), + origin: "provider_native", + driver: ProviderDriverKind.make("antigravity"), + providerInstanceId: ProviderInstanceId.make("antigravity"), + childThreadId: null, + prompt: `Read ${id}`, + result: null, + }); + const startedAt = "2026-06-20T00:00:01.000Z"; + const latestRun = { runId, status: "running" as const, startedAt, completedAt: null }; + const present = (tail: ReadonlyArray) => + deriveThreadFeedPresentation( + buildThreadFeed([ + projected(userMessage(), 0), + projected(child("a", 2, "running"), 1), + projected(child("b", 3, "completed"), 2), + projected(child("c", 4, "running"), 3), + ...tail.map((item, index) => projected(item, index + 4)), + ]), + latestRun, + new Set(), + new Set(), + startedAt, + ); + const thinkingLabel = (rows: ReadonlyArray) => { + const row = rows.find((entry) => entry.type === "thinking"); + return row?.type === "thinking" ? row.label : undefined; + }; + expect( + thinkingLabel( + present([ + { + ...assistantMessage("2026-06-20T00:00:05.000Z"), + id: TurnItemId.make("status"), + messageId: MessageId.make("status"), + text: "Subagents launched; waiting for them to report back.", + }, + ]), + ), + ).toBe("Waiting on 2 subagents"); + expect( + thinkingLabel( + present([ + { + ...assistantMessage("2026-06-20T00:00:05.000Z"), + id: TurnItemId.make("foreign"), + messageId: MessageId.make("foreign"), + runId: RunId.make("run-2"), + text: "Earlier answer.", + }, + ]), + ), + ).toBeUndefined(); + }); + it("does not show Thinking once the provider turn has ended or its reply is streaming", () => { const startedAt = "2026-04-01T00:00:01.000Z"; const run = { runId, status: "running" as const, startedAt, completedAt: null }; diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 13bfc8cfaeae7..50e87752574b3 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -2069,6 +2069,15 @@ function runningSubagentsAtRunTail(feed: ReadonlyArray, runId: let running = 0; for (let index = feed.length - 1; index >= 0; index -= 1) { const entry = feed[index]!; + // The run's own finished reply is the parent parking on the children, not new work. + if ( + entry.type === "message" && + entry.message.role === "assistant" && + !entry.message.streaming && + entry.message.runId === runId + ) { + continue; + } if (entry.type !== "activity-group" || entry.runId !== runId) break; const items = entry.activities.map((activity) => activity.projectedItem.item); if (items.some((item) => item.type !== "subagent")) break; diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 37005359592cd..649d6fe289494 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -5081,6 +5081,20 @@ describe("parent run waiting on foreground subagents", () => { expect(liveRow([], "hideAll")).toEqual({ ...thinking, label: "Waiting on 2 subagents" }); }); + // regression: #40551 a finished status after the children is the parent parking, not new work + it("names the running children when the parent's finished status message follows them", () => { + const status: OrchestrationV2TurnItem = { + ...base("status", 5), + status: "completed", + type: "assistant_message", + messageId: MessageId.make("status"), + text: "Subagents launched; waiting for them to report back.", + streaming: false, + }; + expect(liveRow([status])).toEqual({ ...thinking, label: "Waiting on 2 subagents" }); + expect(liveRow([{ ...status, runId: RunId.make("other-run") }])).toEqual(thinking); + }); + it("keeps Thinking when a hidden newer parent command follows the children", () => { const command: OrchestrationV2TurnItem = { ...base("command", 5), diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 990b2a6f4ecc8..d6f260e1dbabf 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1518,6 +1518,15 @@ function runningSubagentsAtRunTail(entries: ReadonlyArray, runId: let running = 0; for (let index = entries.length - 1; index >= 0; index -= 1) { const entry = entries[index]!; + // The run's own finished reply is the parent parking on the children, not new work. + if ( + entry.kind === "message" && + entry.message.role === "assistant" && + !entry.message.streaming && + entry.message.runId === runId + ) { + continue; + } if (entry.kind !== "event") break; const { item } = entry.projectedItem; if (item.type !== "subagent" || item.runId !== runId) break; From 74c6d21c7a31774c27c20f2444bd312196f5e35d Mon Sep 17 00:00:00 2001 From: WhiteWarrior625 <42657673+WhiteWarrior625@users.noreply.github.com> Date: Tue, 24 Nov 2026 01:42:22 -0500 Subject: [PATCH 002/277] fix(web): the update dialog says why a server was skipped (#41672) Co-authored-by: Julius Marminge --- apps/mobile/src/i18n/translations/de.json | 2 +- apps/mobile/src/i18n/translations/en.json | 2 +- apps/mobile/src/i18n/translations/es.json | 2 +- apps/mobile/src/i18n/translations/fr.json | 2 +- apps/mobile/src/i18n/translations/ja.json | 2 +- apps/mobile/src/i18n/translations/ko.json | 2 +- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/mobile/src/i18n/translations/ru.json | 2 +- apps/mobile/src/i18n/translations/sv.json | 2 +- apps/mobile/src/i18n/translations/zh.json | 2 +- .../sidebar/updateEverything.logic.test.ts | 29 ++++++++++++++++++- .../sidebar/updateEverything.logic.ts | 19 +++++++++++- .../components/sidebar/useUpdateEverything.ts | 3 ++ apps/web/src/i18n/translations/de.json | 4 ++- apps/web/src/i18n/translations/en.json | 4 ++- apps/web/src/i18n/translations/es.json | 4 ++- apps/web/src/i18n/translations/fr.json | 4 ++- apps/web/src/i18n/translations/ja.json | 4 ++- apps/web/src/i18n/translations/ko.json | 4 ++- apps/web/src/i18n/translations/pt-BR.json | 4 ++- apps/web/src/i18n/translations/ru.json | 4 ++- apps/web/src/i18n/translations/sv.json | 4 ++- apps/web/src/i18n/translations/zh.json | 4 ++- .../client-runtime/src/connection/errors.ts | 8 ++--- .../client-runtime/src/rpc/session.test.ts | 3 +- 25 files changed, 95 insertions(+), 27 deletions(-) diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index b983974ea7774..d97b521b536fa 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} hat auf keiner gespeicherten Route geantwortet.", "b0dd3cd876937ca8": "Verbindungsprofil {connectionId} ist nicht verfügbar.", "5ce46783e79ca9d1": "Zugangsdaten der Verbindung {connectionId} sind nicht verfügbar.", - "0bda0cac7f5acc20": "Die verbundene Umgebung {actual} stimmt nicht mit {expected} überein.", + "b39d1428ec8b23f5": "Unter dieser Adresse läuft jetzt eine andere T3 Code-Installation ({actual}, nicht {expected}). Entferne diese Verbindung und füge sie erneut hinzu.", "ea0d3e4e51d5706f": "Die Zugangsdaten der Umgebung sind ungültig.", "7283ebfd16d09677": "Die Zugangsdaten der Umgebung gewähren nicht den erforderlichen Zugriff.", "d3e9a9cb543b4b7b": "Die Umgebung hat die Authentifizierungsanfrage abgelehnt.", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 71de078057dc3..840b055813d48 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} did not answer on any saved route.", "b0dd3cd876937ca8": "Connection profile {connectionId} is unavailable.", "5ce46783e79ca9d1": "Connection credential {connectionId} is unavailable.", - "0bda0cac7f5acc20": "Connected environment {actual} does not match {expected}.", + "b39d1428ec8b23f5": "This address now runs a different T3 Code install ({actual}, not {expected}). Remove this connection and add it again.", "ea0d3e4e51d5706f": "The environment credential is invalid.", "7283ebfd16d09677": "The environment credential does not grant the required access.", "d3e9a9cb543b4b7b": "The environment rejected the authentication request.", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 292dc71f03be7..4f315bafcfa0c 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} no respondió en ninguna de las rutas guardadas.", "b0dd3cd876937ca8": "El perfil de conexión {connectionId} no está disponible.", "5ce46783e79ca9d1": "La credencial de conexión {connectionId} no está disponible.", - "0bda0cac7f5acc20": "El entorno conectado {actual} no coincide con {expected}.", + "b39d1428ec8b23f5": "Esta dirección ahora ejecuta otra instalación de T3 Code ({actual}, no {expected}). Elimina esta conexión y vuelve a añadirla.", "ea0d3e4e51d5706f": "La credencial del entorno no es válida.", "7283ebfd16d09677": "La credencial del entorno no concede el acceso necesario.", "d3e9a9cb543b4b7b": "El entorno rechazó la solicitud de autenticación.", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index ca2293353f5e6..c9258e0220c62 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} n’a répondu sur aucune route enregistrée.", "b0dd3cd876937ca8": "Le profil de connexion {connectionId} n’est pas disponible.", "5ce46783e79ca9d1": "Les identifiants de connexion {connectionId} ne sont pas disponibles.", - "0bda0cac7f5acc20": "L’environnement connecté {actual} ne correspond pas à {expected}.", + "b39d1428ec8b23f5": "Cette adresse exécute désormais une autre installation de T3 Code ({actual}, et non {expected}). Supprimez cette connexion et ajoutez-la à nouveau.", "ea0d3e4e51d5706f": "Les identifiants de l’environnement ne sont pas valides.", "7283ebfd16d09677": "Les identifiants de l’environnement n’accordent pas l’accès requis.", "d3e9a9cb543b4b7b": "L’environnement a rejeté la demande d’authentification.", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index cf491d8692d4c..f0707be16a61a 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} は保存されたどのルートでも応答しませんでした。", "b0dd3cd876937ca8": "接続プロファイル {connectionId} は利用できません。", "5ce46783e79ca9d1": "接続の資格情報 {connectionId} は利用できません。", - "0bda0cac7f5acc20": "接続した環境 {actual} が {expected} と一致しません。", + "b39d1428ec8b23f5": "このアドレスでは別の T3 Code が動作しています({expected} ではなく {actual})。この接続を削除して、もう一度追加してください。", "ea0d3e4e51d5706f": "環境の資格情報が無効です。", "7283ebfd16d09677": "環境の資格情報に必要なアクセス権がありません。", "d3e9a9cb543b4b7b": "環境が認証リクエストを拒否しました。", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 0ac08e85af27a..d90f0d02dd0bb 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host}이(가) 저장된 경로 중 어디에서도 응답하지 않았습니다.", "b0dd3cd876937ca8": "연결 프로필 {connectionId}을(를) 사용할 수 없습니다.", "5ce46783e79ca9d1": "연결 자격 증명 {connectionId}을(를) 사용할 수 없습니다.", - "0bda0cac7f5acc20": "연결된 환경 {actual}이(가) {expected}과(와) 일치하지 않습니다.", + "b39d1428ec8b23f5": "이 주소에서 이제 다른 T3 Code 설치가 실행 중입니다({expected}이(가) 아닌 {actual}). 이 연결을 삭제한 후 다시 추가하세요.", "ea0d3e4e51d5706f": "환경 자격 증명이 올바르지 않습니다.", "7283ebfd16d09677": "환경 자격 증명에 필요한 액세스 권한이 없습니다.", "d3e9a9cb543b4b7b": "환경에서 인증 요청을 거부했습니다.", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 41316fb1f1748..bc9eee45bdcb3 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} não respondeu em nenhuma rota salva.", "b0dd3cd876937ca8": "O perfil de conexão {connectionId} não está disponível.", "5ce46783e79ca9d1": "A credencial de conexão {connectionId} não está disponível.", - "0bda0cac7f5acc20": "O ambiente conectado {actual} não corresponde a {expected}.", + "b39d1428ec8b23f5": "Este endereço agora executa outra instalação do T3 Code ({actual}, não {expected}). Remova esta conexão e adicione-a novamente.", "ea0d3e4e51d5706f": "A credencial do ambiente é inválida.", "7283ebfd16d09677": "A credencial do ambiente não concede o acesso necessário.", "d3e9a9cb543b4b7b": "O ambiente rejeitou a solicitação de autenticação.", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 6911eb2909c08..9decfe25c2132 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} не ответил ни по одному сохранённому маршруту.", "b0dd3cd876937ca8": "Профиль подключения {connectionId} недоступен.", "5ce46783e79ca9d1": "Учётные данные подключения {connectionId} недоступны.", - "0bda0cac7f5acc20": "Подключённое окружение {actual} не совпадает с {expected}.", + "b39d1428ec8b23f5": "По этому адресу теперь работает другая установка T3 Code ({actual}, а не {expected}). Удалите это подключение и добавьте его снова.", "ea0d3e4e51d5706f": "Учётные данные окружения недействительны.", "7283ebfd16d09677": "Учётные данные окружения не дают нужного доступа.", "d3e9a9cb543b4b7b": "Окружение отклонило запрос аутентификации.", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index ef96d1cda688b..505ae5682fdba 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} svarade inte på någon sparad rutt.", "b0dd3cd876937ca8": "Anslutningsprofilen {connectionId} är inte tillgänglig.", "5ce46783e79ca9d1": "Autentiseringsuppgiften för anslutningen {connectionId} är inte tillgänglig.", - "0bda0cac7f5acc20": "Den anslutna miljön {actual} matchar inte {expected}.", + "b39d1428ec8b23f5": "Den här adressen kör nu en annan T3 Code-installation ({actual}, inte {expected}). Ta bort anslutningen och lägg till den igen.", "ea0d3e4e51d5706f": "Miljöns autentiseringsuppgift är ogiltig.", "7283ebfd16d09677": "Miljöns autentiseringsuppgift ger inte den åtkomst som krävs.", "d3e9a9cb543b4b7b": "Miljön avvisade autentiseringsbegäran.", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index e130d8fdedba5..1388de0add451 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} 在所有已保存的路由上均无响应。", "b0dd3cd876937ca8": "连接配置 {connectionId} 不可用。", "5ce46783e79ca9d1": "连接凭据 {connectionId} 不可用。", - "0bda0cac7f5acc20": "已连接的环境 {actual} 与 {expected} 不一致。", + "b39d1428ec8b23f5": "此地址现在运行的是另一个 T3 Code 安装({actual},而非 {expected})。请移除此连接后重新添加。", "ea0d3e4e51d5706f": "环境凭据无效。", "7283ebfd16d09677": "环境凭据未授予所需的访问权限。", "d3e9a9cb543b4b7b": "环境拒绝了身份验证请求。", diff --git a/apps/web/src/components/sidebar/updateEverything.logic.test.ts b/apps/web/src/components/sidebar/updateEverything.logic.test.ts index ea44f1592a956..d6a052e551a35 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.test.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.test.ts @@ -93,7 +93,7 @@ describe("collectServerUpdateTargets", () => { expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([ ["nightly-service", "on the nightly channel"], ["offline", "not connected"], - ["never-connected", "not connected"], + ["never-connected", "still loading"], ["no-scope", "no permission"], ["busy", "already updating"], ["manual", "needs a manual update"], @@ -101,6 +101,33 @@ describe("collectServerUpdateTargets", () => { ]); }); + it("says why a disconnected server was skipped when its connection says", () => { + const replaced = + "This address now runs a different T3 Code install (b7a4, not 0359). Remove this connection and add it again."; + const { skipped } = collectServerUpdateTargets( + [ + machine("replaced", "0.0.40", "boot-service", { + connected: false, + serverConfig: null, + connectionError: replaced, + }), + machine("silent", "0.0.40", "boot-service", { connected: false, connectionError: null }), + machine("switched-off", "0.0.40", "boot-service", { + connected: false, + serverConfig: null, + turnedOff: true, + }), + ], + "0.0.50", + ); + + expect(skipped.map((entry) => [entry.label, entry.reason])).toEqual([ + ["replaced", replaced], + ["silent", "not connected"], + ["switched-off", "turned off"], + ]); + }); + it("does not offer a Nightly build to a Stable desktop app, whose own feed has nothing newer", () => { const { targets, skipped } = collectServerUpdateTargets( [machine("stable-desktop", "0.1.9", "desktop-managed")], diff --git a/apps/web/src/components/sidebar/updateEverything.logic.ts b/apps/web/src/components/sidebar/updateEverything.logic.ts index f9bf0976a22e4..30ac609419e0b 100644 --- a/apps/web/src/components/sidebar/updateEverything.logic.ts +++ b/apps/web/src/components/sidebar/updateEverything.logic.ts @@ -30,6 +30,10 @@ export interface UpdateEverythingMachine { readonly managedPolicy?: ServerConfig["managedPolicy"]; } | null; readonly connected: boolean; + /** Why the connection is down, when it says, in the active language. */ + readonly connectionError?: string | null; + /** The saved connection is switched off in Settings, so it never connects. */ + readonly turnedOff?: boolean; readonly hostedByThisApp: boolean; readonly canMaintain: boolean; readonly updateState: ServerUpdateState; @@ -149,7 +153,20 @@ function unavailableReason( machine: UpdateEverythingMachine, resolve: MessageResolver, ): string | null { - if (machine.serverConfig === null || !machine.connected) return resolve(msg("not connected")); + if (machine.turnedOff === true) { + return resolve( + msg("turned off", { + $context: "why a server update was skipped: its saved connection is off", + }), + ); + } + if (!machine.connected) return machine.connectionError ?? resolve(msg("not connected")); + if (machine.serverConfig === null) + return resolve( + msg("still loading", { + $context: "why a server update was skipped: its settings have not arrived yet", + }), + ); if (!machine.canMaintain) return resolve(msg("no permission")); if (machine.updateState.status === "running") return resolve(msg("already updating")); return null; diff --git a/apps/web/src/components/sidebar/useUpdateEverything.ts b/apps/web/src/components/sidebar/useUpdateEverything.ts index 87c3a43a598eb..9b8686085b1bd 100644 --- a/apps/web/src/components/sidebar/useUpdateEverything.ts +++ b/apps/web/src/components/sidebar/useUpdateEverything.ts @@ -1,5 +1,6 @@ import { msg, useMessages } from "gt-react"; import { useAtomValue } from "@effect/atom-react"; +import { connectionErrorText } from "@t3tools/client-runtime/connection"; import { PROVIDER_DISPLAY_NAMES } from "@t3tools/contracts"; import { APP_VERSION } from "~/branding"; @@ -65,6 +66,8 @@ export function useUpdateEverything( label: environment.label, serverConfig: environment.serverConfig, connected: environment.connection.phase === "connected", + connectionError: connectionErrorText(environment.connection, resolve), + turnedOff: !environment.entry.enabled, hostedByThisApp: isHostedByThisApp(environment), canMaintain: canUpdateServer(sessionStates[index]!), updateState: updateStates[index]!, diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 5f47b3f26a63c..9bffdc0b7b720 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} hat auf keiner gespeicherten Route geantwortet.", "b0dd3cd876937ca8": "Verbindungsprofil {connectionId} ist nicht verfügbar.", "5ce46783e79ca9d1": "Zugangsdaten der Verbindung {connectionId} sind nicht verfügbar.", - "0bda0cac7f5acc20": "Die verbundene Umgebung {actual} stimmt nicht mit {expected} überein.", + "b39d1428ec8b23f5": "Unter dieser Adresse läuft jetzt eine andere T3 Code-Installation ({actual}, nicht {expected}). Entferne diese Verbindung und füge sie erneut hinzu.", "ea0d3e4e51d5706f": "Die Zugangsdaten der Umgebung sind ungültig.", "7283ebfd16d09677": "Die Zugangsdaten der Umgebung gewähren nicht den erforderlichen Zugriff.", "d3e9a9cb543b4b7b": "Die Umgebung hat die Authentifizierungsanfrage abgelehnt.", @@ -12135,6 +12135,8 @@ "f13e08bd3614112e": "T3 Code auf diesem Rechner aktualisieren", "3c3348c36a2695af": "Update-Kanal auf diesem Rechner ändern", "fa8faa732a2688ef": "im Kanal {channel}", + "e65649675cb4cbaa": "ausgeschaltet", + "a1e7c08d9ef315c7": "lädt noch", "9b961309baafa09d": "keine Berechtigung", "9bafb2622c22d145": "wird bereits aktualisiert", "61aa0109862ff7ca": "Nightly", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 6692013f798cf..d62730f5addeb 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} did not answer on any saved route.", "b0dd3cd876937ca8": "Connection profile {connectionId} is unavailable.", "5ce46783e79ca9d1": "Connection credential {connectionId} is unavailable.", - "0bda0cac7f5acc20": "Connected environment {actual} does not match {expected}.", + "b39d1428ec8b23f5": "This address now runs a different T3 Code install ({actual}, not {expected}). Remove this connection and add it again.", "ea0d3e4e51d5706f": "The environment credential is invalid.", "7283ebfd16d09677": "The environment credential does not grant the required access.", "d3e9a9cb543b4b7b": "The environment rejected the authentication request.", @@ -12143,6 +12143,8 @@ "f13e08bd3614112e": "update T3 Code on that machine", "3c3348c36a2695af": "change the update track on that machine", "fa8faa732a2688ef": "on the {channel} channel", + "e65649675cb4cbaa": "turned off", + "a1e7c08d9ef315c7": "still loading", "9b961309baafa09d": "no permission", "9bafb2622c22d145": "already updating", "61aa0109862ff7ca": "Nightly", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 2360dd6131602..4ded558e58454 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} no respondió en ninguna de las rutas guardadas.", "b0dd3cd876937ca8": "El perfil de conexión {connectionId} no está disponible.", "5ce46783e79ca9d1": "La credencial de conexión {connectionId} no está disponible.", - "0bda0cac7f5acc20": "El entorno conectado {actual} no coincide con {expected}.", + "b39d1428ec8b23f5": "Esta dirección ahora ejecuta otra instalación de T3 Code ({actual}, no {expected}). Elimina esta conexión y vuelve a añadirla.", "ea0d3e4e51d5706f": "La credencial del entorno no es válida.", "7283ebfd16d09677": "La credencial del entorno no concede el acceso necesario.", "d3e9a9cb543b4b7b": "El entorno rechazó la solicitud de autenticación.", @@ -12128,6 +12128,8 @@ "f13e08bd3614112e": "actualiza T3 Code en ese equipo", "3c3348c36a2695af": "cambia el canal de actualizaciones en ese equipo", "fa8faa732a2688ef": "en el canal {channel}", + "e65649675cb4cbaa": "desactivado", + "a1e7c08d9ef315c7": "aún cargando", "9b961309baafa09d": "sin permiso", "9bafb2622c22d145": "ya se está actualizando", "61aa0109862ff7ca": "Nightly", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index ab7d02a64ccea..60dae1d830451 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} n’a répondu sur aucune route enregistrée.", "b0dd3cd876937ca8": "Le profil de connexion {connectionId} n’est pas disponible.", "5ce46783e79ca9d1": "Les identifiants de connexion {connectionId} ne sont pas disponibles.", - "0bda0cac7f5acc20": "L’environnement connecté {actual} ne correspond pas à {expected}.", + "b39d1428ec8b23f5": "Cette adresse exécute désormais une autre installation de T3 Code ({actual}, et non {expected}). Supprimez cette connexion et ajoutez-la à nouveau.", "ea0d3e4e51d5706f": "Les identifiants de l’environnement ne sont pas valides.", "7283ebfd16d09677": "Les identifiants de l’environnement n’accordent pas l’accès requis.", "d3e9a9cb543b4b7b": "L’environnement a rejeté la demande d’authentification.", @@ -12133,6 +12133,8 @@ "f13e08bd3614112e": "mettez à jour T3 Code sur cette machine", "3c3348c36a2695af": "changez le canal de mise à jour sur cette machine", "fa8faa732a2688ef": "sur le canal {channel}", + "e65649675cb4cbaa": "désactivé", + "a1e7c08d9ef315c7": "chargement en cours", "9b961309baafa09d": "pas d’autorisation", "9bafb2622c22d145": "déjà en cours de mise à jour", "61aa0109862ff7ca": "Nightly", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 4e9d5932837f4..8f3380f194613 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} は保存されたどのルートでも応答しませんでした。", "b0dd3cd876937ca8": "接続プロファイル {connectionId} は利用できません。", "5ce46783e79ca9d1": "接続の資格情報 {connectionId} は利用できません。", - "0bda0cac7f5acc20": "接続した環境 {actual} が {expected} と一致しません。", + "b39d1428ec8b23f5": "このアドレスでは別の T3 Code が動作しています({expected} ではなく {actual})。この接続を削除して、もう一度追加してください。", "ea0d3e4e51d5706f": "環境の資格情報が無効です。", "7283ebfd16d09677": "環境の資格情報に必要なアクセス権がありません。", "d3e9a9cb543b4b7b": "環境が認証リクエストを拒否しました。", @@ -12084,6 +12084,8 @@ "f13e08bd3614112e": "そのマシンで T3 Code を更新してください", "3c3348c36a2695af": "そのマシンで更新トラックを変更してください", "fa8faa732a2688ef": "{channel} チャネル", + "e65649675cb4cbaa": "オフ", + "a1e7c08d9ef315c7": "読み込み中", "9b961309baafa09d": "権限なし", "9bafb2622c22d145": "すでに更新中", "61aa0109862ff7ca": "Nightly", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 59e53d32f4e5f..f2f266662eb74 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host}이(가) 저장된 경로 중 어디에서도 응답하지 않았습니다.", "b0dd3cd876937ca8": "연결 프로필 {connectionId}을(를) 사용할 수 없습니다.", "5ce46783e79ca9d1": "연결 자격 증명 {connectionId}을(를) 사용할 수 없습니다.", - "0bda0cac7f5acc20": "연결된 환경 {actual}이(가) {expected}과(와) 일치하지 않습니다.", + "b39d1428ec8b23f5": "이 주소에서 이제 다른 T3 Code 설치가 실행 중입니다({expected}이(가) 아닌 {actual}). 이 연결을 삭제한 후 다시 추가하세요.", "ea0d3e4e51d5706f": "환경 자격 증명이 올바르지 않습니다.", "7283ebfd16d09677": "환경 자격 증명에 필요한 액세스 권한이 없습니다.", "d3e9a9cb543b4b7b": "환경에서 인증 요청을 거부했습니다.", @@ -12080,6 +12080,8 @@ "f13e08bd3614112e": "해당 기기에서 T3 Code를 업데이트하세요", "3c3348c36a2695af": "해당 기기에서 업데이트 트랙을 변경하세요", "fa8faa732a2688ef": "{channel} 채널", + "e65649675cb4cbaa": "꺼짐", + "a1e7c08d9ef315c7": "불러오는 중", "9b961309baafa09d": "권한 없음", "9bafb2622c22d145": "이미 업데이트 중", "61aa0109862ff7ca": "Nightly", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 31e64a75d0a00..7348253aa8980 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} não respondeu em nenhuma rota salva.", "b0dd3cd876937ca8": "O perfil de conexão {connectionId} não está disponível.", "5ce46783e79ca9d1": "A credencial de conexão {connectionId} não está disponível.", - "0bda0cac7f5acc20": "O ambiente conectado {actual} não corresponde a {expected}.", + "b39d1428ec8b23f5": "Este endereço agora executa outra instalação do T3 Code ({actual}, não {expected}). Remova esta conexão e adicione-a novamente.", "ea0d3e4e51d5706f": "A credencial do ambiente é inválida.", "7283ebfd16d09677": "A credencial do ambiente não concede o acesso necessário.", "d3e9a9cb543b4b7b": "O ambiente rejeitou a solicitação de autenticação.", @@ -12133,6 +12133,8 @@ "f13e08bd3614112e": "atualize o T3 Code nessa máquina", "3c3348c36a2695af": "mude o canal de atualização nessa máquina", "fa8faa732a2688ef": "no canal {channel}", + "e65649675cb4cbaa": "desativado", + "a1e7c08d9ef315c7": "ainda carregando", "9b961309baafa09d": "sem permissão", "9bafb2622c22d145": "já está atualizando", "61aa0109862ff7ca": "Nightly", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6ca368e7b3aff..4b428ec6a1751 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} не ответил ни по одному сохранённому маршруту.", "b0dd3cd876937ca8": "Профиль подключения {connectionId} недоступен.", "5ce46783e79ca9d1": "Учётные данные подключения {connectionId} недоступны.", - "0bda0cac7f5acc20": "Подключённое окружение {actual} не совпадает с {expected}.", + "b39d1428ec8b23f5": "По этому адресу теперь работает другая установка T3 Code ({actual}, а не {expected}). Удалите это подключение и добавьте его снова.", "ea0d3e4e51d5706f": "Учётные данные окружения недействительны.", "7283ebfd16d09677": "Учётные данные окружения не дают нужного доступа.", "d3e9a9cb543b4b7b": "Окружение отклонило запрос аутентификации.", @@ -12134,6 +12134,8 @@ "f13e08bd3614112e": "обновите T3 Code на этом компьютере", "3c3348c36a2695af": "смените канал обновлений на этом компьютере", "fa8faa732a2688ef": "на канале {channel}", + "e65649675cb4cbaa": "выключено", + "a1e7c08d9ef315c7": "ещё загружается", "9b961309baafa09d": "нет прав", "9bafb2622c22d145": "уже обновляется", "61aa0109862ff7ca": "Nightly", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c798ee120864d..353f3554e31e9 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} svarade inte på någon sparad rutt.", "b0dd3cd876937ca8": "Anslutningsprofilen {connectionId} är inte tillgänglig.", "5ce46783e79ca9d1": "Autentiseringsuppgiften för anslutningen {connectionId} är inte tillgänglig.", - "0bda0cac7f5acc20": "Den anslutna miljön {actual} matchar inte {expected}.", + "b39d1428ec8b23f5": "Den här adressen kör nu en annan T3 Code-installation ({actual}, inte {expected}). Ta bort anslutningen och lägg till den igen.", "ea0d3e4e51d5706f": "Miljöns autentiseringsuppgift är ogiltig.", "7283ebfd16d09677": "Miljöns autentiseringsuppgift ger inte den åtkomst som krävs.", "d3e9a9cb543b4b7b": "Miljön avvisade autentiseringsbegäran.", @@ -12141,6 +12141,8 @@ "f13e08bd3614112e": "uppdatera T3 Code på den datorn", "3c3348c36a2695af": "byt uppdateringsspår på den datorn", "fa8faa732a2688ef": "på kanalen {channel}", + "e65649675cb4cbaa": "avstängd", + "a1e7c08d9ef315c7": "läses fortfarande in", "9b961309baafa09d": "ingen behörighet", "9bafb2622c22d145": "uppdateras redan", "61aa0109862ff7ca": "Nightly", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index e3c47287652be..1b72edb0ab4d4 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -497,7 +497,7 @@ "bc24c300d53d61c5": "{host} 在所有已保存的路由上均无响应。", "b0dd3cd876937ca8": "连接配置 {connectionId} 不可用。", "5ce46783e79ca9d1": "连接凭据 {connectionId} 不可用。", - "0bda0cac7f5acc20": "已连接的环境 {actual} 与 {expected} 不一致。", + "b39d1428ec8b23f5": "此地址现在运行的是另一个 T3 Code 安装({actual},而非 {expected})。请移除此连接后重新添加。", "ea0d3e4e51d5706f": "环境凭据无效。", "7283ebfd16d09677": "环境凭据未授予所需的访问权限。", "d3e9a9cb543b4b7b": "环境拒绝了身份验证请求。", @@ -12159,6 +12159,8 @@ "f13e08bd3614112e": "请在该机器上更新 T3 Code", "3c3348c36a2695af": "请在该机器上更改更新通道", "fa8faa732a2688ef": "使用 {channel} 通道", + "e65649675cb4cbaa": "已关闭", + "a1e7c08d9ef315c7": "仍在加载", "9b961309baafa09d": "没有权限", "9bafb2622c22d145": "正在更新", "61aa0109862ff7ca": "Nightly 版", diff --git a/packages/client-runtime/src/connection/errors.ts b/packages/client-runtime/src/connection/errors.ts index 67d840f58a4e5..383abf83b2f12 100644 --- a/packages/client-runtime/src/connection/errors.ts +++ b/packages/client-runtime/src/connection/errors.ts @@ -54,10 +54,10 @@ export function environmentMismatchError(input: { return new ConnectionBlockedError({ reason: "configuration", ...translatableDetail( - msg("Connected environment {actual} does not match {expected}.", { - actual: input.actual, - expected: input.expected, - }), + msg( + "This address now runs a different T3 Code install ({actual}, not {expected}). Remove this connection and add it again.", + { actual: input.actual, expected: input.expected }, + ), ), }); } diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index 27bb60f567e10..b69793f3d4cee 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -1079,7 +1079,8 @@ describe("RpcSessionFactory", () => { const error = yield* Fiber.join(readyFiber); expect(error).toMatchObject({ reason: "configuration", - message: "Connected environment environment-2 does not match environment-1.", + message: + "This address now runs a different T3 Code install (environment-2, not environment-1). Remove this connection and add it again.", }); expect((yield* Fiber.join(configFiber))._tag).toBe("RpcClientError"); expect((yield* Fiber.join(customConfigFiber))._tag).toBe("RpcClientError"); From 426dac005055203f731c05c4a3c107ba3d1381dc Mon Sep 17 00:00:00 2001 From: Ryan Ilano Date: Tue, 24 Nov 2026 01:42:36 -0500 Subject: [PATCH 003/277] fix(web): expose diagnostics CPU history values to screen readers (#41948) Co-authored-by: Julius Marminge --- .../components/settings/DiagnosticsSettings.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsx index c5b40aadbf867..75817a6e1b5ba 100644 --- a/apps/web/src/components/settings/DiagnosticsSettings.tsx +++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx @@ -529,13 +529,13 @@ function ProcessResourceHistoryChart({ -
+
+ + {gt("Average CPU {average}%, peak CPU {peak}%", { + average: bucket.avgCpuPercent.toFixed(1), + peak: bucket.maxCpuPercent.toFixed(1), + })} +
Date: Tue, 24 Nov 2026 01:56:37 -0500 Subject: [PATCH 004/277] fix(web): copied startup error details no longer end in a broken character (#41937) Co-authored-by: Julius Marminge --- apps/web/src/lib/bootError.test.ts | 3 +++ apps/web/src/lib/bootError.ts | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/apps/web/src/lib/bootError.test.ts b/apps/web/src/lib/bootError.test.ts index e04e8bef2cfb4..60d655cccadc0 100644 --- a/apps/web/src/lib/bootError.test.ts +++ b/apps/web/src/lib/bootError.test.ts @@ -112,6 +112,9 @@ describe("buildErrorReport", () => { expect(report).toContain("[truncated]"); expect(report.length).toBeLessThan(7_000); expect(report).toContain("Time: 2026-10-26T00:00:00.000Z"); + expect(buildErrorReport(`${"x".repeat(5_999)}😀 tail`, environment)).toMatch( + new RegExp(`^x{5999}\\n\\[truncated\\]\\n`), + ); }); }); diff --git a/apps/web/src/lib/bootError.ts b/apps/web/src/lib/bootError.ts index 49fd3aec52ca9..d2852e2d70efb 100644 --- a/apps/web/src/lib/bootError.ts +++ b/apps/web/src/lib/bootError.ts @@ -105,7 +105,10 @@ export function buildErrorReport(error: unknown, environment: BootErrorEnvironme } let details = redact(parts.join("\n") || "(no error message)"); if (details.length > MAX_ERROR_CHARS) { - details = `${details.slice(0, MAX_ERROR_CHARS)}\n[truncated]`; + let end = MAX_ERROR_CHARS; + const last = details.charCodeAt(end - 1); + if (last >= 0xd800 && last <= 0xdbff) end -= 1; + details = `${details.slice(0, end)}\n[truncated]`; } return [ details, From 4afdfefde06235d979734fba1e5fa6d9d723fa3f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 22:59:58 -0800 Subject: [PATCH 005/277] ci: the release version bump is pushed by a job that installs nothing (#41969) Co-authored-by: Claude Fable 5.2 --- .github/scripts/set-release-version.cjs | 31 ++++++++++++++ .github/scripts/workflow-credentials.test.cjs | 42 +++++++++++++++++++ .github/workflows/release.yml | 30 +++++-------- 3 files changed, 83 insertions(+), 20 deletions(-) create mode 100644 .github/scripts/set-release-version.cjs diff --git a/.github/scripts/set-release-version.cjs b/.github/scripts/set-release-version.cjs new file mode 100644 index 0000000000000..1a15e2f81475a --- /dev/null +++ b/.github/scripts/set-release-version.cjs @@ -0,0 +1,31 @@ +const fs = require("node:fs"); + +// The manifests in scripts/lib/tagged-source-version.ts. +const RELEASE_PACKAGE_FILES = [ + "apps/server/package.json", + "apps/desktop/package.json", + "apps/web/package.json", + "packages/contracts/package.json", +]; +const VERSION_LINE = /^( {2}"version": ")[^"]*(",?)$/gm; + +// Replaces one string literal, so the result needs no formatter and no dependencies. +function setReleaseVersion(source, version) { + if (!/^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$/.test(version)) { + throw new Error(`Invalid release version: '${version}'.`); + } + if (source.match(VERSION_LINE)?.length !== 1) { + throw new Error("Expected exactly one top-level version in the manifest"); + } + return source.replace(VERSION_LINE, `$1${version}$2`); +} + +if (require.main === module) { + for (const file of RELEASE_PACKAGE_FILES) { + const source = fs.readFileSync(file, "utf8"); + const next = setReleaseVersion(source, process.argv[2] ?? ""); + if (next !== source) fs.writeFileSync(file, next); + } +} + +module.exports = { RELEASE_PACKAGE_FILES, setReleaseVersion }; diff --git a/.github/scripts/workflow-credentials.test.cjs b/.github/scripts/workflow-credentials.test.cjs index 87313178cd152..35d0c5bf56e73 100644 --- a/.github/scripts/workflow-credentials.test.cjs +++ b/.github/scripts/workflow-credentials.test.cjs @@ -13,6 +13,7 @@ const { join } = require("node:path"); const { test } = require("node:test"); const { setMobileVersion } = require("./set-mobile-version.cjs"); +const { RELEASE_PACKAGE_FILES, setReleaseVersion } = require("./set-release-version.cjs"); const read = (path) => readFileSync(join(__dirname, "..", path), "utf8"); @@ -200,6 +201,15 @@ test("the version override token covers this repository only", () => { assert.doesNotMatch(production, /RELEASE_APP|create-github-app-token/); }); +test("the release version bump is pushed by a job that installs nothing, with a token for this repository only", () => { + const { finalize } = jobs("workflows/release.yml"); + const mint = steps(finalize).find((step) => step.includes("create-github-app-token")); + assert.doesNotMatch(mint, /^\s+(?:owner|repositories):/m); + assert.match(mint, /^\s+permission-contents: write$/m); + assert.ok(!runsProjectCode(finalize), "finalize holds a write token and runs code"); + assert.match(finalize, /run: node \.github\/scripts\/set-release-version\.cjs /); +}); + test("the Vite+ toolchain is cached before the job installs or runs project code", () => { const names = Array.from( read("actions/setup-ci-deps/action.yml").matchAll( @@ -300,3 +310,35 @@ test("a version override rewrites only the app version", () => { } assert.throws(() => setMobileVersion("export default {};", "1.2.3"), /Could not update/); }); + +test("a release version bump rewrites only the version of each release manifest", () => { + const listed = /releasePackageFiles = \[\n([^\]]+)\]/.exec( + read("../scripts/lib/tagged-source-version.ts"), + )[1]; + assert.deepEqual( + RELEASE_PACKAGE_FILES, + Array.from(listed.matchAll(/"([^"]+)"/g), (m) => m[1]), + ); + for (const file of RELEASE_PACKAGE_FILES) { + const manifest = read(`../${file}`); + const next = setReleaseVersion(manifest, "98.7.6"); + assert.equal(JSON.parse(next).version, "98.7.6"); + assert.deepEqual( + { ...JSON.parse(next), version: "" }, + { ...JSON.parse(manifest), version: "" }, + ); + assert.equal(setReleaseVersion(next, "98.7.6"), next); + assert.deepEqual( + next.split("\n").filter((line, index) => line !== manifest.split("\n")[index]).length, + 1, + ); + } + for (const version of ["", "1", "1.2", "v1.2.3", '1.2.3", "x": "y']) { + assert.throws(() => setReleaseVersion('{\n "version": "1.0.0"\n}\n', version), /Invalid/); + } + assert.equal( + setReleaseVersion('{\n "version": "1.0.0"\n}\n', "1.2.3-rc.1"), + '{\n "version": "1.2.3-rc.1"\n}\n', + ); + assert.throws(() => setReleaseVersion('{\n "name": "x"\n}\n', "1.2.3"), /exactly one/); +}); diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 92ec860dbe33c..6fe82ebcb0069 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1471,6 +1471,8 @@ jobs: --token "$VERCEL_TOKEN" \ --scope "${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}" + # Commits the version bump as the Release App. It installs nothing and runs no + # dependency code, so that token never shares a runner with any. finalize: name: Finalize release if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }} @@ -1478,13 +1480,14 @@ jobs: runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 10 steps: + # No owner input: the token covers this repository only, with contents write. - id: app_token name: Mint release app token uses: actions/create-github-app-token@fee1f7d63c2ff003460e3d139729b119787bc349 # v2.2.2 with: app-id: ${{ secrets.RELEASE_APP_ID }} private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} - owner: ${{ github.repository_owner }} + permission-contents: write - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -1508,32 +1511,19 @@ jobs: echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT" echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT" - - name: Setup dependencies - uses: ./.github/actions/setup-ci-deps - with: - install-args: --filter=@t3tools/scripts... --filter=@t3tools/oxlint-plugin-t3code... - - - id: update_versions - name: Update version strings + # Rewrites the version string in place: the manifests stay formatted, and + # the lockfile records no workspace package version. + - name: Update version strings env: RELEASE_VERSION: ${{ needs.preflight.outputs.version }} - run: node scripts/update-release-package-versions.ts "$RELEASE_VERSION" --github-output - - - name: Format package.json files - if: steps.update_versions.outputs.changed == 'true' - run: vp fmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json - - - name: Refresh lockfile - if: steps.update_versions.outputs.changed == 'true' - run: vp install --lockfile-only --ignore-scripts + run: node .github/scripts/set-release-version.cjs "$RELEASE_VERSION" - name: Commit and push version bump - if: steps.update_versions.outputs.changed == 'true' shell: bash env: RELEASE_TAG: ${{ needs.preflight.outputs.tag }} run: | - if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml; then + if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json; then echo "No version changes to commit." exit 0 fi @@ -1541,7 +1531,7 @@ jobs: git config user.name "${{ steps.app_bot.outputs.name }}" git config user.email "${{ steps.app_bot.outputs.email }}" - git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml + git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json git commit --no-verify -m "chore(release): prepare $RELEASE_TAG" # main moves while this job runs, so a rejected push rebases and retries. From 667116eee966bb740a566431cdf60eb223d1685e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:01:45 -0800 Subject: [PATCH 006/277] fix(server): Windows uninstall cleanup runs from System32 (#41967) Co-authored-by: Claude Fable 5.2 --- apps/server/src/cli/uninstall.test.ts | 145 +++++++++++++++----------- apps/server/src/cli/uninstall.ts | 20 ++-- 2 files changed, 95 insertions(+), 70 deletions(-) diff --git a/apps/server/src/cli/uninstall.test.ts b/apps/server/src/cli/uninstall.test.ts index 19093032fc3d3..c78f8a5df9c2c 100644 --- a/apps/server/src/cli/uninstall.test.ts +++ b/apps/server/src/cli/uninstall.test.ts @@ -2,7 +2,6 @@ import * as NodeChildProcess from "node:child_process"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; -import * as Config from "effect/Config"; import * as ConfigProvider from "effect/ConfigProvider"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -28,64 +27,80 @@ vi.mock("node:child_process", { spy: true }); afterEach(() => vi.restoreAllMocks()); -it.live("reports failure when the Windows cleanup shell cannot start", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-shell-" }); - const runtimeDir = path.join(baseDir, "runtime"); - yield* fs.makeDirectory(runtimeDir); - vi.spyOn(BootService, "layer").mockReturnValue( - Layer.succeed( - BootService.BootService, - BootService.BootService.of({ - status: Effect.succeed({ - supported: false, - installed: false, - current: false, - unitPath: "", - logPath: "", +it.live( + "runs the Windows cleanup from System32 and reports failure when its shell cannot start", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-shell-" }); + const runtimeDir = path.join(baseDir, "runtime"); + yield* fs.makeDirectory(runtimeDir); + vi.spyOn(BootService, "layer").mockReturnValue( + Layer.succeed( + BootService.BootService, + BootService.BootService.of({ + status: Effect.succeed({ + supported: false, + installed: false, + current: false, + unitPath: "", + logPath: "", + }), + withStopped: (operation) => operation, + restart: Effect.die("unexpected restart"), + install: () => Effect.die("unexpected install"), + uninstall: Effect.die("unexpected uninstall"), }), - withStopped: (operation) => operation, - restart: Effect.die("unexpected restart"), - install: () => Effect.die("unexpected install"), - uninstall: Effect.die("unexpected uninstall"), - }), - ), - ); - const actual = yield* Effect.promise(() => - vi.importActual("node:child_process"), - ); - const spawn = actual.spawn; - const failedSpawn = new Promise((resolve) => { - vi.spyOn(NodeChildProcess, "spawn").mockImplementation((...args) => { - const child = spawn(...args); - // Observe the real spawn error without letting it terminate the test runner. - child.once("error", resolve); - return child; + ), + ); + const actual = yield* Effect.promise(() => + vi.importActual("node:child_process"), + ); + const spawn = actual.spawn; + const spawned: Array> = []; + const failedSpawn = new Promise((resolve) => { + vi.spyOn(NodeChildProcess, "spawn").mockImplementation((...args) => { + spawned.push(args); + const child = spawn(...args); + // Observe the real spawn error without letting it terminate the test runner. + child.once("error", resolve); + return child; + }); }); - }); - const result = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([ - "--base-dir", - baseDir, - "--yes", - ]).pipe( - Effect.result, - Effect.provideService(HostProcess.Environment, { - ComSpec: path.join(baseDir, "missing-cmd.exe"), - }), - Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(HostProcess.IsExecutable, false), - Effect.provide( - Layer.mergeAll( - ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), - Layer.fresh(TestConsole.layer), + const result = yield* Command.runWith(uninstallCommand, { version: packageJson.version })([ + "--base-dir", + baseDir, + "--yes", + ]).pipe( + Effect.result, + Effect.provideService(HostProcess.Environment, { + ComSpec: path.join(baseDir, "missing-cmd.exe"), + SystemRoot: String.raw`C:\Windows`, + }), + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.IsExecutable, false), + Effect.provide( + Layer.mergeAll( + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })), + Layer.fresh(TestConsole.layer), + ), ), - ), - ); - yield* Effect.promise(() => failedSpawn); - expect(result._tag, "an unavailable cleanup shell must fail uninstall").toBe("Failure"); - }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer))), + ); + yield* Effect.promise(() => failedSpawn); + expect(result._tag, "an unavailable cleanup shell must fail uninstall").toBe("Failure"); + const [, args, options] = spawned[0]!; + expect(args.at(-1)).toBe( + '""%T3_UNINSTALL_PING%" -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""', + ); + expect(options).toMatchObject({ + cwd: String.raw`C:\Windows\System32`, + env: { + T3_UNINSTALL_PING: String.raw`C:\Windows\System32\ping.exe`, + T3_UNINSTALL_RUNTIME: runtimeDir, + }, + }); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NetService.layer))), ); it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 uninstall command", (it) => { @@ -277,7 +292,7 @@ it.layer(NodeServices.layer)("t3 uninstall launcher", (it) => { }); it.live.runIf(HostProcess.Platform.defaultValue() === "win32")( - "t3 uninstall has cmd.exe remove the runtime directory, preserving spaces and literal environment-variable syntax", + "t3 uninstall has cmd.exe remove the runtime directory with System32 tools, preserving spaces and literal environment-variable syntax", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -287,10 +302,19 @@ it.live.runIf(HostProcess.Platform.defaultValue() === "win32")( yield* fs.makeDirectory(path.join(runtimeDir, "versions", "1.0.0"), { recursive: true }); yield* fs.writeFileString(path.join(runtimeDir, "versions", "1.0.0", "t3.exe"), ""); - const child = spawnWindowsRemoval( - yield* Config.String("ComSpec").pipe(Config.withDefault("cmd.exe")), - runtimeDir, + // The directory `t3 uninstall` is run from holds its own `ping`, which must stay unused. + const marker = path.join(root, "ping-ran.txt"); + yield* fs.writeFileString(path.join(root, "ping.cmd"), '@echo ran>"%~dp0ping-ran.txt"\r\n'); + yield* Effect.acquireRelease( + Effect.sync(() => { + const previous = process.cwd(); + process.chdir(root); + return previous; + }), + (previous) => Effect.sync(() => process.chdir(previous)), ); + + const child = spawnWindowsRemoval(yield* HostProcess.Environment, runtimeDir); yield* Effect.callback((resume) => { child.once("error", (error) => resume(Effect.fail(error))); child.once("exit", (code) => @@ -299,5 +323,6 @@ it.live.runIf(HostProcess.Platform.defaultValue() === "win32")( }); assert.isFalse(yield* fs.exists(runtimeDir)); + assert.isFalse(yield* fs.exists(marker)); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/cli/uninstall.ts b/apps/server/src/cli/uninstall.ts index 07978299b4642..e1f535d7cd7a6 100644 --- a/apps/server/src/cli/uninstall.ts +++ b/apps/server/src/cli/uninstall.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off // Windows cleanup must outlive this executable to delete its directory; scoped ChildProcess kills children on exit. import * as NodeChildProcess from "node:child_process"; +import * as NodePath from "node:path"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Console from "effect/Console"; @@ -126,19 +127,22 @@ export const findRecordedLaunchers = Effect.fn("cli.uninstall.find_recorded_laun return owned; }); -// cmd.exe needs verbatim quoting and a literal path, with delayed expansion disabled. -export function spawnWindowsRemoval(comspec: string, dir: string) { +// cmd.exe needs verbatim quoting and literal paths, with delayed expansion disabled. The shell +// starts in System32 and runs ping from there, whatever directory `t3 uninstall` was run in. +export function spawnWindowsRemoval(environment: NodeJS.ProcessEnv, dir: string) { + const ping = windowsSystem32Path(environment, "ping.exe"); return NodeChildProcess.spawn( - comspec, + environment["ComSpec"] ?? environment["COMSPEC"] ?? windowsSystem32Path(environment, "cmd.exe"), [ "/d", "/v:off", "/s", "/c", - '"ping -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""', + '""%T3_UNINSTALL_PING%" -n 3 127.0.0.1 >nul & rmdir /s /q "%T3_UNINSTALL_RUNTIME%""', ], { - env: { ...process.env, T3_UNINSTALL_RUNTIME: dir }, + cwd: NodePath.win32.dirname(ping), + env: { ...process.env, T3_UNINSTALL_PING: ping, T3_UNINSTALL_RUNTIME: dir }, windowsVerbatimArguments: true, detached: true, stdio: "ignore", @@ -282,15 +286,11 @@ const runUninstall = Effect.fn("cli.uninstall.run")(function* (input: { // Windows refuses to unlink this running executable; a detached shell removes it after exit. if (platform === "win32") { const runtimeDir = plan.runtimeDir; - const comspec = - environment["ComSpec"] ?? - environment["COMSPEC"] ?? - windowsSystem32Path(environment, "cmd.exe"); const notScheduled = () => new CliUninstallError({ reason: `Could not schedule removal of ${runtimeDir}. Delete it yourself once this window is closed.`, }); - yield* awaitDetachedSpawn(() => spawnWindowsRemoval(comspec, runtimeDir)).pipe( + yield* awaitDetachedSpawn(() => spawnWindowsRemoval(environment, runtimeDir)).pipe( Effect.mapError(notScheduled), ); yield* Console.log(`${runtimeDir} will be removed once t3 exits.`); From 5b2299ca0a471f1ac9263b0e313f2b4394700d48 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:08:35 -0800 Subject: [PATCH 007/277] fix(server): Claude review guides use project launch settings and only their own tool list (#41972) Co-authored-by: Claude Fable 5.2 --- .../src/provider/Drivers/ClaudeSkills.ts | 19 +++ .../PullRequestReviewGuideService.ts | 1 + .../pullRequestReviewGuideInput.ts | 2 +- .../ClaudeTextGeneration.test.ts | 116 ++++++++++++++---- .../textGeneration/ClaudeTextGeneration.ts | 53 +++++++- .../CodexTextGeneration.test.ts | 1 + .../testing/ClaudeTextGeneration.fixture.mjs | 10 +- docs/user/source-control.md | 4 +- .../src/server/textGeneration.ts | 3 + .../src/server/textGenerationOperations.ts | 10 +- 10 files changed, 188 insertions(+), 31 deletions(-) diff --git a/apps/server/src/provider/Drivers/ClaudeSkills.ts b/apps/server/src/provider/Drivers/ClaudeSkills.ts index ae020bf40a8c1..05bb7f197c80f 100644 --- a/apps/server/src/provider/Drivers/ClaudeSkills.ts +++ b/apps/server/src/provider/Drivers/ClaudeSkills.ts @@ -700,6 +700,25 @@ export const readClaudeSettingsEnv = Effect.fn("readClaudeSettingsEnv")(function return settingsEnv; }); +const decodeSettingsRecord = Schema.decodeUnknownEffect( + fromLenientJson(Schema.Record(Schema.String, Schema.Unknown)), +); + +/** Claude's user settings file as written; undefined when it is missing or not a JSON object. */ +export const readClaudeUserSettings = Effect.fn("readClaudeUserSettings")(function* ( + config: Pick, + cwd: string | undefined, + environment: NodeJS.ProcessEnv, +): Effect.fn.Return | undefined, never, FileSystem.FileSystem | Path.Path> { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, cwd); + return yield* fileSystem.readFileString(path.join(configDirPath, "settings.json")).pipe( + Effect.flatMap(decodeSettingsRecord), + Effect.orElseSucceed(() => undefined), + ); +}); + /** The host of an `ANTHROPIC_BASE_URL` that is not Anthropic's own API. */ export function customClaudeApiEndpointHost(baseUrl: string | undefined): string | undefined { const endpoint = URL.parse(baseUrl?.trim() ?? ""); diff --git a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts index 580816890a390..c41ea07096909 100644 --- a/apps/server/src/pullRequest/PullRequestReviewGuideService.ts +++ b/apps/server/src/pullRequest/PullRequestReviewGuideService.ts @@ -402,6 +402,7 @@ const make = Effect.gen(function* () { generated: textGeneration.generateReviewGuide({ ...reviewGuideInputFromPullRequest(detail, activity, checkout.baseCommit), cwd: checkout.path, + projectCwd: workspaceRoot, modelSelection, projectId: input.projectId, instructions: projectSettings.reviewGuideInstructions, diff --git a/apps/server/src/pullRequest/pullRequestReviewGuideInput.ts b/apps/server/src/pullRequest/pullRequestReviewGuideInput.ts index 2f483490e86ed..e284292894b55 100644 --- a/apps/server/src/pullRequest/pullRequestReviewGuideInput.ts +++ b/apps/server/src/pullRequest/pullRequestReviewGuideInput.ts @@ -28,7 +28,7 @@ export function reviewGuideInputFromPullRequest( detail: PullRequestDetail, activity: PullRequestActivity, baseCommit: string, -): Omit { +): Omit { return { number: detail.number, title: detail.title, diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts index d26642616ea6c..92cc86b896054 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.test.ts @@ -69,6 +69,7 @@ function withFakeClaudeEnv( imageAttemptLog?: string; configDirMustBe?: string; cwdMustNotBe?: string; + settingsLog?: string; claudeConfig?: Partial; }, effectFn: (textGeneration: TextGeneration.TextGeneration["Service"]) => Effect.Effect, @@ -93,6 +94,7 @@ function withFakeClaudeEnv( T3_FAKE_CLAUDE_IMAGE_REJECTION: input.imageRejection, T3_FAKE_CLAUDE_IMAGE_ATTEMPT_LOG: input.imageAttemptLog, T3_FAKE_CLAUDE_CWD_MUST_NOT_BE: input.cwdMustNotBe, + T3_FAKE_CLAUDE_SETTINGS_LOG: input.settingsLog, T3_FAKE_CLAUDE_CONFIG_DIR_MUST_BE: input.configDirMustBe, }; const environment: NodeJS.ProcessEnv = { @@ -115,29 +117,101 @@ function withFakeClaudeEnv( }).pipe(Effect.scoped); } +const reviewGuideInput = { + number: 12, + title: "Review a change", + description: "", + baseBranch: "main", + baseCommit: "base", + settledReview: "", + modelSelection: createModelSelection( + ProviderInstanceId.make("claudeAgent"), + SYNTHETIC_CLAUDE_CAPABLE_MODEL, + ), +}; + it.layer(layerClaudeTextGenerationTest)("ClaudeTextGeneration", (it) => { - it.effect("loads only user settings when generating review guides", () => - withFakeClaudeEnv( - { - output: JSON.stringify({ structured_output: { stops: [] } }), - argsMustContain: "--setting-sources user", - expectedTools: "Read,Grep,Glob,Bash", - }, - (textGeneration) => - textGeneration.generateReviewGuide({ - cwd: process.cwd(), - number: 12, - title: "Review a change", - description: "", - baseBranch: "main", - baseCommit: "base", - settledReview: "", - modelSelection: createModelSelection( - ProviderInstanceId.make("claudeAgent"), - SYNTHETIC_CLAUDE_CAPABLE_MODEL, - ), + it.effect("reads a relative settings path for a review guide from the project folder", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-guide-" }); + const project = path.join(root, "project"); + const checkout = path.join(root, "checkout"); + for (const [directory, origin] of [ + [project, "project"], + [checkout, "checkout"], + ] as const) { + yield* fs.makeDirectory(directory); + yield* fs.writeFileString( + path.join(directory, "claude.json"), + JSON.stringify({ env: { ORIGIN: origin } }), + ); + } + const settingsLog = path.join(root, "settings.json"); + yield* withFakeClaudeEnv( + { + output: JSON.stringify({ structured_output: { stops: [] } }), + expectedTools: "Read,Grep,Glob,Bash", + settingsLog, + claudeConfig: { homePath: path.join(root, "home"), launchArgs: "--settings claude.json" }, + }, + (textGeneration) => + textGeneration.generateReviewGuide({ + ...reviewGuideInput, + cwd: checkout, + projectCwd: project, + }), + ); + expect(JSON.parse(yield* fs.readFileString(settingsLog))).toEqual({ + env: { ORIGIN: "project" }, + disableAllHooks: true, + }); + }), + ); + + it.effect("gives a review guide the user's settings without their pre-approved tools", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-guide-" }); + const home = path.join(root, "home"); + yield* fs.makeDirectory(home); + yield* fs.writeFileString( + path.join(home, "settings.json"), + JSON.stringify({ + env: { ENDPOINT: "user", SHARED: "user" }, + permissions: { allow: ["Bash(touch:*)"], deny: ["Read(./private/**)"] }, }), - ), + ); + const settingsLog = path.join(root, "settings.json"); + const launchSettings = JSON.stringify({ + env: { SHARED: "launch" }, + permissions: { allow: ["Bash(npm test:*)"], deny: ["Read(./keys/**)"] }, + }); + yield* withFakeClaudeEnv( + { + output: JSON.stringify({ structured_output: { stops: [] } }), + // The CLI loads no settings file of its own. + argsMustContain: "--setting-sources --disable-slash-commands", + argsMustNotContain: "ENDPOINT", + expectedTools: "Read,Grep,Glob,Bash", + settingsLog, + claudeConfig: { homePath: home, launchArgs: `--settings '${launchSettings}'` }, + }, + (textGeneration) => + textGeneration.generateReviewGuide({ + ...reviewGuideInput, + cwd: process.cwd(), + projectCwd: process.cwd(), + }), + ); + expect(JSON.parse(yield* fs.readFileString(settingsLog))).toEqual({ + env: { ENDPOINT: "user", SHARED: "launch" }, + permissions: { deny: ["Read(./private/**)", "Read(./keys/**)"] }, + disableAllHooks: true, + }); + }), ); it.effect( diff --git a/apps/server/src/textGeneration/ClaudeTextGeneration.ts b/apps/server/src/textGeneration/ClaudeTextGeneration.ts index 30e0c5c6841de..0d1c5eb54f38e 100644 --- a/apps/server/src/textGeneration/ClaudeTextGeneration.ts +++ b/apps/server/src/textGeneration/ClaudeTextGeneration.ts @@ -2,6 +2,7 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; @@ -9,6 +10,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { type ClaudeSettings, TextGenerationError } from "@t3tools/contracts"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; +import { deepMerge } from "@t3tools/shared/Struct"; import * as TextGenerationOperations from "@t3tools/provider-core/server/textGenerationOperations"; import { @@ -34,6 +36,7 @@ import { hasClaudeManagedMcpConfig, makeClaudeEnvironment, } from "../provider/Drivers/ClaudeHome.ts"; +import { readClaudeUserSettings } from "../provider/Drivers/ClaudeSkills.ts"; import { readClaudeLaunchArgSettings } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts"; import { resolveAttachmentPath } from "../attachmentStore.ts"; import * as ServerConfig from "../config.ts"; @@ -41,7 +44,7 @@ import * as ServerConfig from "../config.ts"; const CLAUDE_TIMEOUT_MS = 180_000; /** `--tools` takes bare names; patterns go in the allow list. */ const CLAUDE_INVESTIGATION_TOOLS = "Read,Grep,Glob,Bash"; -/** In dontAsk mode every call outside this list, Bash included, is refused. */ +/** In dontAsk mode every call outside this list, Bash included, is refused; investigationSettings keeps settings from adding to it. */ const CLAUDE_INVESTIGATION_ALLOWED = [ "Read", "Grep", @@ -53,6 +56,26 @@ const CLAUDE_INVESTIGATION_ALLOWED = [ // Denies override allows; block git --output/-o because allowed trailing args can otherwise write anywhere. const CLAUDE_INVESTIGATION_DENIED = ["Bash(git * --output*)", "Bash(git * -o *)"].join(","); +/** + * Settings for an investigation, which runs with `--setting-sources ""`: the user's settings file + * and the launch argument's settings as Claude Code would merge them, keeping from `permissions` + * only the deny rules. Allow rules, extra directories and a default mode would approve calls + * beyond the investigation's own list. + */ +function investigationSettings( + userSettings: Record | undefined, + launchArgSettings: Record | undefined, +): Record { + const { permissions: _, ...settings } = deepMerge(userSettings ?? {}, launchArgSettings ?? {}); + const deny = [userSettings, launchArgSettings].flatMap((source) => { + const permissions = source?.permissions; + return Predicate.isObject(permissions) && Array.isArray(permissions.deny) + ? permissions.deny + : []; + }); + return deny.length > 0 ? { ...settings, permissions: { deny: [...new Set(deny)] } } : settings; +} + const NO_SESSION_PERSISTENCE = "--no-session-persistence"; // Claude Code before 2.0.63 exits with this on stderr; those runs retry without the flag. const NO_SESSION_PERSISTENCE_REJECTED = `error: unknown option '${NO_SESSION_PERSISTENCE}'`; @@ -244,7 +267,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined; const launchArgSettings = yield* readClaudeLaunchArgSettings({ settings: claudeSettings, - cwd, + // The investigated checkout holds the change under review, not the user's files. + cwd: investigate?.projectCwd ?? cwd, fileSystem, path, }).pipe( @@ -253,7 +277,15 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu ), ); const settings = { - ...launchArgSettings, + ...(investigate + ? investigationSettings( + yield* readClaudeUserSettings(claudeSettings, workingDirectory, claudeEnvironment).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ), + launchArgSettings, + ) + : launchArgSettings), disableAllHooks: true, ...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}), ...(fastMode ? { fastMode: true } : {}), @@ -264,6 +296,17 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu settings, "Failed to encode Claude CLI settings.", ); + // The user's settings can hold credentials; a file keeps them out of the process list. + const settingsArgument = investigate + ? yield* fileSystem + .makeTempFileScoped({ prefix: "t3code-claude-settings-", suffix: ".json" }) + .pipe( + Effect.tap((filePath) => fileSystem.writeFileString(filePath, settingsJson)), + Effect.mapError((cause) => + normalizeCliError("claude", operation, cause, "Failed to write Claude CLI settings"), + ), + ) + : settingsJson; // `claude -p` accepts images only as content blocks of a stream-json user message. const apiModelId = resolveClaudeCatalogApiModelId(catalog, resolvedModelSelection); @@ -300,7 +343,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu apiModelId, ...(cliEffort ? ["--effort", cliEffort] : []), "--settings", - settingsJson, + settingsArgument, ...(investigate ? [ "--tools", @@ -311,7 +354,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu CLAUDE_INVESTIGATION_DENIED, ] : ["--tools", ""]), - ...(investigate ? ["--setting-sources", "user"] : []), + ...(investigate ? ["--setting-sources", ""] : []), "--disable-slash-commands", ...(noSessionPersistence ? [NO_SESSION_PERSISTENCE] : []), // managed-mcp.json already isolates servers and makes Claude reject this flag. diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index 1462983e949b1..11c4c2c351306 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -915,6 +915,7 @@ it.effect( ); const input = { cwd: "/tmp", + projectCwd: "/tmp", number: 1, title: "Change", description: "", diff --git a/apps/server/src/textGeneration/testing/ClaudeTextGeneration.fixture.mjs b/apps/server/src/textGeneration/testing/ClaudeTextGeneration.fixture.mjs index 9405e52927ae3..5fd955ec1bb7f 100644 --- a/apps/server/src/textGeneration/testing/ClaudeTextGeneration.fixture.mjs +++ b/apps/server/src/textGeneration/testing/ClaudeTextGeneration.fixture.mjs @@ -36,9 +36,17 @@ if (process.env.T3_FAKE_CLAUDE_REJECTS_NO_SESSION_PERSISTENCE === "1") { fail("text generation must not save a resumable session", 16); } const settingsIndex = argv.indexOf("--settings"); -if (settingsIndex === -1 || JSON.parse(argv[settingsIndex + 1]).disableAllHooks !== true) { +const settingsValue = settingsIndex === -1 ? "{}" : argv[settingsIndex + 1]; +// Like the CLI: a value starting with a brace is inline JSON, anything else a file path. +const settingsText = settingsValue.startsWith("{") + ? settingsValue + : NodeFS.readFileSync(settingsValue, "utf8"); +if (JSON.parse(settingsText).disableAllHooks !== true) { fail("text generation must disable hooks", 10); } +if (process.env.T3_FAKE_CLAUDE_SETTINGS_LOG) { + NodeFS.writeFileSync(process.env.T3_FAKE_CLAUDE_SETTINGS_LOG, settingsText); +} const cwdMustNotBe = process.env.T3_FAKE_CLAUDE_CWD_MUST_NOT_BE; if (cwdMustNotBe && NodeFS.realpathSync(process.cwd()) === NodeFS.realpathSync(cwdMustNotBe)) { fail("text generation ran in the project directory", 11); diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 3791d137bf91e..d436cd64eb144 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -309,7 +309,9 @@ Choose **Write guide** to have the review guide model from Settings → Source c change in a temporary checkout; without one set, the source control writer model is used. Nothing in the checkout is changed, and a large pull request takes a few minutes; you can go elsewhere in the app. On web, you are told when the guide is ready; on mobile, return to the guide to check -its progress. Claude and Codex can write guides. The guide is +its progress. Claude and Codex can write guides. Claude writes them with your user settings, but +tool approvals in those settings do not apply: it reads files and runs `git diff`, `git log` and +`git show`, nothing else. The guide is kept for everyone using this server. To write it again, for example after a push or after changing the model or instructions, choose **Rewrite guide** from the pull request's **⋯** menu. diff --git a/packages/provider-core/src/server/textGeneration.ts b/packages/provider-core/src/server/textGeneration.ts index ff253b86b4794..144952a321307 100644 --- a/packages/provider-core/src/server/textGeneration.ts +++ b/packages/provider-core/src/server/textGeneration.ts @@ -87,7 +87,10 @@ export interface ReviewGuideStackLayer { } export interface ReviewGuideGenerationInput { + /** A scratch checkout of the pull request's head. */ cwd: string; + /** The project folder the checkout was made from; the user's own relative paths resolve here. */ + projectCwd: string; number: number; title: string; description: string; diff --git a/packages/provider-core/src/server/textGenerationOperations.ts b/packages/provider-core/src/server/textGenerationOperations.ts index 4914c34de0e1a..5e7bd0caab0d4 100644 --- a/packages/provider-core/src/server/textGenerationOperations.ts +++ b/packages/provider-core/src/server/textGenerationOperations.ts @@ -31,7 +31,13 @@ export interface Request { readonly modelSelection: ModelSelection; readonly attachments?: ReadonlyArray | undefined; /** Investigate cwd with read-only tools across turns; fail if the runner cannot guarantee read-only access. */ - readonly investigate?: { readonly timeoutMs: number } | undefined; + readonly investigate?: + | { + readonly timeoutMs: number; + /** cwd holds the content under review; paths the user configured resolve here instead. */ + readonly projectCwd: string; + } + | undefined; } const INVESTIGATION_TIMEOUT_MS = 15 * 60_000; @@ -190,7 +196,7 @@ export function fromRunner(name: string, run: Runner): ProviderTextGeneration { operation: "generateReviewGuide", cwd: input.cwd, modelSelection: input.modelSelection, - investigate: { timeoutMs: INVESTIGATION_TIMEOUT_MS }, + investigate: { timeoutMs: INVESTIGATION_TIMEOUT_MS, projectCwd: input.projectCwd }, ...buildReviewGuidePrompt(input), }); }); From 3fb76f1be889c4cbf511e7bb0d0437b0cdea3c83 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:10:00 -0800 Subject: [PATCH 008/277] fix(web): issue links in HTML renders open in the issue panel (#41945) --- .../threads/HtmlRenderWebView.test.tsx | 61 +++++++++++++++++++ .../features/threads/HtmlRenderWebView.tsx | 5 +- apps/mobile/src/lib/openExternalUrl.ts | 1 - apps/mobile/vite.config.ts | 1 + .../BrowserDocumentFrame.browser.test.tsx | 37 +++++++++++ .../components/files/BrowserDocumentFrame.tsx | 15 +++-- 6 files changed, 111 insertions(+), 9 deletions(-) create mode 100644 apps/mobile/src/features/threads/HtmlRenderWebView.test.tsx diff --git a/apps/mobile/src/features/threads/HtmlRenderWebView.test.tsx b/apps/mobile/src/features/threads/HtmlRenderWebView.test.tsx new file mode 100644 index 0000000000000..018f3e27ebf6a --- /dev/null +++ b/apps/mobile/src/features/threads/HtmlRenderWebView.test.tsx @@ -0,0 +1,61 @@ +import type { ReactNode } from "react"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +const harness = vi.hoisted(() => ({ + openedLinks: [] as string[], + openWindow: null as ((event: { nativeEvent: { targetUrl: string } }) => void) | null, +})); + +type Children = { children?: ReactNode }; + +vi.mock("react-native", () => ({ + Platform: { OS: "ios" }, + View: ({ children }: Children) =>
{children}
, + Pressable: ({ children }: Children) =>
{children}
, +})); +vi.mock("react-native-webview", () => ({ + WebView: (props: { onOpenWindow: typeof harness.openWindow }) => { + harness.openWindow = props.onOpenWindow; + return null; + }, +})); +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); +vi.mock("../../components/ui/AppSymbol", () => ({ SymbolView: () => null })); +vi.mock("../../components/ui/AppText", () => ({ + AppText: ({ children }: Children) => {children}, +})); +vi.mock("../../lib/htmlRenderTheme", () => ({ + mobileHtmlRenderTheme: () => ({ variables: {} }), +})); +vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({ + useAppearancePreferences: () => ({}), +})); +vi.mock("../../state/assets", () => ({ + useAssetUrlState: () => ({ _tag: "Initial" }), + useRefreshAssetUrl: () => async () => null, +})); +vi.mock("../../native/useOpenPullRequest", () => ({ + useOpenPullRequest: () => async (url: string) => { + harness.openedLinks.push(url); + return true; + }, +})); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({}) })); + +import { HtmlRenderWebView } from "./HtmlRenderWebView"; + +it("opens a render's issue link the way the thread's own links open", async () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + await act(async () => + root.render(), + ); + + const issueUrl = "https://github.com/pingdotgg/t3code/issues/41939"; + await act(async () => harness.openWindow?.({ nativeEvent: { targetUrl: issueUrl } })); + + expect(harness.openedLinks).toEqual([issueUrl]); + await act(async () => root.unmount()); +}); diff --git a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx index d756e3f3e7918..8f3c76eb507a1 100644 --- a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx +++ b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx @@ -17,7 +17,7 @@ import { WebView, type WebViewMessageEvent } from "react-native-webview"; import { SymbolView } from "../../components/ui/AppSymbol"; import { AppText as Text } from "../../components/ui/AppText"; import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme"; -import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; +import { useOpenPullRequest } from "../../native/useOpenPullRequest"; import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; @@ -83,6 +83,7 @@ export function HtmlRenderWebView(props: { readonly onLoadError?: () => void; }) { const theme = useHtmlRenderTheme(); + const openLink = useOpenPullRequest(); const [initialTheme] = useState(theme); const [generation, setGeneration] = useState(0); const [loaded, setLoaded] = useState(false); @@ -144,7 +145,7 @@ export function HtmlRenderWebView(props: { } onOpenWindow={(event) => { const url = event.nativeEvent.targetUrl; - if (/^https?:/i.test(url)) void tryOpenExternalUrl(url, "html-render"); + if (/^https?:/i.test(url)) void openLink(url); }} onLoadEnd={() => { setLoaded(true); diff --git a/apps/mobile/src/lib/openExternalUrl.ts b/apps/mobile/src/lib/openExternalUrl.ts index d57442ac78045..2821d6bb78f96 100644 --- a/apps/mobile/src/lib/openExternalUrl.ts +++ b/apps/mobile/src/lib/openExternalUrl.ts @@ -6,7 +6,6 @@ const ExternalUrlTarget = Schema.Literals([ "markdown-link", "pull-request", "provider-auth", - "html-render", "mcp-app", "secret-request", "external-link", diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 584ac4ae67968..4be0dbea1bda7 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -40,6 +40,7 @@ const reactTests = [ "src/components/ui/FilePreviewSession.test.tsx", "src/features/threads/UsageLimitRecoveryCard.test.tsx", "src/features/threads/PendingUserInputCard.test.tsx", + "src/features/threads/HtmlRenderWebView.test.tsx", "src/features/threads/NewTaskDraftRouteScreen.test.tsx", "src/native/NativeHeaderToolbar.test.tsx", "src/components/ComposerEditor.ios.test.tsx", diff --git a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx index 34b450dbce87f..c03b143949931 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.browser.test.tsx @@ -3,6 +3,8 @@ import { injectHtmlRenderBootstrap, readFilePreviewScroll, } from "@t3tools/shared/htmlRender"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { describe, expect, it, vi } from "vite-plus/test"; import { page } from "vite-plus/test/browser"; @@ -11,6 +13,17 @@ import { render } from "../../../test/render"; import { BrowserDocumentFrame, HtmlRenderDocument } from "./BrowserDocumentFrame"; +const links = vi.hoisted(() => ({ + openLink: vi.fn(async () => undefined), + openChangeRequestLink: vi.fn(() => false), + openIssueLink: vi.fn(() => true), +})); +vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => links.openLink })); +vi.mock("~/lib/openPullRequestLink", () => ({ + useOpenChangeRequestLink: () => links.openChangeRequestLink, +})); +vi.mock("~/lib/openIssueLink", () => ({ useOpenIssueLink: () => links.openIssueLink })); + const sizeChanged = (height: number) => ({ jsonrpc: "2.0", method: "ui/notifications/size-changed", @@ -61,6 +74,30 @@ describe("HtmlRenderDocument", () => { await expect.element(viewer.getByRole("button", { name: "Next media" })).toBeVisible(); await expect.element(viewer.getByRole("button", { name: "Previous media" })).toBeVisible(); }); + + it("opens a clicked issue link beside the thread, as chat Markdown does", async () => { + const issueUrl = "https://github.com/pingdotgg/t3code/issues/41939"; + const html = injectHtmlRenderBootstrap( + `Issue #41939`, + ); + const src = URL.createObjectURL(new Blob([html], { type: "text/html" })); + using _url = { [Symbol.dispose]: () => URL.revokeObjectURL(src) }; + const threadRef = scopeThreadRef(EnvironmentId.make("local"), ThreadId.make("thread")); + await using screen = await render( + , + ); + + await page.frameLocator(screen.getByTitle("Links")).getByRole("link").click(); + + // The frame tries the pull request handler first, then settles the click in the same call. + await vi.waitFor(() => expect(links.openChangeRequestLink).toHaveBeenCalled()); + expect(links.openLink).not.toHaveBeenCalled(); + expect(links.openIssueLink).toHaveBeenCalledWith( + expect.anything(), + issueUrl, + threadRef.environmentId, + ); + }); }); it("keeps the chat in place when a label far from its hidden radio is clicked", async () => { diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsx index 3270556fb0ff4..af079bab7c441 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx @@ -46,6 +46,7 @@ import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog"; import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview"; import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme"; import { shortcutConflictKey } from "~/keybindings"; +import { useOpenIssueLink } from "~/lib/openIssueLink"; import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink"; import { readLocalApi } from "~/localApi"; import { cn } from "~/lib/utils"; @@ -375,6 +376,7 @@ export function HtmlRenderDocument(props: { }, ); const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef); + const openIssueLink = useOpenIssueLink(props.threadRef); const openLink = useOpenLink(props.threadRef); const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => { if (modifiers.metaKey || modifiers.ctrlKey) { @@ -383,14 +385,15 @@ export function HtmlRenderDocument(props: { .catch((cause: unknown) => console.error(cause)); return; } + const event = { + ...modifiers, + preventDefault: () => undefined, + stopPropagation: () => undefined, + }; if ( props.threadRef !== undefined && - openChangeRequestLink( - { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined }, - url, - undefined, - props.threadRef.environmentId, - ) + (openChangeRequestLink(event, url, undefined, props.threadRef.environmentId) || + openIssueLink(event, url, props.threadRef.environmentId)) ) { return; } From 2b2da5e7f9b8b9eab397621f70b1b87881a529ef Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:10:09 -0800 Subject: [PATCH 009/277] docs(security): clarify intended behaviour and triage steps (#41942) --- SECURITY.md | 150 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 102 insertions(+), 48 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 156e7292e3da2..9c63913169305 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -4,46 +4,46 @@ Report vulnerabilities to [security@t3.codes](mailto:security@t3.codes). The [security policy](.github/SECURITY.md) covers disclosure and safe harbor. The rest of this file is for agents and maintainers auditing T3 Code or triaging -a report. It says who is trusted with what, which boundaries a real finding +reports. It defines who is trusted with what, which boundaries a real finding crosses, and what is intended. The reasoning behind each boundary lives in [environment auth](docs/internals/04_environment-auth.md), [T3 Connect](docs/internals/06_t3-connect.md), and -[remote environments](docs/internals/05_remote.md). Read those before you report a -finding in their area. +[remote environments](docs/internals/05_remote.md); read those before reporting +in their area. ## The model in one paragraph An environment is a T3 server running as an OS user. It is not a sandbox: it -runs agents and terminals with that user's privileges, on purpose. Clients get -authority by pairing, which issues a scoped session. A full-scope session is -equivalent to a shell as the server's user, because `terminal:operate` opens a -PTY and `orchestration:operate` can start a full-access agent. Security work -here is about who can get a session, what each kind of session can reach, and -whether revocation and ceilings hold. It is not about what a full session can do -once it has one. +intentionally runs agents and terminals with that user's privileges. Clients +gain authority by pairing, which issues a scoped session. A full-scope session +equals a shell as the server's OS user, because `terminal:operate` opens a PTY +and `orchestration:operate` can start a full-access agent. Security here is +about who can obtain a session, what each session type can reach, and whether +revocation and ceilings hold, not what a full-scope session can do once issued. ## Principals -| Principal | How it gets in | What it may do | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Anyone who reaches the port | Network | Read the environment descriptor, pair with a valid one-time credential, run OAuth flows. Nothing else. | -| Full-scope client (desktop, paired browser or phone, `t3 auth session issue`, T3 Connect device) | Pairing, token exchange, Connect mint | Everything the server's OS user can do. This is the default grant. | -| Narrow client | Pairing link with explicit scopes | Only the RPCs and routes its scopes allow. Can never widen its own grant. | -| MCP client (outside agent, subject `mcp-client`) | OAuth on `/mcp` | Only `/mcp`, within a read-only grant or a runtime-mode ceiling. Every other route rejects it. | -| Linked environment (peer link) | OAuth client `t3code-peer-link` | Work it starts carries an immutable `linkOrigin` and never exceeds the access it was paired with. | -| Agent run by T3 | Thread's runtime mode and thread credential | Within its runtime mode, managed policy, and the MCP access declared per tool. | -| Guest link | HMAC token for one share | Read one thread and propose messages. Never a session; no RPC, WebSocket, or MCP path accepts it. | -| Signed asset URL | Minted with `filesystem:read` | One file, by device and inode identity, until it expires. | -| T3 Connect relay | Environment link | Trusted broker for mint requests. It never sees environment session tokens. With `requireConnectDeviceApproval` on, a new device key also needs approval from someone with `access:write`. | -| Managed policy | Admin-deployed file, read at startup | Ceilings and locks the server enforces for every client. | -| Preview pages, HTML renders, file previews, agent output | Rendered by clients | Untrusted content. It must never run script in the app's origin or reach Electron IPC or Node. | +| Principal | How it gets in | What it may do | +| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Anyone who reaches the port | Network | Read the environment descriptor, pair with a valid one-time credential, run OAuth flows. Nothing else. | +| Full-scope client (desktop, paired browser or phone, `t3 auth session issue`, T3 Connect device) | Pairing, token exchange, Connect mint | Everything the server's OS user can do. This is the default grant. | +| Narrow client | Pairing link with explicit scopes | Only the RPCs and routes its scopes allow. Can never widen its own grant. | +| MCP client (outside agent, subject `mcp-client`) | OAuth on `/mcp` | Only `/mcp`, within a read-only grant or a runtime-mode ceiling. Every other route rejects it. | +| Linked environment (peer link) | OAuth client `t3code-peer-link` | Work it starts carries an immutable `linkOrigin` and never exceeds the access it was paired with. | +| Agent run by T3 | Thread's runtime mode and thread credential | Within its runtime mode, managed policy, and the MCP access declared per tool. | +| Guest link | HMAC token for one share | Read one thread and propose messages. Never a session; no RPC, WebSocket, or MCP path accepts it. | +| Signed asset URL | Minted with `filesystem:read` | One file, by device and inode identity, until it expires. | +| Webhook sender | A task's webhook URL, plus its signing secret when the task requires one | Start that one task's run with content of its choosing. Nothing in the request is trusted beyond the signature check. | +| T3 Connect relay | Environment link | Trusted broker for mint requests. It never sees environment session tokens. With `requireConnectDeviceApproval` on, a new device key also needs approval from someone with `access:write`. | +| Managed policy | Admin-deployed file, read at startup | Ceilings and locks the server enforces for every client. | +| Preview pages, HTML renders, file previews, agent output | Rendered by clients | Untrusted content. It must never run script in the app's origin or reach Electron IPC or Node. | ## A real finding crosses one of these -1. **No credential → session.** Any route or socket that grants access without - a valid credential, or a pairing credential that can be redeemed twice. -2. **Scope escalation.** An RPC, HTTP route, or MCP tool that runs without the - scope it declares; pairing or token exchange that widens a grant; an +1. **No credential → session.** Any route or socket granting access without + a valid credential, or a pairing credential redeemable twice. +2. **Scope escalation.** An RPC, HTTP route, or MCP tool running without its + declared scope; pairing or token exchange widening a grant; an `mcp-client` session reaching a non-`/mcp` route; a read-only MCP grant calling a write tool. 3. **Mode or policy escalation.** An agent, MCP client, or peer link acting @@ -52,43 +52,77 @@ once it has one. 4. **Guest escape.** A guest token reading another thread, acting beyond proposing messages, or surviving a closed or replaced share. 5. **Revocation that doesn't take effect.** A revoked session, device key, - pairing link, or peer link that still works. The exception is documented: - signed asset URLs last until they expire. + pairing link, or peer link that still works. Documented exception: signed + asset URLs last until they expire. 6. **Credential exposure.** Tokens or secrets reaching logs, traces, telemetry, the relay, socket URLs (outside short-lived tickets), the access read model, or error messages. A token sent to an address that has not answered as the - expected environment. A token paired over HTTPS starting to travel over plain - HTTP. + expected environment, or a token paired over HTTPS sent over plain HTTP. 7. **Impersonation and egress.** Another process or the relay impersonating an - environment, or endpoint discovery, previews, or webhooks used to reach + environment; endpoint discovery, previews, or webhooks used to reach arbitrary hosts (SSRF). 8. **Client-side code execution.** Untrusted content running script in the web origin, the desktop renderer, or with access to preload or IPC. -9. **Filesystem writes escaping workspace path rules.** Reads are another - matter: `filesystem:read` is intentionally the whole account. +9. **Filesystem writes escaping workspace path rules.** Reads are separate: + `filesystem:read` intentionally covers the whole OS account. ## Intended, not vulnerabilities -- A full-scope token gives a shell. Leaking one is serious, but the bug is the - leak, not the shell. -- The default grant includes `access:write`, so a full session can mint more - pairing links and sessions. They appear in Sharing & access, and "revoke all - others" removes them. -- `filesystem:read` reads anything the server's user can read, including paths - outside projects. -- Plain HTTP on a LAN or tailnet is the user's choice. `t3 serve` warns when it - advertises a non-loopback HTTP address. The iOS app allows arbitrary loads so +- A full-scope session gives a shell. Leaking its token is serious, but the bug + is the leak, not the shell. The same applies to a narrow session holding + `terminal:operate` or `orchestration:operate`: reaching via another route + what its shell can already do crosses no boundary, though it can still be an + ordinary bug. That stops at what a shell as the server's OS user cannot reach: + another client's device, what another scope guards by name (as + `providers:manage` does for secret references), a managed-policy ceiling or + lock, and access that outlives the session's revocation. Where the session + can obtain that shell, file contents are within its reach, so reading a file + via a route that does not check `filesystem:read` crosses no boundary. +- The default grant includes `access:write`, so a full-scope session can mint + more pairing links and sessions. They appear in Sharing & access, and "revoke + all others" removes them. +- `filesystem:read` reads anything the server's OS user can read, including + paths outside projects. +- Plain HTTP on a LAN or tailnet is the user's choice. `t3 serve` warns when + advertising a non-loopback HTTP address. The iOS app allows arbitrary loads so it can reach these addresses. - `access-control-allow-origin: *` on the environment API. Auth is a bearer header, so the wildcard grants nothing a caller without a token lacks. -- An agent in full-access mode can do whatever the user can. Prompt injection - that stays within the agent's mode is the provider's concern. One that lets - it act above that mode is in scope (see 3). +- Rendered Markdown loads remote images and media from the host its author + names, so that host learns the reader's network address and when the content + was shown. A page in a preview tab can likewise start a download, as it can + in a browser. It is a finding when the request carries a credential or names + the environment it was rendered in, when it is made where the product says + none is made, or when the app does for the content what the content could + not do from where it runs (see 7 and 8). +- A full-access agent can do whatever the user can. Prompt injection that stays + within the agent's mode is the provider's concern; one that lets it act above + that mode is in scope (see 3). - A compromised relay signing key can mint for linked environments. That is the stated trust assumption; device approval is the mitigation. - `T3CODE_DEV_AUTH_TOKEN` and dev startup URLs are administrative by design and ignored outside development servers. -- An attacker already running code as the same OS user. +- A webhook URL is a credential for one task. Unless the task requires a + signature, whoever holds the URL can start that task's run, and the request's + content, within the route's limits, is theirs to choose. It is a finding when + a request starts a different task, runs without a signature the task + requires, or has its values treated as anything but untrusted data. Tokens in + or around the request remain covered by 6. +- The machine owner's own configuration. Whoever sets a provider's launch + arguments, an environment variable, a binary path, or the endpoint or file T3 + Code points at already holds the OS account, so a value weakening their own + setup is their choice. It is a finding when a narrower principal can set it + for them (a narrow client, an MCP client, an agent below full access, + repository content), when [managed policy](docs/user/managed-policy.md) locks + the setting and the value still applies, or when the value leaks (see 6). + Choosing a host does not make it trusted: what a configured endpoint can do + to the server or its clients stays in scope. +- An attacker already running code as the same OS user. That includes one whose + only move is to rewrite files that user owns outside a workspace: T3 Code's + data directory, its installed helpers, the user's own config. Another OS + account on the same machine is not this attacker; neither is repository + content or an agent below full access, which write inside a workspace without + holding the OS account. ## Where enforcement lives @@ -106,10 +140,30 @@ once it has one. - Name the precondition first. If a chain starts with "the attacker holds a full-scope token", it is a new vulnerability only if it widens that token's reach (2–3), outlives revocation (5), or shows how the token leaks (6). +- Name the actor next and what they can already do. If the only actor is the + user on their own device, or a principal reaching the same outcome via a + documented route, no boundary is crossed unless data goes somewhere they did + not send it. It may still be a bug; report it as one. +- Read tests and comments beside the code before calling a behaviour a defect. + They show author intent and are evidence, not a decision: a test can pin a + behaviour nobody chose, and a comment can be stale. Only this file and the + docs say what is intended. If only a test or comment supports a behaviour, + report it and say so. +- Follow the claim to its effect. A guard in a caller, a schema, or a version + check elsewhere often means the cited lines cannot do what the report says. +- Rate severity by what the actor must already hold, not the worst outcome + named. Each of these lowers severity and none removes the finding: a narrow + grant the owner chose to issue (the default grant is full scope); another OS + account on the same machine; a host or service the owner connected turning + hostile; a change that must land in the moment between a person's look and + their action; a person acting on prepared input (opening a file, pasting, + following a link); and an effect limited to resource use or a stalled + client. A finding that needs none of these, or that yields a session, a + credential, or code execution above the actor's grant, keeps its severity. - Check the reported commit against `main`. Reports often trail fixes. - Prove a finding with a failing test at the lowest layer that shows it, as [Verifying](AGENTS.md#verifying) describes. Do not run a PoC against - `~/.t3/userdata` or any live environment. Use a dev server on seeded data. + `~/.t3/userdata` or any live environment; use a dev server on seeded data. - Treat report attachments as untrusted. Extract them into an empty directory outside the worktree and read PoCs before running anything. - Fix confirmed findings rather than filing them. Keep advisory details out of From bc138a77d1a2ec5f8c13400a011a1af63a6c5fd1 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:12:45 -0800 Subject: [PATCH 010/277] fix(mobile): a local preview link opens only http and https addresses (#41974) Co-authored-by: Claude Fable 5.2 --- .../browser/LocalPreviewRouteScreen.test.tsx | 58 +++++++++++++++++++ .../browser/LocalPreviewRouteScreen.tsx | 6 +- .../src/features/browser/browserTabs.test.ts | 13 ++++- .../src/features/browser/browserTabs.ts | 12 ++++ apps/mobile/vite.config.ts | 1 + 5 files changed, 86 insertions(+), 4 deletions(-) create mode 100644 apps/mobile/src/features/browser/LocalPreviewRouteScreen.test.tsx diff --git a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.test.tsx b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.test.tsx new file mode 100644 index 0000000000000..e44b2dffa3a91 --- /dev/null +++ b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.test.tsx @@ -0,0 +1,58 @@ +import type { ReactNode } from "react"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { expect, it, vi } from "vite-plus/test"; + +const { Children, loaded } = vi.hoisted(() => ({ + Children: ({ children }: { children?: ReactNode }) => <>{children}, + loaded: [] as string[], +})); + +vi.mock("react-native", () => ({ View: Children })); +vi.mock("react-native-safe-area-context", () => ({ SafeAreaView: Children })); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ goBack: vi.fn() }) })); +vi.mock("../../components/ui/AppText", () => ({ AppText: Children })); +vi.mock("../../components/ui/Dialog", () => ({ alert: vi.fn() })); +vi.mock("../../components/ui/EmptyState", () => ({ EmptyState: () => null })); +vi.mock("../../state/entities", () => ({ useEnvironmentPreviewTunnelOff: () => false })); +vi.mock("../../state/environments", () => ({ + useEnvironments: () => ({ presentationById: new Map() }), +})); +vi.mock("../settings/appearance/AppearancePreferencesProvider", () => ({ + useAppearancePreferences: () => ({ themeVariables: {} }), +})); +vi.mock("./BrowserBar", () => ({ + BrowserChrome: (props: { + children: (page: { topInset: number; onScrollDirection: () => void }) => ReactNode; + }) => <>{props.children({ topInset: 0, onScrollDirection: () => {} })}, +})); +vi.mock("./TunnelWebView", () => ({ + TunnelWebView: ({ url }: { url: string }) => { + loaded.push(url); + return null; + }, +})); + +import { LocalPreviewRouteScreen } from "./LocalPreviewRouteScreen"; + +it("gives the webview only web addresses from the route, on open and on a later link", () => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + const root = createRoot(document.createElement("div")); + const show = (url: string) => { + loaded.length = 0; + act(() => + root.render(), + ); + return loaded.at(-1); + }; + + try { + expect(show("http://0.0.0.0:5173/app")).toBe("http://localhost:5173/app"); + expect(show("javascript:document.title='x'")).toBe(""); + expect(show("https://example.com/docs")).toBe("https://example.com/docs"); + expect(show("file:///data/local/tmp/a.html")).toBe(""); + expect(show("intent://example.com#Intent;scheme=http;end")).toBe(""); + } finally { + act(() => root.unmount()); + } +}); diff --git a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx index 8cfd22142698a..91fdc8e644e02 100644 --- a/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx +++ b/apps/mobile/src/features/browser/LocalPreviewRouteScreen.tsx @@ -14,7 +14,7 @@ import { useEnvironmentPreviewTunnelOff } from "../../state/entities"; import { useEnvironments } from "../../state/environments"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; import { BrowserChrome } from "./BrowserBar"; -import { loopbackUrlForDevice } from "./browserTabs"; +import { localPreviewUrlForDevice } from "./browserTabs"; import { TunnelWebView, type TunnelNavigation, type TunnelWebViewRef } from "./TunnelWebView"; type LocalPreviewRouteScreenProps = StaticScreenProps<{ @@ -231,9 +231,9 @@ function hostOf(value: string): string { } } -// The unspecified address would name the phone itself, so it becomes the environment's localhost. +// A route URL that is not a web address opens the preview empty, ready for one to be typed. function forDevice(url: string): string { - return loopbackUrlForDevice(url) ?? url; + return localPreviewUrlForDevice(url) ?? ""; } function normalizedOrNull(value: string): string | null { diff --git a/apps/mobile/src/features/browser/browserTabs.test.ts b/apps/mobile/src/features/browser/browserTabs.test.ts index 394b3fd404fb1..c4e892782f458 100644 --- a/apps/mobile/src/features/browser/browserTabs.test.ts +++ b/apps/mobile/src/features/browser/browserTabs.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vite-plus/test"; -import { loopbackUrlForDevice } from "./browserTabs"; +import { localPreviewUrlForDevice, loopbackUrlForDevice } from "./browserTabs"; describe("loopbackUrlForDevice", () => { it("opens only the environment's loopback pages on this device", () => { @@ -18,3 +18,14 @@ describe("loopbackUrlForDevice", () => { expect(loopbackUrlForDevice("")).toBeNull(); }); }); + +describe("localPreviewUrlForDevice", () => { + it("loads http and https addresses and nothing else", () => { + expect(localPreviewUrlForDevice("http://0.0.0.0:3000/")).toBe("http://localhost:3000/"); + expect(localPreviewUrlForDevice("https://example.com/docs")).toBe("https://example.com/docs"); + expect(localPreviewUrlForDevice(" JavaScript:void(0)")).toBeNull(); + expect(localPreviewUrlForDevice("file:///tmp/a.html")).toBeNull(); + expect(localPreviewUrlForDevice("data:text/html,hello")).toBeNull(); + expect(localPreviewUrlForDevice("")).toBeNull(); + }); +}); diff --git a/apps/mobile/src/features/browser/browserTabs.ts b/apps/mobile/src/features/browser/browserTabs.ts index 294d67ca8ce09..b27cd442c4f92 100644 --- a/apps/mobile/src/features/browser/browserTabs.ts +++ b/apps/mobile/src/features/browser/browserTabs.ts @@ -38,3 +38,15 @@ export function loopbackUrlForDevice(value: string): string | null { return null; } } + +/** The address a local preview loads for `value`: an http(s) URL, or null when it is anything else. */ +export function localPreviewUrlForDevice(value: string): string | null { + const loopback = loopbackUrlForDevice(value); + if (loopback !== null) return loopback; + try { + const url = new URL(value); + return /^https?:$/.test(url.protocol) ? url.toString() : null; + } catch { + return null; + } +} diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.ts index 4be0dbea1bda7..792c881c76b8a 100644 --- a/apps/mobile/vite.config.ts +++ b/apps/mobile/vite.config.ts @@ -4,6 +4,7 @@ import { defineConfig, normalizePath } from "vite-plus"; import "vite-plus/test/config"; const reactTests = [ + "src/features/browser/LocalPreviewRouteScreen.test.tsx", "src/features/threads/LinkedThreadSheet.test.tsx", "src/features/threads/ThreadGuestShareSheet.test.tsx", "src/features/threads/useSubmitAfterNativeImages.test.tsx", From 97b8c9c7c2be371dfdda55c3fbfac44118ec8d65 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:14:30 -0800 Subject: [PATCH 011/277] fix(mobile): a typed pairing code goes to the address shown in the form (#41975) Co-authored-by: Claude Fable 5.2 --- .../src/features/connection/pairing.test.ts | 15 +++++++++++++++ apps/mobile/src/features/connection/pairing.ts | 2 ++ 2 files changed, 17 insertions(+) diff --git a/apps/mobile/src/features/connection/pairing.test.ts b/apps/mobile/src/features/connection/pairing.test.ts index 466fbfa7a282d..a3f2fab4861f5 100644 --- a/apps/mobile/src/features/connection/pairing.test.ts +++ b/apps/mobile/src/features/connection/pairing.test.ts @@ -1,3 +1,4 @@ +import { resolveRemotePairingTarget } from "@t3tools/shared/remote"; import { describe, expect, it } from "vite-plus/test"; import { buildPairingUrl, extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing"; @@ -20,6 +21,20 @@ describe("buildPairingUrl", () => { "https://192.168.1.100:3773/#token=pairing-token", ); }); + + it("pairs with the address's own origin when the address carries a query", () => { + const pairingUrl = buildPairingUrl( + "https://remote.example.com/?host=https%3A%2F%2Fother.example.com", + "pairing-token", + ); + + expect(pairingUrl).toBe("https://remote.example.com/#token=pairing-token"); + expect(resolveRemotePairingTarget({ pairingUrl })).toEqual({ + credential: "pairing-token", + httpBaseUrl: "https://remote.example.com/", + wsBaseUrl: "wss://remote.example.com/", + }); + }); }); describe("extractPairingUrlFromQrPayload", () => { diff --git a/apps/mobile/src/features/connection/pairing.ts b/apps/mobile/src/features/connection/pairing.ts index d596343d3f90e..2d9b129a0fc13 100644 --- a/apps/mobile/src/features/connection/pairing.ts +++ b/apps/mobile/src/features/connection/pairing.ts @@ -38,6 +38,8 @@ export function buildPairingUrl(host: string, code: string): string { try { const url = new URL(h.includes("://") ? h : `${isIpLiteral(h) ? "http" : "https"}://${h}`); + // The code goes to the address shown, so a query cannot name another destination. + url.search = ""; url.hash = new URLSearchParams([["token", c]]).toString(); return url.toString(); } catch { From f89883c56885776261434d546cb79075d8280d90 Mon Sep 17 00:00:00 2001 From: Noah Sigel <30538387+nsigel@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:14:58 -0800 Subject: [PATCH 012/277] fix(web): a long commit name no longer runs under the PR code tab's icons (#39875) Co-authored-by: Julius Marminge --- apps/web/src/components/pullRequest/PullRequestCodeTab.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index d06cb1efeaacd..159a05509fe10 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -1413,12 +1413,12 @@ function PullRequestCodeTab({ }; const toolbar = (
-
+
{orderedCommits.length > 0 ? ( } - className="min-w-0 max-w-64" + className="min-w-0 max-w-64 shrink-[999]" aria-label={gt("Diff scope: {scope}", { scope: scopeLabel })} > {scopeLabel} From d00aaac85fc71195f133a8580c3f0f2e29ac33a2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:15:19 -0800 Subject: [PATCH 013/277] fix(antigravity): a tool's own arguments no longer mark it as a T3 MCP call (#41978) Co-authored-by: Claude Fable 5.2 --- .../provider/acp/AntigravityAcpSupport.test.ts | 8 ++++++++ .../src/provider/acp/AntigravityAcpSupport.ts | 16 +++++++++++----- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index a68c1334c473f..ebb984b5a4fb4 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -169,6 +169,14 @@ describe("Antigravity Auto", () => { request("Run mcp_t3-code_preview_status", { CommandLine: "Run mcp_t3-code_preview_status", }), + // A directly called tool's rawInput is its own arguments, whatever their names. + request("Run mcp_github_create_issue", { + ServerName: "t3-code", + ToolName: "delegate_task", + }), + request("Running create_issue", { ServerName: "t3-code", ToolName: "delegate_task" }), + // call_mcp_tool is titled for the tool it calls. + request("MCP Tool create_issue", { ServerName: "t3-code", ToolName: "delegate_task" }), ]) { expect(antigravityPermissionDisposition(policy, otherCall)).toBe("ask"); } diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index f16c143cc278c..31439ea03277f 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -187,17 +187,23 @@ export function antigravitySessionMode( // MCP server's tool of the same name would pass. const ANTIGRAVITY_T3_MCP_TITLE = /^Run mcp_t3-code_(?[A-Za-z0-9_]+)\??$/; +// call_mcp_tool is the one call whose rawInput names a server and tool; in every other call +// rawInput is the tool's own arguments. +const ANTIGRAVITY_PROXIED_MCP_TITLE = /^MCP Tool (?[A-Za-z0-9_]+)\??$/; + function isAntigravityT3McpRequest(request: EffectAcpSchema.RequestPermissionRequest): boolean { + const title = request.toolCall.title?.trim() ?? ""; const rawInput = unknownRecord(request.toolCall.rawInput); - if (rawInput?.ServerName !== undefined) { + const proxiedTool = ANTIGRAVITY_PROXIED_MCP_TITLE.exec(title)?.groups?.tool; + if (proxiedTool !== undefined) { return ( - rawInput.ServerName === "t3-code" && - typeof rawInput.ToolName === "string" && - T3_MCP_TOOL_NAMES.has(rawInput.ToolName) + rawInput?.ServerName === "t3-code" && + rawInput.ToolName === proxiedTool && + T3_MCP_TOOL_NAMES.has(proxiedTool) ); } if (typeof rawInput?.CommandLine === "string") return false; - const tool = ANTIGRAVITY_T3_MCP_TITLE.exec(request.toolCall.title?.trim() ?? "")?.groups?.tool; + const tool = ANTIGRAVITY_T3_MCP_TITLE.exec(title)?.groups?.tool; return tool !== undefined && T3_MCP_TOOL_NAMES.has(tool); } From bba3918e3c0cf4c32ea855e6510864dcc145fc02 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:18:46 -0800 Subject: [PATCH 014/277] fix(server): saving project scripts requires task operation scope (#41979) Co-authored-by: Claude Fable 5.2 --- apps/server/src/auth/RpcAuthorization.test.ts | 60 +++++++++++++++++++ docs/internals/04_environment-auth.md | 3 + packages/contracts/src/settings.ts | 19 +++++- 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/apps/server/src/auth/RpcAuthorization.test.ts b/apps/server/src/auth/RpcAuthorization.test.ts index 1aa2a5b182ffa..2319216f64d60 100644 --- a/apps/server/src/auth/RpcAuthorization.test.ts +++ b/apps/server/src/auth/RpcAuthorization.test.ts @@ -608,6 +608,66 @@ describe("settings mutation authorization", () => { }), ); + it.effect("saving project scripts needs task operation as well as the settings grant", () => + Effect.gen(function* () { + const projectId = ProjectId.make("project-1"); + const scripts = [ + { + id: "setup", + name: "Setup", + command: "pnpm install", + icon: "play" as const, + runOnWorktreeCreate: true, + }, + ]; + const update = (scopes: Parameters[0]) => { + let handled = 0; + return RpcTest.makeClient(group).pipe( + Effect.provide( + Layer.mergeAll( + group.toLayerHandler(WS_METHODS.serverUpdateSettings, () => + Effect.sync(() => { + handled++; + return DEFAULT_SERVER_SETTINGS; + }), + ), + RpcAuthorization.layer(scopes), + ), + ), + Effect.map((client) => ({ client, handled: () => handled })), + ); + }; + const patches = [ + { defaultProjectScripts: scripts }, + { projectScriptOverrides: { [projectId]: scripts } }, + { projectSettingsOverrides: { [projectId]: { defaultProjectScripts: scripts } } }, + ]; + + const settingsOnly = yield* update([AuthSettingsWriteScope]); + for (const patch of patches) { + expect( + yield* settingsOnly.client[WS_METHODS.serverUpdateSettings]({ patch }).pipe(Effect.flip), + ).toMatchObject({ requiredPermission: AuthOrchestrationOperateScope }); + } + expect(settingsOnly.handled()).toBe(0); + // Settings that carry no script stay with the settings grant alone. + yield* settingsOnly.client[WS_METHODS.serverUpdateSettings]({ + patch: { + defaultAutoPull: true, + projectScriptOverrides: { [projectId]: null }, + projectSettingsOverrides: { [projectId]: { defaultAutoPull: true } }, + }, + }); + expect(settingsOnly.handled()).toBe(1); + + const operator = yield* update([AuthSettingsWriteScope, AuthOrchestrationOperateScope]); + for (const patch of patches) { + yield* operator.client[WS_METHODS.serverUpdateSettings]({ patch }); + } + expect(operator.handled()).toBe(patches.length); + }), + ); + it.effect("does not let a settings grant send a named secret to a gateway it picks", () => Effect.gen(function* () { const group = WsRpcGroup.omit( diff --git a/docs/internals/04_environment-auth.md b/docs/internals/04_environment-auth.md index 1b22ab16e4d6d..cc67e5522de1a 100644 --- a/docs/internals/04_environment-auth.md +++ b/docs/internals/04_environment-auth.md @@ -33,6 +33,9 @@ model. read needs `providers:manage` on top of its method's scope, whether the reference is saved in settings or used once, as in a secret request answered with a reference. Typed values need only the method's scope. Clients hide the secret provider picker from sessions without it. +- **Project scripts need `orchestration:operate`.** The host runs a saved project script itself, + on worktree creation and on settle, so saving one needs `orchestration:operate` on top of + `settings:write`, whether it arrives in a settings patch or a project update. - **Backward-compatible scope evolution.** Token exchange intersects requested scopes with the pairing grant, dropping retired/unknown names and failing before consuming a link if none remain. Stored grants are never expanded when scopes split. Auth responses preserve legacy `scopes` diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 5b6ce48c88833..a99be293c2121 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -2029,6 +2029,17 @@ export const ClientServerSettingsPatch = ServerSettingsPatch.mapFields( Struct.omit(["defaultTheme", "defaultThemeSetAt", "defaultAppearance", "defaultAppearanceSetAt"]), ); +/** The host runs saved project scripts, some without anyone asking: on worktree creation and on settle. */ +function carriesProjectScripts(patch: ServerSettingsPatch): boolean { + return ( + patch.defaultProjectScripts !== undefined || + Object.values(patch.projectScriptOverrides ?? {}).some((scripts) => scripts !== null) || + Object.values(patch.projectSettingsOverrides ?? {}).some( + (overrides) => overrides?.defaultProjectScripts !== undefined, + ) + ); +} + export function requiredScopesForServerSettingsPatch( patch: ServerSettingsPatch, ): ReadonlyArray { @@ -2061,6 +2072,8 @@ export function requiredScopesForServerSettingsPatch( ...(changesSettings || (!changesProviders && !changesAccess) ? [AuthSettingsWriteScope] : []), ...(changesProviders ? [AuthProvidersManageScope] : []), ...(changesAccess ? [AuthAccessWriteScope] : []), + // Saving a script is choosing a command for the host to run, wherever the patch carries it. + ...(carriesProjectScripts(patch) ? [AuthOrchestrationOperateScope] : []), ]; } @@ -2072,8 +2085,10 @@ export function requiredScopesForProjectMutation( return [AuthOrchestrationOperateScope]; } return [ - AuthOrchestrationOperateScope, - ...requiredScopesForServerSettingsPatch({ defaultProjectScripts: mutation.scripts }), + ...new Set([ + AuthOrchestrationOperateScope, + ...requiredScopesForServerSettingsPatch({ defaultProjectScripts: mutation.scripts }), + ]), ]; } From f8b3ff0dff491806c3fa95764ee64155d0cc945f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:19:37 -0800 Subject: [PATCH 015/277] fix(source-control): TanStack Source issue requests require a numeric issue key (#41980) Co-authored-by: Claude Fable 5.2 --- .../server/TanStackSourceIssueTracker.test.ts | 30 +++++++++++++++++++ .../src/server/TanStackSourceIssueTracker.ts | 28 +++++++++-------- 2 files changed, 45 insertions(+), 13 deletions(-) diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.test.ts index bed0175c9cc22..09904578cdf75 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.test.ts @@ -189,4 +189,34 @@ describe("TanStackSourceIssueTracker", () => { ]); }); }); + + it.effect("sends nothing for a key that is not an issue number", () => { + const { tracker, paths } = withApi({ "/user": { username: "alice" } }); + return Effect.gen(function* () { + const issues = yield* tracker; + for (const key of ["7/labels", "7/../8", "7?state=open", "0", "x"]) { + const issue = { ...target, key }; + const exits = yield* Effect.forEach( + [ + issues.getIssue(issue), + issues.getComments({ ...issue, cursor: "t2" }), + issues.comment!({ ...issue, body: "Hello." }), + issues.update!({ ...issue, title: "New title", labels: [], assignees: [] }), + issues.setState!({ ...issue, state: "Closed" }), + ], + (effect) => Effect.exit(effect), + ); + assert.deepStrictEqual( + exits.map((exit) => exit._tag), + ["Failure", "Failure", "Failure", "Failure", "Failure"], + key, + ); + } + // Reading an issue asks for the viewer alongside it. + assert.deepStrictEqual( + paths.filter((path) => path !== "/user"), + [], + ); + }); + }); }); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.ts index e436ba54375c1..a404c71d31c52 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceIssueTracker.ts @@ -125,6 +125,12 @@ export const make = Effect.gen(function* () { : Effect.fail(failure(operation, "TanStack Source issues live in owner/name repositories.")); }; + /** The key is checked here because it becomes a path segment of the request. */ + const issuePath = (operation: string, input: IssueScopeTarget & { readonly key: string }) => + /^[1-9]\d*$/u.test(input.key) + ? Effect.map(base(operation, input), (path) => `${path}/issues/${input.key}`) + : Effect.fail(failure(operation, "TanStack Source issue keys are numbers.")); + const send = ( operation: string, input: Pick, @@ -220,10 +226,8 @@ export const make = Effect.gen(function* () { operation: string, input: IssueScopeTarget & { readonly key: string }, ) { - const path = yield* base(operation, input); - if (!/^\d+$/u.test(input.key)) - return yield* failure(operation, "TanStack Source issue keys are numbers."); - return yield* read(operation, input, { path: `${path}/issues/${input.key}` }, IssueDetail); + const path = yield* issuePath(operation, input); + return yield* read(operation, input, { path }, IssueDetail); }); const tracker: IssueTrackerApi = { @@ -314,13 +318,11 @@ export const make = Effect.gen(function* () { }), getComments: Effect.fn("TanStackSourceIssueTracker.getComments")(function* (input) { - const path = yield* base("getComments", input); + const path = yield* issuePath("getComments", input); const detail = yield* read( "getComments", input, - { - path: `${path}/issues/${input.key}?${new URLSearchParams({ cursor: input.cursor })}`, - }, + { path: `${path}?${new URLSearchParams({ cursor: input.cursor })}` }, IssueDetail, ); return { comments: toConversation(detail, input).comments, nextCursor: detail.next }; @@ -359,16 +361,16 @@ export const make = Effect.gen(function* () { }), comment: Effect.fn("TanStackSourceIssueTracker.comment")(function* (input) { - const path = yield* base("comment", input); + const path = yield* issuePath("comment", input); yield* send("comment", input, { method: "POST", - path: `${path}/issues/${input.key}/comments`, + path: `${path}/comments`, body: { body: input.body }, }); }), update: Effect.fn("TanStackSourceIssueTracker.update")(function* (input) { - const path = `${yield* base("update", input)}/issues/${input.key}`; + const path = yield* issuePath("update", input); if (input.title !== undefined || input.body !== undefined) yield* send("update", input, { method: "PATCH", @@ -396,10 +398,10 @@ export const make = Effect.gen(function* () { const state = STATES.find((candidate) => candidate.name === input.state); if (state === undefined) return yield* failure("setState", `TanStack Source issues have no "${input.state}" state.`); - const path = yield* base("setState", input); + const path = yield* issuePath("setState", input); yield* send("setState", input, { method: "PATCH", - path: `${path}/issues/${input.key}`, + path, body: { state: state.category }, }); }), From bb0862ead48b5e44d766eaf62e5b97ed312e60e7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 23 Nov 2026 23:20:31 -0800 Subject: [PATCH 016/277] fix(client): a long run of fence markers is read in one pass (#41983) Co-authored-by: Claude Fable 5.2 --- packages/client-runtime/src/pullRequestMarkdown.test.ts | 1 + packages/client-runtime/src/pullRequestMarkdown.ts | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index a397241775db6..787e6931a9f28 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -193,6 +193,7 @@ describe("pull request body segmentation", () => { it.each([ ["a whitespace run inside a line", `a${" ".repeat(1_000_000)}b`], ["a run of unclosed video tags", `${"