---
apps/mobile/src/features/usage/UsageRouteScreen.tsx | 11 +++++++----
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 +-
apps/web/src/components/usage/UsagePage.tsx | 2 +-
apps/web/src/i18n/translations/de.json | 1 -
apps/web/src/i18n/translations/en.json | 1 -
apps/web/src/i18n/translations/es.json | 1 -
apps/web/src/i18n/translations/fr.json | 1 -
apps/web/src/i18n/translations/ja.json | 1 -
apps/web/src/i18n/translations/ko.json | 1 -
apps/web/src/i18n/translations/pt-BR.json | 1 -
apps/web/src/i18n/translations/ru.json | 1 -
apps/web/src/i18n/translations/sv.json | 1 -
apps/web/src/i18n/translations/zh.json | 1 -
22 files changed, 18 insertions(+), 25 deletions(-)
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
index 48215804ee2dc..599c80e1bc853 100644
--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx
+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx
@@ -548,10 +548,13 @@ function UsageSummary(props: { readonly merged: MergedUsage; readonly metric: Us
{metric === "cost"
? gt("* if billed at full API rate")
- : gt("{count, plural, other {Across {sessions} sessions}}", {
- count: merged.sessions,
- sessions: formatCount(merged.sessions),
- })}
+ : gt(
+ "{count, plural, one {Across {sessions} session} other {Across {sessions} sessions}}",
+ {
+ count: merged.sessions,
+ sessions: formatCount(merged.sessions),
+ },
+ )}
);
diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json
index 0e1e8b79d090a..c0a851fe55fc4 100644
--- a/apps/mobile/src/i18n/translations/de.json
+++ b/apps/mobile/src/i18n/translations/de.json
@@ -5209,7 +5209,7 @@
"0b363b02a7e17bcb": "Rohe Token-Kosten",
"ea4beda46b22b8b0": "Verarbeitete Tokens",
"212d974007cacf3f": "* bei Abrechnung zum vollen API-Preis",
- "82bc7f1cc5a039fc": "{count, plural, one {Über {sessions} Sitzung} other {Über {sessions} Sitzungen}}",
+ "45340a7dc1f89d51": "{count, plural, one {Über {sessions} Sitzung} other {Über {sessions} Sitzungen}}",
"2a57181a9d128463": "{share} der Kosten · {tokens} Tokens",
"d8a6a99fbdda0d3e": "{share} der Tokens · {cost}",
"19a3f4f2ba09e787": "Summen",
diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json
index f460c7dccd6e2..07b19c65bc2c1 100644
--- a/apps/mobile/src/i18n/translations/en.json
+++ b/apps/mobile/src/i18n/translations/en.json
@@ -5211,7 +5211,7 @@
"0b363b02a7e17bcb": "Raw token cost",
"ea4beda46b22b8b0": "Processed tokens",
"212d974007cacf3f": "* if billed at full API rate",
- "82bc7f1cc5a039fc": "{count, plural, other {Across {sessions} sessions}}",
+ "45340a7dc1f89d51": "{count, plural, one {Across {sessions} session} other {Across {sessions} sessions}}",
"2a57181a9d128463": "{share} of cost · {tokens} tokens",
"d8a6a99fbdda0d3e": "{share} of tokens · {cost}",
"19a3f4f2ba09e787": "Totals",
diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json
index c80f59cdd9839..a9d0e0a71522c 100644
--- a/apps/mobile/src/i18n/translations/es.json
+++ b/apps/mobile/src/i18n/translations/es.json
@@ -5203,7 +5203,7 @@
"0b363b02a7e17bcb": "Coste bruto de tokens",
"ea4beda46b22b8b0": "Tokens procesados",
"212d974007cacf3f": "* si se facturara a la tarifa completa de la API",
- "82bc7f1cc5a039fc": "{count, plural, one {En {sessions} sesión} other {En {sessions} sesiones}}",
+ "45340a7dc1f89d51": "{count, plural, one {En {sessions} sesión} other {En {sessions} sesiones}}",
"2a57181a9d128463": "{share} del coste · {tokens} tokens",
"d8a6a99fbdda0d3e": "{share} de los tokens · {cost}",
"19a3f4f2ba09e787": "Totales",
diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json
index 746b4cca96776..53f494c1f78a0 100644
--- a/apps/mobile/src/i18n/translations/fr.json
+++ b/apps/mobile/src/i18n/translations/fr.json
@@ -5203,7 +5203,7 @@
"0b363b02a7e17bcb": "Coût brut des tokens",
"ea4beda46b22b8b0": "Tokens traités",
"212d974007cacf3f": "* si facturé au tarif API complet",
- "82bc7f1cc5a039fc": "{count, plural, one {Sur {sessions} session} other {Sur {sessions} sessions}}",
+ "45340a7dc1f89d51": "{count, plural, one {Sur {sessions} session} other {Sur {sessions} sessions}}",
"2a57181a9d128463": "{share} du coût · {tokens} tokens",
"d8a6a99fbdda0d3e": "{share} des tokens · {cost}",
"19a3f4f2ba09e787": "Totaux",
diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json
index 6e58d8c038c2e..b02e036733a2e 100644
--- a/apps/mobile/src/i18n/translations/ja.json
+++ b/apps/mobile/src/i18n/translations/ja.json
@@ -5183,7 +5183,7 @@
"0b363b02a7e17bcb": "トークンの素のコスト",
"ea4beda46b22b8b0": "処理トークン",
"212d974007cacf3f": "* API の正規料金で請求された場合",
- "82bc7f1cc5a039fc": "{count, plural, other {{sessions} セッションの合計}}",
+ "45340a7dc1f89d51": "{count, plural, other {{sessions} セッションの合計}}",
"2a57181a9d128463": "コストの {share} · {tokens} トークン",
"d8a6a99fbdda0d3e": "トークンの {share} · {cost}",
"19a3f4f2ba09e787": "合計",
diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json
index b9584b73f4c25..ea0b2f0fe6bf6 100644
--- a/apps/mobile/src/i18n/translations/ko.json
+++ b/apps/mobile/src/i18n/translations/ko.json
@@ -5187,7 +5187,7 @@
"0b363b02a7e17bcb": "원시 토큰 비용",
"ea4beda46b22b8b0": "처리된 토큰",
"212d974007cacf3f": "* 전체 API 요율로 청구되는 경우",
- "82bc7f1cc5a039fc": "{count, plural, other {세션 {sessions}개 전체}}",
+ "45340a7dc1f89d51": "{count, plural, other {세션 {sessions}개 전체}}",
"2a57181a9d128463": "비용의 {share} · 토큰 {tokens}개",
"d8a6a99fbdda0d3e": "토큰의 {share} · {cost}",
"19a3f4f2ba09e787": "합계",
diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json
index b3134701db673..2d71166e0e693 100644
--- a/apps/mobile/src/i18n/translations/pt-BR.json
+++ b/apps/mobile/src/i18n/translations/pt-BR.json
@@ -5203,7 +5203,7 @@
"0b363b02a7e17bcb": "Custo bruto de tokens",
"ea4beda46b22b8b0": "Tokens processados",
"212d974007cacf3f": "* se cobrado pela taxa cheia da API",
- "82bc7f1cc5a039fc": "{count, plural, one {Em {sessions} sessões} other {Em {sessions} sessões}}",
+ "45340a7dc1f89d51": "{count, plural, one {Em {sessions} sessão} other {Em {sessions} sessões}}",
"2a57181a9d128463": "{share} do custo · {tokens} tokens",
"d8a6a99fbdda0d3e": "{share} dos tokens · {cost}",
"19a3f4f2ba09e787": "Totais",
diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json
index 81c95ba264906..c3b869d1e87b9 100644
--- a/apps/mobile/src/i18n/translations/ru.json
+++ b/apps/mobile/src/i18n/translations/ru.json
@@ -5282,7 +5282,7 @@
"0b363b02a7e17bcb": "Стоимость токенов без скидок",
"ea4beda46b22b8b0": "Обработанные токены",
"212d974007cacf3f": "* при оплате по полной цене API",
- "82bc7f1cc5a039fc": "{count, plural, one {За {sessions} сеанс} few {За {sessions} сеанса} many {За {sessions} сеансов} other {За {sessions} сеанса}}",
+ "45340a7dc1f89d51": "{count, plural, one {За {sessions} сеанс} few {За {sessions} сеанса} many {За {sessions} сеансов} other {За {sessions} сеанса}}",
"2a57181a9d128463": "{share} стоимости · {tokens} токенов",
"d8a6a99fbdda0d3e": "{share} токенов · {cost}",
"19a3f4f2ba09e787": "Итоги",
diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json
index 73a089e773c34..b5ecfc8d466f4 100644
--- a/apps/mobile/src/i18n/translations/sv.json
+++ b/apps/mobile/src/i18n/translations/sv.json
@@ -5209,7 +5209,7 @@
"0b363b02a7e17bcb": "Rå tokenkostnad",
"ea4beda46b22b8b0": "Bearbetade token",
"212d974007cacf3f": "* om det debiterades till fullt API-pris",
- "82bc7f1cc5a039fc": "{count, plural, one {Över {sessions} session} other {Över {sessions} sessioner}}",
+ "45340a7dc1f89d51": "{count, plural, one {Över {sessions} session} other {Över {sessions} sessioner}}",
"2a57181a9d128463": "{share} av kostnaden · {tokens} token",
"d8a6a99fbdda0d3e": "{share} av token · {cost}",
"19a3f4f2ba09e787": "Totalt",
diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json
index 3fe06b30bd525..b9be48c79205f 100644
--- a/apps/mobile/src/i18n/translations/zh.json
+++ b/apps/mobile/src/i18n/translations/zh.json
@@ -5192,7 +5192,7 @@
"0b363b02a7e17bcb": "原始 token 费用",
"ea4beda46b22b8b0": "处理的 token",
"212d974007cacf3f": "* 按完整 API 费率计费时",
- "82bc7f1cc5a039fc": "{count, plural, other {共 {sessions} 个会话}}",
+ "45340a7dc1f89d51": "{count, plural, other {共 {sessions} 个会话}}",
"2a57181a9d128463": "占费用的 {share} · {tokens} token",
"d8a6a99fbdda0d3e": "占 token 的 {share} · {cost}",
"19a3f4f2ba09e787": "总计",
diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx
index 0aa227a146fe5..f4aa54b160eb2 100644
--- a/apps/web/src/components/usage/UsagePage.tsx
+++ b/apps/web/src/components/usage/UsagePage.tsx
@@ -702,7 +702,7 @@ function UsageOverview({
- {gt("{count, plural, one {{formatted} sessions} other {{formatted} sessions}}", {
+ {gt("{count, plural, one {{formatted} session} other {{formatted} sessions}}", {
count: merged.sessions,
formatted: formatCount(merged.sessions, locale),
})}
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json
index 96b3cb7f1967a..121682d3175bd 100644
--- a/apps/web/src/i18n/translations/de.json
+++ b/apps/web/src/i18n/translations/de.json
@@ -12342,7 +12342,6 @@
"d2d071e45a2d6b89": "Wähle eine Umgebung, um Limits zu sehen.",
"c9180daea905a0a6": "Wähle eine Umgebung, um die Nutzung zu sehen.",
"f0297ec79e896a13": "{environment}: {error}",
- "6dcbf651d51d4023": "{count, plural, one {{formatted} Sitzung} other {{formatted} Sitzungen}}",
"b01bf98dd90ee819": "API-Schätzung",
"bab34b28e9ee8e88": "Details zur Nutzung ohne Preis",
"61571f4542da9903": "{count, plural, one {{formatted} Sitzung} other {{formatted} Sitzungen}}",
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index 311e476e747ea..945814048420e 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -12350,7 +12350,6 @@
"d2d071e45a2d6b89": "Select an environment to see limits.",
"c9180daea905a0a6": "Select an environment to see usage.",
"f0297ec79e896a13": "{environment}: {error}",
- "6dcbf651d51d4023": "{count, plural, one {{formatted} sessions} other {{formatted} sessions}}",
"b01bf98dd90ee819": "API estimate",
"bab34b28e9ee8e88": "Unpriced usage details",
"61571f4542da9903": "{count, plural, one {{formatted} session} other {{formatted} sessions}}",
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index 56c909b7dd178..f6dd7cccaa75a 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -12335,7 +12335,6 @@
"d2d071e45a2d6b89": "Selecciona un entorno para ver los límites.",
"c9180daea905a0a6": "Selecciona un entorno para ver el uso.",
"f0297ec79e896a13": "{environment}: {error}",
- "6dcbf651d51d4023": "{count, plural, one {{formatted} sesión} other {{formatted} sesiones}}",
"b01bf98dd90ee819": "Estimación de API",
"bab34b28e9ee8e88": "Detalles del uso sin precio",
"61571f4542da9903": "{count, plural, one {{formatted} sesión} other {{formatted} sesiones}}",
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index 23a7578590f54..e3b5807b3da59 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -12340,7 +12340,6 @@
"d2d071e45a2d6b89": "Sélectionnez un environnement pour voir les limites.",
"c9180daea905a0a6": "Sélectionnez un environnement pour voir l’utilisation.",
"f0297ec79e896a13": "{environment} : {error}",
- "6dcbf651d51d4023": "{count, plural, one {{formatted} session} other {{formatted} sessions}}",
"b01bf98dd90ee819": "Estimation API",
"bab34b28e9ee8e88": "Détails de l’utilisation sans prix",
"61571f4542da9903": "{count, plural, one {{formatted} session} other {{formatted} sessions}}",
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index c89a28f54095d..22421d690a26a 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -12290,7 +12290,6 @@
"d2d071e45a2d6b89": "上限を表示するには環境を選択してください。",
"c9180daea905a0a6": "使用量を表示するには環境を選択してください。",
"f0297ec79e896a13": "{environment}: {error}",
- "6dcbf651d51d4023": "{count, plural, other {{formatted} セッション}}",
"b01bf98dd90ee819": "API の推定額",
"bab34b28e9ee8e88": "価格不明の使用量の詳細",
"61571f4542da9903": "{count, plural, other {{formatted} セッション}}",
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index 760c1546802f6..d0773f6146b3d 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -12286,7 +12286,6 @@
"d2d071e45a2d6b89": "한도를 보려면 환경을 선택하세요.",
"c9180daea905a0a6": "사용량을 보려면 환경을 선택하세요.",
"f0297ec79e896a13": "{environment}: {error}",
- "6dcbf651d51d4023": "{count, plural, other {세션 {formatted}개}}",
"b01bf98dd90ee819": "API 추정치",
"bab34b28e9ee8e88": "가격 없는 사용량 세부 정보",
"61571f4542da9903": "{count, plural, other {세션 {formatted}개}}",
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index a616078c936f6..ed3816a288bff 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -12340,7 +12340,6 @@
"d2d071e45a2d6b89": "Selecione um ambiente para ver os limites.",
"c9180daea905a0a6": "Selecione um ambiente para ver o uso.",
"f0297ec79e896a13": "{environment}: {error}",
- "6dcbf651d51d4023": "{count, plural, one {{formatted} sessão} other {{formatted} sessões}}",
"b01bf98dd90ee819": "Estimativa da API",
"bab34b28e9ee8e88": "Detalhes do uso sem preço",
"61571f4542da9903": "{count, plural, one {{formatted} sessão} other {{formatted} sessões}}",
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index 30cdb82efc3a2..e72c7773214b7 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -12341,7 +12341,6 @@
"d2d071e45a2d6b89": "Выберите окружение, чтобы увидеть лимиты.",
"c9180daea905a0a6": "Выберите окружение, чтобы увидеть использование.",
"f0297ec79e896a13": "{environment}: {error}",
- "6dcbf651d51d4023": "{count, plural, one {{formatted} сеанс} few {{formatted} сеанса} many {{formatted} сеансов} other {{formatted} сеанса}}",
"b01bf98dd90ee819": "Оценка по API",
"bab34b28e9ee8e88": "Подробности использования без цены",
"61571f4542da9903": "{count, plural, one {{formatted} сеанс} few {{formatted} сеанса} many {{formatted} сеансов} other {{formatted} сеанса}}",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index 9c524ac8b6e42..0756c1b15fa95 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -12348,7 +12348,6 @@
"d2d071e45a2d6b89": "Välj en miljö för att se gränser.",
"c9180daea905a0a6": "Välj en miljö för att se användning.",
"f0297ec79e896a13": "{environment}: {error}",
- "6dcbf651d51d4023": "{count, plural, one {{formatted} session} other {{formatted} sessioner}}",
"b01bf98dd90ee819": "API-uppskattning",
"bab34b28e9ee8e88": "Detaljer om användning utan pris",
"61571f4542da9903": "{count, plural, one {{formatted} session} other {{formatted} sessioner}}",
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index 341422731b4c0..cee3d72a497a2 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -12365,7 +12365,6 @@
"d2d071e45a2d6b89": "选择一个环境即可查看限制。",
"c9180daea905a0a6": "选择一个环境即可查看用量。",
"f0297ec79e896a13": "{environment}:{error}",
- "6dcbf651d51d4023": "{count, plural, other {{formatted} 个会话}}",
"b01bf98dd90ee819": "API 估算",
"bab34b28e9ee8e88": "未定价用量的详情",
"61571f4542da9903": "{count, plural, other {{formatted} 个会话}}",
From 19a6e5b57be7b016e037f14ab05ec2c12f0d4853 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 06:06:56 -0800
Subject: [PATCH 033/238] fix(web): clicking outside a citation comment keeps
its dictation (#42856)
---
.../AssistantCitationChip.browser.test.tsx | 125 +++++++++++++++++-
.../components/chat/AssistantCitationChip.tsx | 19 ++-
.../chat/AssistantCitationCommentEditor.tsx | 25 +++-
3 files changed, 163 insertions(+), 6 deletions(-)
diff --git a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx
index 53cf01fbbc645..8d02e359d3f36 100644
--- a/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx
+++ b/apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx
@@ -7,13 +7,86 @@ import {
} from "@t3tools/contracts";
import { useState, type ReactNode } from "react";
import { describe, expect, it, vi } from "vite-plus/test";
-import { userEvent } from "vite-plus/test/browser";
+import { page, userEvent } from "vite-plus/test/browser";
+import * as Effect from "effect/Effect";
+import * as Option from "effect/Option";
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
import "~/index.css";
import { act, render } from "../../../test/render";
+import { chooseAudioDestination, chooseTranscriptCleanup } from "../../speech/voiceConsent";
-const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() }));
+const mocks = vi.hoisted(() => ({
+ observeSource: vi.fn(),
+ dispose: vi.fn(),
+ transcribeCalls: 0,
+ transcript: null as Promise | null,
+}));
+const environment = vi.hoisted(() => ({
+ environmentId: "environment",
+ serverConfig: {
+ environment: { capabilities: { voiceTranscription: true, cloudVoiceTranscription: false } },
+ },
+}));
+const preparedConnection = vi.hoisted(() => ({
+ environmentId: "environment",
+ label: "environment",
+}));
+vi.mock(import("../../state/session"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useEnvironmentScope: () => true,
+ usePreparedConnection: ((environmentId: string | null) =>
+ environmentId === preparedConnection.environmentId
+ ? Option.some(preparedConnection)
+ : Option.none()) as never,
+}));
+vi.mock(import("../../state/environments"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ useEnvironment: ((environmentId: string | null) =>
+ environmentId === environment.environmentId ? environment : null) as never,
+}));
+vi.mock(import("../../speech/runEnvironmentSpeech"), () => ({
+ runEnvironmentSpeech: Effect.runPromise as never,
+}));
+vi.mock(import("@t3tools/client-runtime/voice-input"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ getEnvironmentSpeechStatus: (() =>
+ Effect.succeed({
+ supported: true,
+ state: "ready",
+ modelId: "test-model",
+ model: "Test",
+ size: 1,
+ supportsStreaming: false,
+ supportsTranslation: false,
+ acceleration: "auto",
+ benchmarkTier: "accelerated",
+ modelUnloadTimeout: "min_15",
+ gpuDevices: [],
+ })) as never,
+}));
+vi.mock(import("../../speech/browserVoiceInput"), () => ({
+ createAppleSpeechVoiceInputPlatform: vi.fn() as never,
+ createBrowserVoiceInputPlatform: (() => ({
+ recorder: {
+ uri: "blob:recording",
+ prepareToRecordAsync: async () => {},
+ record() {},
+ stop: async () => {},
+ },
+ transcriber: {
+ prepare: async () => ({
+ locale: "en",
+ transcribe: async () => {
+ mocks.transcribeCalls += 1;
+ return mocks.transcript ?? "dictated comment";
+ },
+ }),
+ },
+ cancelRecording() {},
+ deleteRecording() {},
+ })) as never,
+}));
vi.mock(import("./AssistantCitationSource"), async (importOriginal) => ({
...(await importOriginal()),
observeAssistantCitationCommentSource: mocks.observeSource,
@@ -51,6 +124,13 @@ function setup() {
return { sourceAnchor, [Symbol.dispose]: () => source.remove() };
}
+function useDictation() {
+ chooseAudioDestination({ kind: "environment", environmentId: citation.environmentId });
+ chooseTranscriptCleanup(false);
+ mocks.transcribeCalls = 0;
+ mocks.transcript = null;
+}
+
function mount(
sourceAnchor: AssistantCitationSourceAnchor | undefined,
onSave: () => boolean,
@@ -65,7 +145,12 @@ function mount(
/>
);
}
- return render( );
+ return render(
+ <>
+
+ Outside
+ >,
+ );
}
const textarea = () =>
@@ -247,3 +332,37 @@ describe("citation comment popup position", () => {
expect(rect.right).toBeLessThanOrEqual(window.innerWidth);
});
});
+
+describe("citation comment dictation", () => {
+ async function startDictation(onSave: () => boolean) {
+ using _source = setup();
+ useDictation();
+ const screen = await mount(undefined, onSave);
+ await page.getByRole("button", { name: "Start voice input" }).click();
+ await expect.element(page.getByRole("button", { name: "Finish voice input" })).toBeVisible();
+ return screen;
+ }
+
+ it("keeps the dictation when the box is clicked away while recording", async () => {
+ const onSave = vi.fn(() => true);
+ await using _screen = await startDictation(onSave);
+
+ await page.getByRole("button", { name: "Outside" }).click();
+
+ await vi.waitFor(() => expect(onSave).toHaveBeenCalledWith("dictated comment"));
+ });
+
+ it("keeps the dictation when the box is clicked away while transcribing", async () => {
+ const onSave = vi.fn(() => true);
+ await using _screen = await startDictation(onSave);
+ let finish!: (text: string) => void;
+ mocks.transcript = new Promise((resolve) => (finish = resolve));
+ await page.getByRole("button", { name: "Finish voice input" }).click();
+ await vi.waitFor(() => expect(mocks.transcribeCalls).toBe(1));
+
+ await page.getByRole("button", { name: "Outside" }).click();
+ finish("dictated comment");
+
+ await vi.waitFor(() => expect(onSave).toHaveBeenCalledWith("dictated comment"));
+ });
+});
diff --git a/apps/web/src/components/chat/AssistantCitationChip.tsx b/apps/web/src/components/chat/AssistantCitationChip.tsx
index 15aa53a2d3487..3bcc1215991d1 100644
--- a/apps/web/src/components/chat/AssistantCitationChip.tsx
+++ b/apps/web/src/components/chat/AssistantCitationChip.tsx
@@ -27,7 +27,10 @@ import { cn } from "~/lib/utils";
import { useQuietThreadShell } from "~/state/entities";
import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
-import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor";
+import {
+ AssistantCitationCommentEditor,
+ type AssistantCitationCommentDictation,
+} from "./AssistantCitationCommentEditor";
import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal";
import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
import { composerFloatingLayerProps } from "./composerEventScope";
@@ -200,6 +203,7 @@ export function AssistantCitationChip({
const commentInputRef = useRef(null);
const commentPopupRef = useRef(null);
const draftCommentRef = useRef(null);
+ const dictationRef = useRef(null);
const [voiceSetupOpen, setVoiceSetupOpen] = useState(false);
const [unavailableSourceAnchor, setUnavailableSourceAnchor] =
useState(null);
@@ -210,7 +214,7 @@ export function AssistantCitationChip({
useEffect(() => {
if (!commentOpen) draftCommentRef.current = null;
}, [commentOpen]);
- const settleDraftOnClose = (reason: string): boolean => {
+ const settleDraft = (reason: string): boolean => {
const dismissal = resolveAssistantCitationCommentDismissal({
reason,
draft: draftCommentRef.current,
@@ -219,6 +223,16 @@ export function AssistantCitationChip({
if (dismissal.kind === "commit") return commentEditor?.onSave(dismissal.comment) ?? true;
return dismissal.kind !== "keep-open";
};
+ // Closing unmounts the editor, which would discard its dictation, so it stays open until that lands.
+ const settleDraftOnClose = (reason: string): boolean => {
+ const finishing =
+ reason !== "escape-key" &&
+ dictationRef.current?.finish((comment) => {
+ draftCommentRef.current = comment;
+ if (settleDraft(reason)) commentEditor?.onOpenChange(false);
+ });
+ return !finishing && settleDraft(reason);
+ };
// The timeline virtualizes rows, so a vanished source is routine; the user may still be typing.
const onSourceUnavailable = useEffectEvent(() => {
if (sourceAnchor) setUnavailableSourceAnchor(sourceAnchor);
@@ -334,6 +348,7 @@ export function AssistantCitationChip({
key={serializeAssistantCitation(citation)}
citation={citation}
inputRef={commentInputRef}
+ dictationRef={dictationRef}
onVoiceSetupOpenChange={setVoiceSetupOpen}
onDraftChange={(comment) => {
draftCommentRef.current = comment;
diff --git a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx
index c8909ddc31fef..67cb1559aa4ff 100644
--- a/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx
+++ b/apps/web/src/components/chat/AssistantCitationCommentEditor.tsx
@@ -1,6 +1,14 @@
import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts";
import { T, useGT, Var } from "gt-react";
-import { use, useEffect, useRef, useState, type RefObject } from "react";
+import {
+ use,
+ useEffect,
+ useImperativeHandle,
+ useRef,
+ useState,
+ type Ref,
+ type RefObject,
+} from "react";
import { TextFieldSpeechControls, useTextFieldSpeech } from "~/speech/useTextFieldSpeech";
import { textDirection } from "~/textDirection";
@@ -8,6 +16,12 @@ import { textDirection } from "~/textDirection";
import { ComposerContextActionsContext } from "../composerContextActions";
import { Button } from "../ui/button";
+/** Lets the popover finish a running dictation, instead of discarding it, when it is dismissed. */
+export type AssistantCitationCommentDictation = {
+ /** False when nothing is being dictated; otherwise `settle` gets the comment once it is transcribed. */
+ finish: (settle: (comment: string) => void) => boolean;
+};
+
export function AssistantCitationCommentEditor({
citation,
inputRef,
@@ -16,6 +30,7 @@ export function AssistantCitationCommentEditor({
onCancel,
onDraftChange,
onVoiceSetupOpenChange,
+ dictationRef,
}: {
citation: AssistantCitation;
inputRef?: RefObject;
@@ -24,6 +39,7 @@ export function AssistantCitationCommentEditor({
onCancel: () => void;
onDraftChange?: (comment: string) => void;
onVoiceSetupOpenChange?: (open: boolean) => void;
+ dictationRef?: Ref;
}) {
const gt = useGT();
const [comment, setComment] = useState(citation.comment ?? "");
@@ -55,6 +71,13 @@ export function AssistantCitationCommentEditor({
onVoiceSetupOpenChange?.(setupOpen);
return () => onVoiceSetupOpenChange?.(false);
}, [onVoiceSetupOpenChange, setupOpen]);
+ useImperativeHandle(dictationRef, () => ({
+ finish: (settle) => {
+ if (!speech.blocksSubmission || speech.preparing) return false;
+ speech.submitAfterDictation(settle);
+ return true;
+ },
+ }));
const commentTooLong = comment.length > ASSISTANT_CITATION_MAX_COMMENT_LENGTH;
const submit = () => {
speech.submitAfterDictation((text) => {
From f1efcfb4948542237f6e2ceb5389de9e23f9baea Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 08:14:21 -0600
Subject: [PATCH 034/238] fix(client-runtime): feedback trace shows "1
character", not "1 characters" (#42855)
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 +-
apps/web/src/i18n/translations/de.json | 2 +-
apps/web/src/i18n/translations/en.json | 2 +-
apps/web/src/i18n/translations/es.json | 2 +-
apps/web/src/i18n/translations/fr.json | 2 +-
apps/web/src/i18n/translations/ja.json | 2 +-
apps/web/src/i18n/translations/ko.json | 2 +-
apps/web/src/i18n/translations/pt-BR.json | 2 +-
apps/web/src/i18n/translations/ru.json | 2 +-
apps/web/src/i18n/translations/sv.json | 2 +-
apps/web/src/i18n/translations/zh.json | 2 +-
packages/client-runtime/src/feedbackRequest.test.ts | 6 ++++--
packages/client-runtime/src/feedbackRequest.ts | 11 +++++++----
22 files changed, 31 insertions(+), 26 deletions(-)
diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json
index c0a851fe55fc4..3b62045baa01e 100644
--- a/apps/mobile/src/i18n/translations/de.json
+++ b/apps/mobile/src/i18n/translations/de.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Erwartet",
"9d11c93d4035de3e": "Tatsächlich passiert",
"c87d0595693704f9": "Stattdessen getan",
- "d7a4ea6ce5af44e0": "{speaker} · {count} Zeichen",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} Zeichen} other {{speaker} · {count} Zeichen}}",
"f5114fb9c40fd929": "Du",
"cd03eb1b84271c02": "Agent",
"bfe1a60f3f9c60fb": "Runde {turn} · {what}",
diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json
index 07b19c65bc2c1..2e482d69aa7f4 100644
--- a/apps/mobile/src/i18n/translations/en.json
+++ b/apps/mobile/src/i18n/translations/en.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Expected",
"9d11c93d4035de3e": "Happened",
"c87d0595693704f9": "Did instead",
- "d7a4ea6ce5af44e0": "{speaker} · {count} characters",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} character} other {{speaker} · {count} characters}}",
"f5114fb9c40fd929": "You",
"cd03eb1b84271c02": "Agent",
"bfe1a60f3f9c60fb": "Turn {turn} · {what}",
diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json
index a9d0e0a71522c..9f513dfccd516 100644
--- a/apps/mobile/src/i18n/translations/es.json
+++ b/apps/mobile/src/i18n/translations/es.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Resultado esperado",
"9d11c93d4035de3e": "Lo que ocurrió",
"c87d0595693704f9": "Alternativa utilizada",
- "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} carácter} other {{speaker} · {count} caracteres}}",
"f5114fb9c40fd929": "Tú",
"cd03eb1b84271c02": "Agente",
"bfe1a60f3f9c60fb": "Turno {turn} · {what}",
diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json
index 53f494c1f78a0..63a62d7f03188 100644
--- a/apps/mobile/src/i18n/translations/fr.json
+++ b/apps/mobile/src/i18n/translations/fr.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Résultat attendu",
"9d11c93d4035de3e": "Résultat obtenu",
"c87d0595693704f9": "Solution de repli",
- "d7a4ea6ce5af44e0": "{speaker} · {count} caractères",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} caractère} other {{speaker} · {count} caractères}}",
"f5114fb9c40fd929": "Vous",
"cd03eb1b84271c02": "Agent",
"bfe1a60f3f9c60fb": "Tour {turn} · {what}",
diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json
index b02e036733a2e..f0c24995414d9 100644
--- a/apps/mobile/src/i18n/translations/ja.json
+++ b/apps/mobile/src/i18n/translations/ja.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "期待した動作",
"9d11c93d4035de3e": "実際の動作",
"c87d0595693704f9": "代わりに行ったこと",
- "d7a4ea6ce5af44e0": "{speaker} · {count} 文字",
+ "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count} 文字}}",
"f5114fb9c40fd929": "あなた",
"cd03eb1b84271c02": "エージェント",
"bfe1a60f3f9c60fb": "ターン {turn} · {what}",
diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json
index ea0b2f0fe6bf6..e0c188e8c878d 100644
--- a/apps/mobile/src/i18n/translations/ko.json
+++ b/apps/mobile/src/i18n/translations/ko.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "기대한 동작",
"9d11c93d4035de3e": "실제 동작",
"c87d0595693704f9": "대신 한 일",
- "d7a4ea6ce5af44e0": "{speaker} · {count}자",
+ "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count}자}}",
"f5114fb9c40fd929": "나",
"cd03eb1b84271c02": "에이전트",
"bfe1a60f3f9c60fb": "턴 {turn} · {what}",
diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json
index 2d71166e0e693..386b5dc53afbf 100644
--- a/apps/mobile/src/i18n/translations/pt-BR.json
+++ b/apps/mobile/src/i18n/translations/pt-BR.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Resultado esperado",
"9d11c93d4035de3e": "O que aconteceu",
"c87d0595693704f9": "Alternativa utilizada",
- "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} caractere} other {{speaker} · {count} caracteres}}",
"f5114fb9c40fd929": "Você",
"cd03eb1b84271c02": "Agente",
"bfe1a60f3f9c60fb": "Turno {turn} · {what}",
diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json
index c3b869d1e87b9..c3197052b5fa7 100644
--- a/apps/mobile/src/i18n/translations/ru.json
+++ b/apps/mobile/src/i18n/translations/ru.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Ожидалось",
"9d11c93d4035de3e": "Произошло",
"c87d0595693704f9": "Что сделано вместо этого",
- "d7a4ea6ce5af44e0": "{speaker} · {count} симв.",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} симв.} few {{speaker} · {count} симв.} many {{speaker} · {count} симв.} other {{speaker} · {count} симв.}}",
"f5114fb9c40fd929": "Вы",
"cd03eb1b84271c02": "Агент",
"bfe1a60f3f9c60fb": "Ход {turn} · {what}",
diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json
index b5ecfc8d466f4..fa0454bb9f430 100644
--- a/apps/mobile/src/i18n/translations/sv.json
+++ b/apps/mobile/src/i18n/translations/sv.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Förväntat",
"9d11c93d4035de3e": "Vad som hände",
"c87d0595693704f9": "Gjorde i stället",
- "d7a4ea6ce5af44e0": "{speaker} · {count} tecken",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} tecken} other {{speaker} · {count} tecken}}",
"f5114fb9c40fd929": "Du",
"cd03eb1b84271c02": "Agent",
"bfe1a60f3f9c60fb": "Omgång {turn} · {what}",
diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json
index b9be48c79205f..5eb155844e938 100644
--- a/apps/mobile/src/i18n/translations/zh.json
+++ b/apps/mobile/src/i18n/translations/zh.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "预期行为",
"9d11c93d4035de3e": "实际情况",
"c87d0595693704f9": "替代做法",
- "d7a4ea6ce5af44e0": "{speaker} · {count} 个字符",
+ "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count} 个字符}}",
"f5114fb9c40fd929": "你",
"cd03eb1b84271c02": "智能体",
"bfe1a60f3f9c60fb": "第 {turn} 轮 · {what}",
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json
index 121682d3175bd..2f8bb9a78f29e 100644
--- a/apps/web/src/i18n/translations/de.json
+++ b/apps/web/src/i18n/translations/de.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Erwartet",
"9d11c93d4035de3e": "Tatsächlich passiert",
"c87d0595693704f9": "Stattdessen getan",
- "d7a4ea6ce5af44e0": "{speaker} · {count} Zeichen",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} Zeichen} other {{speaker} · {count} Zeichen}}",
"f5114fb9c40fd929": "Du",
"cd03eb1b84271c02": "Agent",
"bfe1a60f3f9c60fb": "Runde {turn} · {what}",
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index 945814048420e..344891fe62609 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Expected",
"9d11c93d4035de3e": "Happened",
"c87d0595693704f9": "Did instead",
- "d7a4ea6ce5af44e0": "{speaker} · {count} characters",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} character} other {{speaker} · {count} characters}}",
"f5114fb9c40fd929": "You",
"cd03eb1b84271c02": "Agent",
"bfe1a60f3f9c60fb": "Turn {turn} · {what}",
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index f6dd7cccaa75a..38ae9dc156ebc 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Resultado esperado",
"9d11c93d4035de3e": "Lo que ocurrió",
"c87d0595693704f9": "Alternativa utilizada",
- "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} carácter} other {{speaker} · {count} caracteres}}",
"f5114fb9c40fd929": "Tú",
"cd03eb1b84271c02": "Agente",
"bfe1a60f3f9c60fb": "Turno {turn} · {what}",
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index e3b5807b3da59..57cc6f526c041 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Résultat attendu",
"9d11c93d4035de3e": "Résultat obtenu",
"c87d0595693704f9": "Solution de repli",
- "d7a4ea6ce5af44e0": "{speaker} · {count} caractères",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} caractère} other {{speaker} · {count} caractères}}",
"f5114fb9c40fd929": "Vous",
"cd03eb1b84271c02": "Agent",
"bfe1a60f3f9c60fb": "Tour {turn} · {what}",
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index 22421d690a26a..5a48ea70d7abc 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "期待した動作",
"9d11c93d4035de3e": "実際の動作",
"c87d0595693704f9": "代わりに行ったこと",
- "d7a4ea6ce5af44e0": "{speaker} · {count} 文字",
+ "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count} 文字}}",
"f5114fb9c40fd929": "あなた",
"cd03eb1b84271c02": "エージェント",
"bfe1a60f3f9c60fb": "ターン {turn} · {what}",
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index d0773f6146b3d..bdec1db133159 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "기대한 동작",
"9d11c93d4035de3e": "실제 동작",
"c87d0595693704f9": "대신 한 일",
- "d7a4ea6ce5af44e0": "{speaker} · {count}자",
+ "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count}자}}",
"f5114fb9c40fd929": "나",
"cd03eb1b84271c02": "에이전트",
"bfe1a60f3f9c60fb": "턴 {turn} · {what}",
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index ed3816a288bff..20baf91f8b106 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Resultado esperado",
"9d11c93d4035de3e": "O que aconteceu",
"c87d0595693704f9": "Alternativa utilizada",
- "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} caractere} other {{speaker} · {count} caracteres}}",
"f5114fb9c40fd929": "Você",
"cd03eb1b84271c02": "Agente",
"bfe1a60f3f9c60fb": "Turno {turn} · {what}",
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index e72c7773214b7..1f58942bc5cfc 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Ожидалось",
"9d11c93d4035de3e": "Произошло",
"c87d0595693704f9": "Что сделано вместо этого",
- "d7a4ea6ce5af44e0": "{speaker} · {count} симв.",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} симв.} few {{speaker} · {count} симв.} many {{speaker} · {count} симв.} other {{speaker} · {count} симв.}}",
"f5114fb9c40fd929": "Вы",
"cd03eb1b84271c02": "Агент",
"bfe1a60f3f9c60fb": "Ход {turn} · {what}",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index 0756c1b15fa95..c7370bb2ec772 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "Förväntat",
"9d11c93d4035de3e": "Vad som hände",
"c87d0595693704f9": "Gjorde i stället",
- "d7a4ea6ce5af44e0": "{speaker} · {count} tecken",
+ "ed5c85bb4aecb472": "{count, plural, one {{speaker} · {count} tecken} other {{speaker} · {count} tecken}}",
"f5114fb9c40fd929": "Du",
"cd03eb1b84271c02": "Agent",
"bfe1a60f3f9c60fb": "Omgång {turn} · {what}",
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index cee3d72a497a2..98276b6809237 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -66,7 +66,7 @@
"2f6e4f7cd364da73": "预期行为",
"9d11c93d4035de3e": "实际情况",
"c87d0595693704f9": "替代做法",
- "d7a4ea6ce5af44e0": "{speaker} · {count} 个字符",
+ "ed5c85bb4aecb472": "{count, plural, other {{speaker} · {count} 个字符}}",
"f5114fb9c40fd929": "你",
"cd03eb1b84271c02": "智能体",
"bfe1a60f3f9c60fb": "第 {turn} 轮 · {what}",
diff --git a/packages/client-runtime/src/feedbackRequest.test.ts b/packages/client-runtime/src/feedbackRequest.test.ts
index 8c1d5b6cae4bd..6911a213867e7 100644
--- a/packages/client-runtime/src/feedbackRequest.test.ts
+++ b/packages/client-runtime/src/feedbackRequest.test.ts
@@ -31,8 +31,8 @@ describe("feedbackRequestDisplay", () => {
describe("feedback preview", () => {
it("shows every field that is sent, and each outline entry with its text", () => {
const trace = {
- turns: 1,
- textTurns: 1,
+ turns: 2,
+ textTurns: 2,
truncated: false,
entries: [
{ turn: 1, type: "user" as const, length: 5, text: "Hello" },
@@ -43,6 +43,7 @@ describe("feedback preview", () => {
outcome: "error" as const,
durationMs: 1_500,
},
+ { turn: 2, type: "user" as const, length: 1, text: "y" },
],
};
expect(
@@ -58,6 +59,7 @@ describe("feedback preview", () => {
expect(feedbackTraceLines(trace)).toEqual([
{ key: "0", line: "Turn 1 · You · 5 characters", text: "Hello" },
{ key: "1", line: "Turn 1 · t3_thread_read · error · 1.5 s" },
+ { key: "2", line: "Turn 2 · You · 1 character", text: "y" },
]);
// Text only in turn 4 of 5: the wording reaches back to it, not "the last turn".
const older = {
diff --git a/packages/client-runtime/src/feedbackRequest.ts b/packages/client-runtime/src/feedbackRequest.ts
index f6b0079213ebc..4c131c116d3e1 100644
--- a/packages/client-runtime/src/feedbackRequest.ts
+++ b/packages/client-runtime/src/feedbackRequest.ts
@@ -86,10 +86,13 @@ export function feedbackTraceLines(
.filter((part) => part !== undefined)
.join(" · ")
: resolve(
- msg("{speaker} · {count} characters", {
- speaker: resolve(entry.type === "user" ? msg("You") : msg("Agent")),
- count: entry.length ?? 0,
- }),
+ msg(
+ "{count, plural, one {{speaker} · {count} character} other {{speaker} · {count} characters}}",
+ {
+ speaker: resolve(entry.type === "user" ? msg("You") : msg("Agent")),
+ count: entry.length ?? 0,
+ },
+ ),
);
return {
key: `${index}`,
From 7814c9f884b2baff651c132ce38a077767de138d Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 06:30:19 -0800
Subject: [PATCH 035/238] fix(desktop): WSL-only backend no longer falls back
to Windows when reg.exe is blocked by policy (#42857)
---
.../src/wsl/DesktopWslEnvironment.test.ts | 39 ++++++++++++++++++-
apps/desktop/src/wsl/DesktopWslEnvironment.ts | 14 +++++--
2 files changed, 48 insertions(+), 5 deletions(-)
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
index 470091f334fb7..aab0f0b2f8eea 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts
@@ -557,6 +557,7 @@ describe("parseResolvedPath", () => {
const WSL_EXE = "/windows/System32/wsl.exe";
const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService";
const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager";
+const SERVICES_ROOT = "HKLM\\SYSTEM\\CurrentControlSet\\Services";
const registrySpawner = (keys: ReadonlyArray) =>
ChildProcessSpawner.make((command) =>
@@ -570,7 +571,7 @@ const registrySpawner = (keys: ReadonlyArray) =>
ChildProcessSpawner.ExitCode(
command._tag === "StandardCommand" &&
command.command === "reg.exe" &&
- keys.some((key) => command.args.includes(key))
+ [SERVICES_ROOT, ...keys].some((key) => command.args.includes(key))
? 0
: 1,
),
@@ -608,6 +609,42 @@ describe("makeIsAvailable", () => {
}),
);
+ it.effect("keeps WSL when registry tools are disabled by policy and reg.exe cannot answer", () =>
+ Effect.gen(function* () {
+ const denied = new TextEncoder().encode(
+ "ERROR: Registry editing has been disabled by your administrator.\r\n",
+ );
+ const blockedRegistry = ChildProcessSpawner.make(() =>
+ Effect.succeed(
+ ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(1),
+ stdout: Stream.empty,
+ stderr: Stream.make(denied),
+ all: Stream.make(denied),
+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(1)),
+ isRunning: Effect.succeed(false),
+ kill: () => Effect.void,
+ stdin: Sink.drain,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ unref: Effect.succeed(Effect.void),
+ }),
+ ),
+ );
+ const available = yield* makeIsAvailable("win32", "/windows").pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ FileSystem.layerNoop({ exists: (path) => Effect.succeed(path === WSL_EXE) }),
+ Path.layer,
+ DesktopManagedPolicy.layerTest(undefined),
+ ),
+ ),
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, blockedRegistry),
+ );
+ assert.isTrue(available);
+ }),
+ );
+
it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () =>
Effect.gen(function* () {
assert.isTrue(yield* isAvailable());
diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
index 9d9540a65dc7d..afd9ef013299d 100644
--- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts
+++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts
@@ -1124,13 +1124,16 @@ const WSL_SERVICE_KEYS = [
"HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService",
"HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager",
] as const;
+// Always present; when reg.exe cannot read it (e.g. "Prevent access to registry editing tools"),
+// a failed service query says nothing about WSL, so fall back to trusting wsl.exe.
+const SERVICES_ROOT_KEY = "HKLM\\SYSTEM\\CurrentControlSet\\Services";
const SERVICE_QUERY_TIMEOUT = Duration.seconds(5);
const wslServiceRegistered = Effect.scoped(
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
- const registered = yield* Effect.forEach(
- WSL_SERVICE_KEYS,
+ const [rootReadable, ...servicesFound] = yield* Effect.forEach(
+ [SERVICES_ROOT_KEY, ...WSL_SERVICE_KEYS],
(key) =>
spawner
.spawn(
@@ -1142,10 +1145,13 @@ const wslServiceRegistered = Effect.scoped(
forceKillAfter: PROCESS_TERMINATE_GRACE,
}),
)
- .pipe(Effect.flatMap((handle) => handle.exitCode)),
+ .pipe(
+ Effect.flatMap((handle) => handle.exitCode),
+ Effect.map((exitCode) => (exitCode as unknown as number) === 0),
+ ),
{ concurrency: "unbounded" },
);
- return registered.some((exitCode) => (exitCode as unknown as number) === 0);
+ return rootReadable === false || servicesFound.includes(true);
}),
).pipe(
Effect.timeoutOption(SERVICE_QUERY_TIMEOUT),
From 6cca0b18646b172d00fc0d88e2a80021d6b55372 Mon Sep 17 00:00:00 2001
From: Pedro Sousa
Date: Wed, 25 Nov 2026 15:39:56 +0100
Subject: [PATCH 036/238] fix(github): count team review requests in the
Reviewing filter (#42835)
Co-authored-by: Pedro Sousa <4235827+pedrosousa13@users.noreply.github.com>
Co-authored-by: Julius Marminge
---
.../server/GitHubPullRequestProvider.test.ts | 71 +++++++++++++++++++
.../src/server/GitHubPullRequestProvider.ts | 20 +++++-
2 files changed, 89 insertions(+), 2 deletions(-)
diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts
index 7d305ac4b7873..ad6eab9634315 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.test.ts
@@ -967,6 +967,60 @@ describe("loginAvatarUrl", () => {
});
});
+describe("listChangeRequests", () => {
+ it.effect("counts a team review request as the viewer's only on search rows", () =>
+ Effect.gen(function* () {
+ const teamOnly = {
+ number: 1,
+ title: "Change",
+ url: "https://github.com/acme/web/pull/1",
+ author: null,
+ headBranch: "feature",
+ baseBranch: "main",
+ state: "open" as const,
+ isDraft: false,
+ mergeability: "mergeable" as const,
+ additions: 0,
+ deletions: 0,
+ createdAt: "2026-07-01T00:00:00Z",
+ updatedAt: "2026-07-02T00:00:00Z",
+ reviewRequestLogins: ["someone-else"],
+ hasTeamReviewRequest: true,
+ labels: [],
+ reviewDecision: null,
+ checksState: null,
+ };
+ const list = (continues: boolean, involvement: "all" | "reviewing") =>
+ make.pipe(
+ Effect.provide(
+ Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({
+ listPullRequests: () =>
+ Effect.succeed({ items: [teamOnly], truncated: false, continues }),
+ }),
+ ),
+ Effect.flatMap((provider) =>
+ provider.listChangeRequests({
+ cwd: "/w",
+ host: "github.com",
+ repository: "acme/web",
+ state: "open",
+ involvement,
+ viewer: "Viewer",
+ limit: 50,
+ }),
+ ),
+ );
+ const searched = yield* list(true, "reviewing");
+ expect(searched.items[0]!.reviewRequestLogins).toEqual(["someone-else", "Viewer"]);
+ const all = yield* list(true, "all");
+ expect(all.items[0]!.reviewRequestLogins).toEqual(["someone-else"]);
+ // The listing fallback keeps any team's request; it cannot say the team is the viewer's.
+ const listed = yield* list(false, "reviewing");
+ expect(listed.items[0]!.reviewRequestLogins).toEqual(["someone-else"]);
+ }),
+ );
+});
+
describe("listChangeRequestsAcross", () => {
const searched = (repository: string): GitHubPullRequestSearchItem => ({
repository,
@@ -1082,6 +1136,23 @@ describe("listChangeRequestsAcross", () => {
}),
);
+ it.effect("counts a review requested from the viewer's team as requested from the viewer", () =>
+ Effect.gen(function* () {
+ const teamOnly = { ...searched("acme/web"), hasTeamReviewRequest: true };
+ const read = yield* providerAnswering({
+ pages: [
+ { items: [teamOnly], truncated: false },
+ { items: [teamOnly], truncated: false },
+ ],
+ covered: () => true,
+ });
+ const reviewing = yield* read({ ...across, involvement: "reviewing" });
+ expect(reviewing.items[0]!.reviewRequestLogins).toEqual(["viewer"]);
+ const all = yield* read(across);
+ expect(all.items[0]!.reviewRequestLogins).toEqual([]);
+ }),
+ );
+
it.effect("past the first slice, believes a covered repository and not an uncovered one", () =>
Effect.gen(function* () {
const read = yield* providerAnswering({
diff --git a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
index 88dcc1aea2ed9..19e894eb308e0 100644
--- a/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
+++ b/packages/source-control-github/src/server/GitHubPullRequestProvider.ts
@@ -32,6 +32,22 @@ import type {
} from "./gitHubPullRequestJson.ts";
import { definition } from "../shared/definition.ts";
+/**
+ * `review-requested:` search rows include the viewer's team requests, which name no login,
+ * so record the viewer as requested. Search rows only: the listing fallback cannot tell whether the
+ * viewer belongs to a requested team.
+ */
+function withViewerRequested }>(
+ item: T,
+ input: { readonly involvement: string; readonly viewer: string },
+): T {
+ const viewer = input.viewer.toLowerCase();
+ return input.involvement === "reviewing" &&
+ !item.reviewRequestLogins.some((login) => login.toLowerCase() === viewer)
+ ? { ...item, reviewRequestLogins: [...item.reviewRequestLogins, input.viewer] }
+ : item;
+}
+
const CAPABILITIES: PullRequestCapabilities = {
diff: true,
comment: true,
@@ -434,7 +450,7 @@ export const make = Effect.gen(function* () {
Effect.map((page) => ({
...page,
items: page.items.map((item) => ({
- ...item,
+ ...(page.continues ? withViewerRequested(item, input) : item),
author: withAvatar(item.author, new Map(), input.host),
})),
})),
@@ -460,7 +476,7 @@ export const make = Effect.gen(function* () {
Effect.map(unresolvedBySearch(input, batch), (unresolved) => ({
truncated: batch.truncated,
items: batch.items.map((item) => ({
- ...item,
+ ...withViewerRequested(item, input),
author: withAvatar(item.author, new Map(), input.host),
})),
unresolved,
From 172309c39c9525df0435141d74d4d9c0530b13e9 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 06:42:13 -0800
Subject: [PATCH 037/238] fix(web): timeline minimap no longer covers the Copy
button when the chat lane is shifted left (#42876)
---
.../chat/MessagesTimeline.browser.test.tsx | 77 +++++++++++++++++++
.../chat/MessagesTimeline.logic.test.ts | 22 +++---
.../components/chat/MessagesTimeline.logic.ts | 22 ++----
.../src/components/chat/MessagesTimeline.tsx | 35 ++++-----
4 files changed, 110 insertions(+), 46 deletions(-)
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index 45ba21665b2fe..b31558c2a38ba 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -737,6 +737,83 @@ describe("MessagesTimeline messages", () => {
});
});
+ it("keeps the minimap off the copy button when the chat lane is shifted left", async () => {
+ setup();
+ const pageSize = { width: window.innerWidth, height: window.innerHeight };
+ await page.viewport(1280, 800);
+ await using _pageSize = {
+ [Symbol.asyncDispose]: () => page.viewport(pageSize.width, pageSize.height),
+ };
+ const props = baseProps();
+ const entries = Array.from({ length: 6 }, (_, index) => [
+ message(`Question ${index}`, {}, `user-${index}`),
+ message(`Answer ${index}`, { role: "assistant" }, `assistant-${index}`),
+ ]).flat();
+ // ChatCanvas at 1024px with the details card open: a 48px left gutter, not a centered one.
+ await using screen = await renderElement(
+
+
+
,
+ );
+ const viewport = props.listRef.current!.getScrollableNode()!;
+ const lane = screen.container.querySelector("[data-timeline-root]")!;
+ await vi.waitFor(() => {
+ expect(screen.container.querySelector("[data-minimap-strip]")).not.toBeNull();
+ const laneRect = lane.getBoundingClientRect();
+ const viewportRect = viewport.getBoundingClientRect();
+ expect(laneRect.left - viewportRect.left).toBeLessThan(viewportRect.right - laneRect.right);
+ });
+
+ const jump = screen.buttons(/^Jump to message/)[0]!;
+ await vi.waitFor(() =>
+ expect(jump.getBoundingClientRect().right).toBeLessThanOrEqual(
+ lane.getBoundingClientRect().left,
+ ),
+ );
+ });
+
+ it("moves the minimap off the chat lane when the lane shifts left without resizing", async () => {
+ setup();
+ const pageSize = { width: window.innerWidth, height: window.innerHeight };
+ await page.viewport(1600, 800);
+ await using _pageSize = {
+ [Symbol.asyncDispose]: () => page.viewport(pageSize.width, pageSize.height),
+ };
+ const props = baseProps();
+ const entries = Array.from({ length: 6 }, (_, index) => [
+ message(`Question ${index}`, {}, `user-${index}`),
+ message(`Answer ${index}`, { role: "assistant" }, `assistant-${index}`),
+ ]).flat();
+ await using screen = await renderElement(
+
+
+
,
+ );
+ const canvas = screen.container.querySelector("[data-chat-canvas]")!;
+ const lane = screen.container.querySelector("[data-timeline-root]")!;
+ await vi.waitFor(() =>
+ expect(screen.container.querySelector("[data-minimap-strip]")).not.toBeNull(),
+ );
+ const laneWidth = lane.getBoundingClientRect().width;
+
+ // Opening the details card on a wide canvas moves the lane left at full width.
+ canvas.style.setProperty("--chat-lane-inset-end", "740px");
+ const jump = screen.buttons(/^Jump to message/)[0]!;
+ await vi.waitFor(() => {
+ expect(lane.getBoundingClientRect().width).toBe(laneWidth);
+ expect(jump.getBoundingClientRect().right).toBeLessThanOrEqual(
+ lane.getBoundingClientRect().left,
+ );
+ });
+ });
+
it("enables the minimap's next turn button on a thread restored above its bottom", async () => {
setup();
const base = baseProps();
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
index 3257f9588eeae..6330bb33c22fa 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
@@ -43,18 +43,16 @@ import { workEntryIconName } from "./TimelineWorkEntryRow.logic";
describe("resolveTimelineMinimapHitStrip", () => {
it.each([
- { viewport: 1280, content: 768, left: 32, width: 40 },
- { viewport: 768, content: 672, left: 32, width: 16 },
- { viewport: 768, content: 704, left: 0, width: 8 },
- { viewport: 768, content: 720, left: 0, width: 8 },
- { viewport: 768, content: 756, left: 0, width: 6 },
- { viewport: 768, content: 768, left: 0, width: 0 },
- ])(
- "keeps the minimap inside the gutter at $viewport/$content",
- ({ viewport, content, left, width }) => {
- expect(resolveTimelineMinimapHitStrip(viewport, content)).toEqual({ left, width });
- },
- );
+ { gutter: 256, left: 32, width: 40 },
+ { gutter: 48, left: 32, width: 16 },
+ { gutter: 32, left: 0, width: 8 },
+ { gutter: 24, left: 0, width: 8 },
+ { gutter: 6, left: 0, width: 6 },
+ { gutter: 0, left: 0, width: 0 },
+ { gutter: -4, left: 0, width: 0 },
+ ])("keeps the minimap inside a $gutter px gutter", ({ gutter, left, width }) => {
+ expect(resolveTimelineMinimapHitStrip(gutter)).toEqual({ left, width });
+ });
});
describe("resolveAssistantMessageCopyState", () => {
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
index a7bca7de9f901..ae8ad90df43b9 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
@@ -464,28 +464,18 @@ export function resolveTimelineMinimapCurrentIndex(input: {
return precedingIndex;
}
-function resolveTimelineSideGutter(viewportWidth: number, contentWidth: number): number {
- if (!Number.isFinite(viewportWidth) || viewportWidth <= 0 || !Number.isFinite(contentWidth)) {
- return 0;
- }
- return Math.max(0, (viewportWidth - Math.min(viewportWidth, contentWidth)) / 2);
-}
-
-export function resolveTimelineMinimapHasPersistentGutter(
- viewportWidth: number,
- contentWidth: number,
-): boolean {
- return (
- resolveTimelineSideGutter(viewportWidth, contentWidth) >= TIMELINE_MINIMAP_PERSISTENT_GUTTER
- );
+export function resolveTimelineMinimapHasPersistentGutter(sideGutter: number): boolean {
+ return sideGutter >= TIMELINE_MINIMAP_PERSISTENT_GUTTER;
}
const TIMELINE_MINIMAP_HIT_STRIP_LEFT = 32;
const TIMELINE_MINIMAP_HIT_STRIP_MAX_WIDTH = 40;
const TIMELINE_MINIMAP_NAVIGATION_REACH = 14;
-export function resolveTimelineMinimapHitStrip(viewportWidth: number, contentWidth: number) {
- const sideGutter = Math.floor(resolveTimelineSideGutter(viewportWidth, contentWidth));
+export function resolveTimelineMinimapHitStrip(measuredSideGutter: number) {
+ const sideGutter = Number.isFinite(measuredSideGutter)
+ ? Math.max(0, Math.floor(measuredSideGutter))
+ : 0;
if (sideGutter < TIMELINE_MINIMAP_HIT_STRIP_LEFT + TIMELINE_MINIMAP_NAVIGATION_REACH) {
// Keep a hover target in the gutter, to the left of the sidebar restore handle.
return { left: 0, width: Math.min(8, sideGutter) };
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 1bd08298ec505..07e42d0a6542e 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -1067,18 +1067,16 @@ const ConversationTimeline = memo(function ConversationTimeline({
};
const measureTimelineGutter = (viewportElement: HTMLElement) => {
- const viewportWidth = viewportElement.getBoundingClientRect().width;
- const contentWidth =
- viewportElement.querySelector("[data-timeline-root]")?.getBoundingClientRect()
- .width ?? viewportWidth;
- const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(
- viewportWidth,
- contentWidth,
- );
+ const lane = viewportElement.querySelector("[data-timeline-root]");
+ // ChatCanvas can shift the lane off center, so measure the gutter the minimap sits in.
+ const sideGutter = lane
+ ? lane.getBoundingClientRect().left - viewportElement.getBoundingClientRect().left
+ : 0;
+ const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(sideGutter);
setMinimapHasPersistentGutter((current) =>
current === nextHasPersistentGutter ? current : nextHasPersistentGutter,
);
- const nextHitStrip = resolveTimelineMinimapHitStrip(viewportWidth, contentWidth);
+ const nextHitStrip = resolveTimelineMinimapHitStrip(sideGutter);
setMinimapHitStrip((current) =>
current.left === nextHitStrip.left && current.width === nextHitStrip.width
? current
@@ -1095,16 +1093,17 @@ const ConversationTimeline = memo(function ConversationTimeline({
}
handleScroll();
});
- // The content lane only changes width with the viewport or the chat width
- // setting, never with streamed content; measuring per content frame would
- // force a layout on every chunk.
- const measuredLaneWidthRef = useRef(null);
+ // The content lane only moves or changes width with the viewport, the chat
+ // width setting or the canvas insets (which resize its row frame), never with
+ // streamed content; measuring per content frame would force a layout on every chunk.
+ const measuredLaneWidthRef = useRef(null);
const observeLaneWidth = (lane: HTMLDivElement | null) => {
- if (!lane) return;
- return observeResize(lane, (entries) => {
- const width = entries.at(-1)?.contentRect.width;
- if (width === undefined || width === measuredLaneWidthRef.current) return;
- measuredLaneWidthRef.current = width;
+ const frame = lane?.parentElement;
+ if (!lane || !frame) return;
+ return observeResize([frame, lane], () => {
+ const widths = `${frame.clientWidth}:${lane.clientWidth}`;
+ if (widths === measuredLaneWidthRef.current) return;
+ measuredLaneWidthRef.current = widths;
const viewportElement = lane.closest("[data-assistant-citation-viewport]");
if (viewportElement) measureTimelineGutter(viewportElement);
});
From 9de5a941eaa42914da08984220daaccb2d971ad2 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 06:42:29 -0800
Subject: [PATCH 038/238] perf(web): Files panel Refresh reads only the folders
on screen (#42870)
---
.../files/FileBrowserPanel.browser.test.tsx | 8 +++
.../src/components/files/FileBrowserPanel.tsx | 24 ++++++---
.../files/fileTreeExpansion.test.ts | 10 ++++
.../src/components/files/fileTreeExpansion.ts | 16 +++++-
.../useDirectoryEntries.browser.test.tsx | 42 +++++++++++++++-
.../components/files/useDirectoryEntries.ts | 49 ++++++++++++++++---
6 files changed, 131 insertions(+), 18 deletions(-)
create mode 100644 apps/web/src/components/files/fileTreeExpansion.test.ts
diff --git a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
index 2a1f16b31070b..ecf51be124491 100644
--- a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
+++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
@@ -20,6 +20,7 @@ const directory: {
entries: readonly ProjectEntry[];
load: () => Promise;
refresh: () => void;
+ revalidate: (directoryPath: string) => void;
ready: boolean;
error: null;
isPending: boolean;
@@ -28,6 +29,7 @@ const directory: {
entries,
load: () => Promise.resolve(),
refresh: () => {},
+ revalidate: () => {},
ready: true,
error: null,
isPending: false,
@@ -365,9 +367,15 @@ describe("FileBrowserPanel", () => {
);
}
+ using revalidate = vi.spyOn(directory, "revalidate");
await using _second = await render(panel());
await vi.waitFor(() => expect(findTreeRow("src/")).not.toBeNull());
await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
+
+ // Refresh revalidates the folders behind the rows on screen: the open one and the root.
+ revalidate.mockClear();
+ await userEvent.click(page.getByRole("button", { name: "Refresh workspace files" }));
+ expect(revalidate.mock.calls).toEqual([["src"], [""]]);
});
describe("revealing a folder while folders above it are still loading", () => {
const roots = Array.from({ length: 12 }, (_, index): ProjectEntry => {
diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx
index 4609a8bacd089..03c6d30972b34 100644
--- a/apps/web/src/components/files/FileBrowserPanel.tsx
+++ b/apps/web/src/components/files/FileBrowserPanel.tsx
@@ -188,6 +188,7 @@ export default function FileBrowserPanel({
entries: directoryEntries,
load,
refresh,
+ revalidate,
ready,
error,
isPending,
@@ -300,6 +301,7 @@ export default function FileBrowserPanel({
);
const loadingDirectoriesRef = useRef(loadingDirectories);
+ const revalidateDirectory = useStableCallback(revalidate);
const dragMention = createFileTreeDragMentionController(
hostFolder ? { mentionPath: (path: string) => joinHostPath(cwd, path) } : {},
);
@@ -332,12 +334,15 @@ export default function FileBrowserPanel({
}
},
paths: [],
- renderRowDecoration: ({ item, row }) =>
- row.kind === "directory" &&
- row.isExpanded &&
- loadingDirectoriesRef.current.has(item.path.replace(/\/$/, ""))
+ renderRowDecoration: ({ item, row }) => {
+ const path = item.path.replace(/\/$/, "");
+ const open = row.kind === "directory" && row.isExpanded;
+ // Pierre calls this for the rows it renders, which is the only sign of what is on screen.
+ revalidateDirectory(open ? path : path.slice(0, Math.max(0, path.lastIndexOf("/"))));
+ return open && loadingDirectoriesRef.current.has(path)
? { icon: "t3-tree-icon-loading", title: gt("Loading…") }
- : null,
+ : null;
+ },
search: false,
onSearchChange: (value) => setQuery(value ?? ""),
unsafeCSS: PIERRE_TREE_UNSAFE_CSS,
@@ -452,15 +457,20 @@ export default function FileBrowserPanel({
}
search.setValue(value);
};
- const handleRefresh = () => {
+ const refreshDirectories = () => {
refresh();
+ // Renders the rows again, so each one on screen revalidates the folders it comes from.
+ model.setComposition(model.getComposition());
+ };
+ const handleRefresh = () => {
+ refreshDirectories();
if (query.trim()) pathSearch.refresh();
onRefreshSelectedFile?.();
};
useWorkspaceMutationRefresh({
mutationId: workspaceMutationId,
refresh: () => {
- refresh();
+ refreshDirectories();
if (query.trim()) pathSearch.refresh();
},
resourceKey: `files:${environmentId}:${cwd}`,
diff --git a/apps/web/src/components/files/fileTreeExpansion.test.ts b/apps/web/src/components/files/fileTreeExpansion.test.ts
new file mode 100644
index 0000000000000..6d8ea1a883b9a
--- /dev/null
+++ b/apps/web/src/components/files/fileTreeExpansion.test.ts
@@ -0,0 +1,10 @@
+import { expect, it } from "vite-plus/test";
+
+import { readExpandedDirectories, writeExpandedDirectories } from "./fileTreeExpansion";
+
+it("keeps the 100 expanded folders nearest the root, so a remount does not list hundreds", () => {
+ const deep = Array.from({ length: 150 }, (_, index) => `pkg/mod/d${index}/`);
+ writeExpandedDirectories("env:/repo", [...deep, "pkg/mod/", "pkg/"]);
+ const restored = readExpandedDirectories("env:/repo");
+ expect(restored).toEqual(["pkg/", "pkg/mod/", ...deep.slice(0, 98)]);
+});
diff --git a/apps/web/src/components/files/fileTreeExpansion.ts b/apps/web/src/components/files/fileTreeExpansion.ts
index 35e6a548603ee..f7055bd1e1b08 100644
--- a/apps/web/src/components/files/fileTreeExpansion.ts
+++ b/apps/web/src/components/files/fileTreeExpansion.ts
@@ -106,6 +106,8 @@ export function coalesceReentrantCalls(run: () => void): () => void {
const EXPANDED_DIRECTORIES_STORAGE_KEY = "t3code.fileTreeExpandedDirectories";
// Roots are kept most recent first and capped so worktrees that come and go do not grow storage.
const MAX_STORED_ROOTS = 20;
+// Every restored folder is listed when the panel mounts, so a root keeps the folders nearest it.
+const MAX_STORED_PATHS_PER_ROOT = 100;
const StoredExpandedDirectories = Schema.Array(
Schema.Struct({ root: Schema.String, paths: Schema.Array(Schema.String) }),
);
@@ -119,13 +121,23 @@ function readStoredExpandedDirectories() {
}
}
+function nearestToRoot(paths: readonly string[]): readonly string[] {
+ if (paths.length <= MAX_STORED_PATHS_PER_ROOT) return paths;
+ const depth = (path: string) => path.split("/").length;
+ return paths
+ .toSorted((left, right) => depth(left) - depth(right))
+ .slice(0, MAX_STORED_PATHS_PER_ROOT);
+}
+
export function readExpandedDirectories(root: string): readonly string[] {
- return readStoredExpandedDirectories().find((entry) => entry.root === root)?.paths ?? [];
+ return nearestToRoot(
+ readStoredExpandedDirectories().find((entry) => entry.root === root)?.paths ?? [],
+ );
}
export function writeExpandedDirectories(root: string, paths: readonly string[]): void {
const others = readStoredExpandedDirectories().filter((entry) => entry.root !== root);
- const next = paths.length > 0 ? [{ root, paths }, ...others] : others;
+ const next = paths.length > 0 ? [{ root, paths: nearestToRoot(paths) }, ...others] : others;
try {
setLocalStorageItem(
EXPANDED_DIRECTORIES_STORAGE_KEY,
diff --git a/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx b/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx
index 694004d0a044d..cee9a88148050 100644
--- a/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx
+++ b/apps/web/src/components/files/useDirectoryEntries.browser.test.tsx
@@ -188,11 +188,15 @@ it("retains the four-query concurrency bound across directories and refreshes",
expect(state.activeQueries).toBe(0);
const refreshStart = state.calls.length;
state.resetPeakQueries();
- await act(async () => state.view.refresh());
+ const refreshOnScreen = () => {
+ state.view.refresh();
+ for (const folder of folders) state.view.revalidate(folder.path);
+ };
+ await act(async () => refreshOnScreen());
expect(state.peakQueries).toBe(4);
expect(state.activeQueries).toBe(4);
await act(async () => {
- for (let index = 0; index < 20; index++) state.view.refresh();
+ for (let index = 0; index < 20; index++) refreshOnScreen();
});
for (let index = refreshStart; index < state.calls.length; index++) {
await state.settle(index, state.calls[index]!.path === "" ? folders : []);
@@ -206,6 +210,40 @@ it("retains the four-query concurrency bound across directories and refreshes",
expect(state.view.isPending).toBe(false);
});
+it("refreshes the root, and another folder only once one of its rows is on screen", async () => {
+ const state = setup();
+ // The hook probe does not navigate.
+ await using _screen = await render( , { router: false });
+ const folders = ["src", "src/ui", "docs"].map((path) => ({ path, kind: "directory" as const }));
+ const listing = (path: string) =>
+ folders.filter((folder) => folder.path.slice(0, folder.path.lastIndexOf("/") + 1) === path);
+ await state.settle(0, listing(""));
+ await act(async () => {
+ for (const folder of folders) void state.view.load(folder.path);
+ });
+ await state.settle(1, listing("src/"));
+ await state.settle(2);
+ await state.settle(3);
+
+ await act(async () => {
+ state.view.refresh();
+ state.view.refresh();
+ });
+ expect(state.calls.slice(4).map((call) => call.path)).toEqual([""]);
+ await act(async () => {
+ state.view.revalidate("src/ui");
+ state.view.revalidate("src/ui");
+ });
+ expect(state.calls.slice(4).map((call) => call.path)).toEqual(["", "src/ui", "src"]);
+ await state.settle(4, listing(""));
+ await state.settle(5);
+ await state.settle(6, listing("src/"));
+ await state.settle(7, listing(""));
+ expect(state.calls).toHaveLength(8); // The second refresh reads the root once more; `docs` is never read.
+ expect(state.view.entries.map((entry) => entry.path)).toEqual(["src", "src/ui", "docs"]);
+ expect(state.view.isPending).toBe(false);
+});
+
it("does not start a queued follow-up after unmount", async () => {
const state = setup();
// The hook probe does not navigate.
diff --git a/apps/web/src/components/files/useDirectoryEntries.ts b/apps/web/src/components/files/useDirectoryEntries.ts
index fc3a984c4788a..ce210315d073c 100644
--- a/apps/web/src/components/files/useDirectoryEntries.ts
+++ b/apps/web/src/components/files/useDirectoryEntries.ts
@@ -25,6 +25,8 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
const followUpRefreshes = useRef(new Map>());
const loaded = useRef(new Set());
const requested = useRef(new Set());
+ // Listed folders a refresh has not read again yet. `revalidate` reads one once it is on screen.
+ const stale = useRef(new Set());
const active = useRef(true);
const running = useRef(0);
const waiting = useRef void>>([]);
@@ -32,6 +34,7 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
const startRequest = (directoryPath: string, refresh: boolean): Promise => {
loaded.current.add(directoryPath);
requested.current.add(directoryPath);
+ stale.current.delete(directoryPath);
const atom = projectEnvironment.listEntries({ environmentId, input: { cwd, directoryPath } });
const detached = detachedRequests.current.get(directoryPath);
const request = (async () => {
@@ -59,6 +62,7 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
(entry) =>
entry.path.slice(0, Math.max(0, entry.path.lastIndexOf("/"))) === directoryPath,
);
+ const listed = listings.current.get(directoryPath);
const next = new Map(listings.current).set(directoryPath, children);
const childDirectories = new Set(
children.filter((entry) => entry.kind === "directory").map((entry) => entry.path),
@@ -73,13 +77,28 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
next.delete(path);
loaded.current.delete(path);
requested.current.delete(path);
+ stale.current.delete(path);
const detachedRequest = requests.current.get(path);
if (detachedRequest) detachedRequests.current.set(path, detachedRequest);
requests.current.delete(path);
followUpRefreshes.current.delete(path);
}
- listings.current = next;
- setDirectories(next);
+ // A refresh that finds a folder as it was publishes nothing, so the tree is not rebuilt.
+ const unchanged =
+ removed.length === 0 &&
+ listed?.length === children.length &&
+ children.every((entry, index) => {
+ const known = listed[index]!;
+ return (
+ entry.path === known.path &&
+ entry.kind === known.kind &&
+ entry.ignored === known.ignored
+ );
+ });
+ if (!unchanged) {
+ listings.current = next;
+ setDirectories(next);
+ }
if (removed.length > 0)
setLoadingDirectories((previous) => {
const remaining = new Set(previous);
@@ -87,8 +106,10 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
return remaining;
});
setErrors((previous) => {
+ const cleared = [directoryPath, ...removed].filter((path) => previous.has(path));
+ if (cleared.length === 0) return previous;
const remaining = new Map(previous);
- for (const path of [directoryPath, ...removed]) remaining.delete(path);
+ for (const path of cleared) remaining.delete(path);
return remaining;
});
} else {
@@ -174,11 +195,24 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
...entries.filter((entry) => entry.kind === "directory").map((entry) => entry.path),
]);
+ // Reads the root again and leaves every other listed folder to `revalidate`, so a refresh costs
+ // what is on screen rather than every folder the tree has listed.
const refresh = () => {
- const paths = [...requested.current].filter((path) => reachableDirectories.has(path));
- for (const path of paths) {
- if (!active.current) break;
- void load(path, true);
+ if (!active.current) return;
+ for (const path of requested.current) if (path !== "") stale.current.add(path);
+ void load("", true);
+ };
+
+ /** Reads again the stale listings that put a row on screen: `directoryPath` and its ancestors. */
+ const revalidate = (directoryPath: string) => {
+ if (!active.current) return;
+ for (
+ let end = directoryPath.length;
+ end > 0 && stale.current.size > 0;
+ end = directoryPath.lastIndexOf("/", end - 1)
+ ) {
+ const path = directoryPath.slice(0, end);
+ if (stale.current.delete(path)) void load(path, true);
}
};
@@ -186,6 +220,7 @@ export function useDirectoryEntries(environmentId: EnvironmentId, cwd: string) {
entries,
load,
refresh,
+ revalidate,
isPending: pending > 0,
loadingDirectories,
ready: directories.has(""),
From 8783b9d2eaaf102dfd7374eef2ecc75c4b754907 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 06:45:53 -0800
Subject: [PATCH 039/238] fix(web): Restart agent session toast says the
conversation is kept (#42880)
---
apps/web/src/components/CommandPalette.tsx | 2 +-
apps/web/src/i18n/translations/de.json | 2 +-
apps/web/src/i18n/translations/en.json | 2 +-
apps/web/src/i18n/translations/es.json | 2 +-
apps/web/src/i18n/translations/fr.json | 2 +-
apps/web/src/i18n/translations/ja.json | 2 +-
apps/web/src/i18n/translations/ko.json | 2 +-
apps/web/src/i18n/translations/pt-BR.json | 2 +-
apps/web/src/i18n/translations/ru.json | 2 +-
apps/web/src/i18n/translations/sv.json | 2 +-
apps/web/src/i18n/translations/zh.json | 2 +-
11 files changed, 11 insertions(+), 11 deletions(-)
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index cf8edc293b7b0..745b96bcdb549 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -1580,7 +1580,7 @@ function OpenCommandPaletteDialog(props: {
toastManager.add({
type: "success",
title: gt("Agent session will restart"),
- description: gt("Your next message starts a fresh session."),
+ description: gt("Your next message restarts the agent. This conversation is kept."),
});
const project = projectByKey.get(`${environmentId}:${thread.projectId}`);
if (!project) return;
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json
index 2f8bb9a78f29e..13ca3148353ec 100644
--- a/apps/web/src/i18n/translations/de.json
+++ b/apps/web/src/i18n/translations/de.json
@@ -1855,7 +1855,7 @@
"67f5b13c3c7bcd40": "Mit Gast teilen",
"82da5b8b340217ac": "Agentensitzung neu starten",
"963d099509eabcd6": "Die Agentensitzung wird neu gestartet",
- "1d384d4fe7888a09": "Deine nächste Nachricht startet eine neue Sitzung.",
+ "71ed7c0da0b93c77": "Deine nächste Nachricht startet den Agenten neu. Diese Unterhaltung bleibt erhalten.",
"e4b61c891fed297e": "Gehe zu Datei",
"d2ccdb8cd3297212": "Projekt hinzufügen",
"594bcbef04093f72": "WSL-Ordner öffnen",
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index 344891fe62609..373a74dcb3037 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -1856,7 +1856,7 @@
"67f5b13c3c7bcd40": "Share with guest",
"82da5b8b340217ac": "Restart agent session",
"963d099509eabcd6": "Agent session will restart",
- "1d384d4fe7888a09": "Your next message starts a fresh session.",
+ "71ed7c0da0b93c77": "Your next message restarts the agent. This conversation is kept.",
"e4b61c891fed297e": "Go to file",
"d2ccdb8cd3297212": "Add project",
"594bcbef04093f72": "Open WSL folder",
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index 38ae9dc156ebc..907459e4af8cf 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -1856,7 +1856,7 @@
"67f5b13c3c7bcd40": "Compartir con un invitado",
"82da5b8b340217ac": "Reiniciar sesión del agente",
"963d099509eabcd6": "La sesión del agente se reiniciará",
- "1d384d4fe7888a09": "Tu próximo mensaje inicia una sesión nueva.",
+ "71ed7c0da0b93c77": "Tu próximo mensaje reinicia el agente. Esta conversación se conserva.",
"e4b61c891fed297e": "Ir al archivo",
"d2ccdb8cd3297212": "Añadir proyecto",
"594bcbef04093f72": "Abrir carpeta de WSL",
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index 57cc6f526c041..8b299a8bb964e 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -1856,7 +1856,7 @@
"67f5b13c3c7bcd40": "Partager avec un invité",
"82da5b8b340217ac": "Redémarrer la session de l’agent",
"963d099509eabcd6": "La session de l’agent va redémarrer",
- "1d384d4fe7888a09": "Votre prochain message démarre une nouvelle session.",
+ "71ed7c0da0b93c77": "Votre prochain message redémarre l’agent. Cette conversation est conservée.",
"e4b61c891fed297e": "Aller au fichier",
"d2ccdb8cd3297212": "Ajouter un projet",
"594bcbef04093f72": "Ouvrir un dossier WSL",
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index 5a48ea70d7abc..969229a89006d 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -1855,7 +1855,7 @@
"67f5b13c3c7bcd40": "ゲストと共有",
"82da5b8b340217ac": "エージェントのセッションを再起動",
"963d099509eabcd6": "エージェントのセッションが再起動されます",
- "1d384d4fe7888a09": "次のメッセージで新しいセッションが始まります。",
+ "71ed7c0da0b93c77": "次のメッセージでエージェントが再起動します。この会話はそのまま残ります。",
"e4b61c891fed297e": "ファイルに移動",
"d2ccdb8cd3297212": "プロジェクトを追加",
"594bcbef04093f72": "WSL のフォルダーを開く",
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index bdec1db133159..85d3f4d351ad7 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -1855,7 +1855,7 @@
"67f5b13c3c7bcd40": "게스트와 공유",
"82da5b8b340217ac": "에이전트 세션 다시 시작",
"963d099509eabcd6": "에이전트 세션이 다시 시작됩니다",
- "1d384d4fe7888a09": "다음 메시지부터 새 세션이 시작됩니다.",
+ "71ed7c0da0b93c77": "다음 메시지를 보내면 에이전트가 다시 시작됩니다. 이 대화는 유지됩니다.",
"e4b61c891fed297e": "파일로 이동",
"d2ccdb8cd3297212": "프로젝트 추가",
"594bcbef04093f72": "WSL 폴더 열기",
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index 20baf91f8b106..9819cb6981ca0 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -1856,7 +1856,7 @@
"67f5b13c3c7bcd40": "Compartilhar com convidado",
"82da5b8b340217ac": "Reiniciar a sessão do agente",
"963d099509eabcd6": "A sessão do agente será reiniciada",
- "1d384d4fe7888a09": "Sua próxima mensagem inicia uma nova sessão.",
+ "71ed7c0da0b93c77": "Sua próxima mensagem reinicia o agente. Esta conversa é mantida.",
"e4b61c891fed297e": "Ir para arquivo",
"d2ccdb8cd3297212": "Adicionar projeto",
"594bcbef04093f72": "Abrir pasta do WSL",
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index 1f58942bc5cfc..4b1d3c7a46f54 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -1856,7 +1856,7 @@
"67f5b13c3c7bcd40": "Поделиться с гостем",
"82da5b8b340217ac": "Перезапустить сеанс агента",
"963d099509eabcd6": "Сеанс агента будет перезапущен",
- "1d384d4fe7888a09": "Следующее сообщение начнёт новый сеанс.",
+ "71ed7c0da0b93c77": "Следующее сообщение перезапустит агента. Эта беседа сохранится.",
"e4b61c891fed297e": "Перейти к файлу",
"d2ccdb8cd3297212": "Добавить проект",
"594bcbef04093f72": "Открыть папку WSL",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index c7370bb2ec772..734f2a2cdee3f 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -1856,7 +1856,7 @@
"67f5b13c3c7bcd40": "Dela med gäst",
"82da5b8b340217ac": "Starta om agentsessionen",
"963d099509eabcd6": "Agentsessionen startas om",
- "1d384d4fe7888a09": "Ditt nästa meddelande startar en ny session.",
+ "71ed7c0da0b93c77": "Ditt nästa meddelande startar om agenten. Den här konversationen behålls.",
"e4b61c891fed297e": "Gå till fil",
"d2ccdb8cd3297212": "Lägg till projekt",
"594bcbef04093f72": "Öppna WSL-mapp",
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index 98276b6809237..c8c51048fd5e2 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -1856,7 +1856,7 @@
"67f5b13c3c7bcd40": "与访客共享",
"82da5b8b340217ac": "重启智能体会话",
"963d099509eabcd6": "智能体会话将重启",
- "1d384d4fe7888a09": "你的下一条消息将以全新上下文开始。",
+ "71ed7c0da0b93c77": "你的下一条消息将重启智能体,当前对话会保留。",
"e4b61c891fed297e": "转到文件",
"d2ccdb8cd3297212": "添加项目",
"594bcbef04093f72": "打开 WSL 文件夹",
From 9301770ae9e595a65e23d83702b86121c380e919 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 06:46:10 -0800
Subject: [PATCH 040/238] fix(mobile): / menu ranks an exact skill name above
description matches (#42879)
---
.../threads/composerSlashSkillSearch.ts | 47 ++++++++++++++++---
.../use-composer-command-menu.select.test.tsx | 43 +++++++++++++++++
.../threads/use-composer-command-menu.ts | 10 ++--
3 files changed, 91 insertions(+), 9 deletions(-)
diff --git a/apps/mobile/src/features/threads/composerSlashSkillSearch.ts b/apps/mobile/src/features/threads/composerSlashSkillSearch.ts
index 7cd81f036fdd4..ed6ff7ae909ec 100644
--- a/apps/mobile/src/features/threads/composerSlashSkillSearch.ts
+++ b/apps/mobile/src/features/threads/composerSlashSkillSearch.ts
@@ -1,7 +1,9 @@
import type { ServerProviderSkill } from "@t3tools/contracts";
+import { scoreQueryMatch } from "@t3tools/shared/searchRanking";
-export function matchesSlashSkillQuery(skill: ServerProviderSkill, query: string): boolean {
- if (!skill.enabled) return false;
+/** Lower is better; `null` when the skill does not match. */
+export function scoreSlashSkillQuery(skill: ServerProviderSkill, query: string): number | null {
+ if (!skill.enabled) return null;
const normalizedQuery = query.toLowerCase();
const skillQuery =
normalizedQuery === "skill"
@@ -9,8 +11,41 @@ export function matchesSlashSkillQuery(skill: ServerProviderSkill, query: string
: normalizedQuery.startsWith("skill:")
? normalizedQuery.slice("skill:".length)
: normalizedQuery;
- if (!skillQuery) return true;
- return [skill.name, skill.displayName, skill.shortDescription, skill.description].some((value) =>
- value?.toLowerCase().includes(skillQuery),
- );
+ if (!skillQuery) return 0;
+ const scores = [
+ scoreQueryMatch({
+ value: skill.name.toLowerCase(),
+ query: skillQuery,
+ exactBase: 0,
+ prefixBase: 2,
+ boundaryBase: 4,
+ includesBase: 6,
+ boundaryMarkers: ["-", "_", "/"],
+ }),
+ scoreQueryMatch({
+ value: skill.displayName?.toLowerCase() ?? "",
+ query: skillQuery,
+ exactBase: 1,
+ prefixBase: 3,
+ boundaryBase: 5,
+ includesBase: 7,
+ }),
+ scoreQueryMatch({
+ value: skill.shortDescription?.toLowerCase() ?? "",
+ query: skillQuery,
+ exactBase: 20,
+ prefixBase: 22,
+ boundaryBase: 24,
+ includesBase: 26,
+ }),
+ scoreQueryMatch({
+ value: skill.description?.toLowerCase() ?? "",
+ query: skillQuery,
+ exactBase: 30,
+ prefixBase: 32,
+ boundaryBase: 34,
+ includesBase: 36,
+ }),
+ ].filter((score): score is number => score !== null);
+ return scores.length > 0 ? Math.min(...scores) : null;
}
diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx b/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx
index 395961bd91ec7..21e5a88f82fdb 100644
--- a/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx
+++ b/apps/mobile/src/features/threads/use-composer-command-menu.select.test.tsx
@@ -53,3 +53,46 @@ it("/model clears only its trigger and opens the model picker", async () => {
expect(onChangeDraftMessage).toHaveBeenCalledWith("fix this ");
act(() => root.unmount());
});
+
+it("/ ranks a skill whose name matches exactly above skills that only mention it", async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ const skill = (name: string, description: string) => ({
+ name,
+ description,
+ path: `/skills/${name}/SKILL.md`,
+ enabled: true,
+ });
+ const provider = {
+ instanceId: "codex",
+ driver: "codex",
+ slashCommands: [],
+ skills: [
+ skill("lint", "Run lint before review"),
+ skill("ship", "Open a pull request after review"),
+ skill("review", "Review the current diff"),
+ ],
+ } as unknown as NonNullable<
+ Parameters[0]["selectedProviderStatus"]
+ >;
+ let menu: ReturnType | undefined;
+ function Probe() {
+ menu = useComposerCommandMenu({
+ draftMessage: "/review",
+ ownerKey: "draft",
+ environmentId: null,
+ projectCwd: null,
+ selectedProviderStatus: provider,
+ hasThread: true,
+ hasCompactableConversation: false,
+ onChangeDraftMessage: vi.fn(),
+ onOpenModelPicker: vi.fn(),
+ });
+ return null;
+ }
+
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render( ));
+
+ expect(menu?.items[0]?.id).toBe("skill:review");
+ act(() => root.unmount());
+});
diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.ts
index b5b6ce681c018..3fa3e9d8860b0 100644
--- a/apps/mobile/src/features/threads/use-composer-command-menu.ts
+++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts
@@ -68,7 +68,7 @@ import {
import type { ModelOption } from "../../lib/modelOptions";
import { m, type MessageResolver } from "../../i18n/messages";
import type { ComposerCommandItem } from "./ComposerCommandPopover";
-import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";
+import { scoreSlashSkillQuery } from "./composerSlashSkillSearch";
const idleWorkspaceSnapshotRefreshAtom: Atom.Atom = Atom.make(undefined).pipe(
Atom.withLabel("mobile:provider-workspace-snapshot-refresh:idle"),
@@ -422,8 +422,12 @@ export function useComposerCommandMenu({
);
const skillItems = visibleSkills
- .filter((skill) => matchesSlashSkillQuery(skill, q))
- .map((skill) => ({
+ .flatMap((skill) => {
+ const score = scoreSlashSkillQuery(skill, q);
+ return score === null ? [] : [{ skill, score }];
+ })
+ .sort((left, right) => left.score - right.score)
+ .map(({ skill }) => ({
id: `skill:${skill.name}`,
type: "skill" as const,
skill,
From 80cac28f5ad31fbf7e3d07dcfacf023b0d38a96d Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 08:50:57 -0600
Subject: [PATCH 041/238] fix(server): EPUB attachment text no longer includes
hidden passages (#42871)
Co-authored-by: Julius Marminge
---
apps/server/src/provider/documentTextWorker.ts | 6 +++++-
.../src/provider/userInputAttachments.test.ts | 16 +++++++++++++---
2 files changed, 18 insertions(+), 4 deletions(-)
diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts
index 230e5d22c144c..4c4504a8b6024 100644
--- a/apps/server/src/provider/documentTextWorker.ts
+++ b/apps/server/src/provider/documentTextWorker.ts
@@ -110,11 +110,15 @@ function xml(source: string, extension: string): XmlNode {
stack.at(-1)!.children.push(node);
stack.push(node);
});
- parser.on("closetag", () => {
+ parser.on("closetag", (tag) => {
const node = stack.pop()!;
const parent = stack.at(-1)!;
if (odf && (node.name === "p" || node.name === "h")) collapseOdfWhitespace(node);
if (
+ (extension === ".epub" &&
+ (stack[1] ?? node).name === "html" &&
+ Object.hasOwn(tag.attributes, "hidden") &&
+ !/^until-found$/i.test(String(tag.attributes.hidden))) ||
(extension === ".docx" && node.name === "del") ||
(extension === ".docx" &&
node.name === "r" &&
diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts
index 6aad293a35ec9..ea61fab1ce990 100644
--- a/apps/server/src/provider/userInputAttachments.test.ts
+++ b/apps/server/src/provider/userInputAttachments.test.ts
@@ -1493,11 +1493,12 @@ describe("question answer paths", () => {
"META-INF/container.xml":
' ',
"OEBPS/book.opf":
- ' ',
+ ' ',
"OEBPS/a.xhtml":
'Last chapter
Price 10 8 old
',
"OEBPS/b.xhtml":
- 'My Novel First chapter Larkspur
Direct divDirect sectionDirect item emphasis trailing
Account: A Balance: 731 Currency: USD
Heading Total Important value 731 BeforeAfter Neighbor
Port 443 Timeout 30 seconds ',
+ 'My Novel First chapter Larkspur
Direct divDirect sectionDirect item emphasis trailing
Account: A Balance: 731 Currency: USD
Heading Total Important value 731 BeforeAfter Neighbor
Port 443 Timeout 30 seconds Draft note
Hidden block
Hidden nested
Findable note
Decorative note
Prefixed note
',
+ "OEBPS/c.xhtml": 'Root hidden
',
},
expected: [
"## Chapter 1",
@@ -1511,11 +1512,20 @@ describe("question answer paths", () => {
"Important value\t731",
"Before Inner After\tNeighbor",
"Port\n443\nTimeout\n30 seconds",
+ "Findable note\nDecorative note\nPrefixed note",
"## Chapter 2",
"Last chapter",
"Price 10 8 old",
+ "## Chapter 3",
+ ],
+ absent: [
+ "My Novel",
+ "Hidden Author",
+ "Draft note",
+ "Hidden block",
+ "Hidden nested",
+ "Root hidden",
],
- absent: ["My Novel", "Hidden Author"],
},
];
for (const [caseIndex, item] of cases.entries()) {
From 45c011e218dccbb8d02c5408d00c6011ee07b9ec Mon Sep 17 00:00:00 2001
From: AymanKhan9
Date: Wed, 25 Nov 2026 20:21:10 +0530
Subject: [PATCH 042/238] fix(web): reopening a closed pull request tab keeps
saved list filters (#42875)
Co-authored-by: Julius Marminge
---
.../ReopenClosedViewShortcut.browser.test.tsx | 63 +++++++++++++++++++
.../components/ReopenClosedViewShortcut.tsx | 3 +-
apps/web/src/reopenClosedView.ts | 48 ++++----------
3 files changed, 78 insertions(+), 36 deletions(-)
diff --git a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx
index 3298af7822c89..a7b2d712239db 100644
--- a/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx
+++ b/apps/web/src/components/ReopenClosedViewShortcut.browser.test.tsx
@@ -85,10 +85,12 @@ vi.mock(import("./ui/toast"), async (original) => {
import { useClosedViewStore } from "../closedViewStore";
import {
ISSUES_PANEL_REF,
+ PULL_REQUESTS_PANEL_REF,
selectThreadRightPanelState,
useRightPanelStore,
} from "../rightPanelStore";
import { useTerminalUiStateStore } from "../terminalUiStateStore";
+import { writePullRequestListPreferences } from "./pullRequest/pullRequestListPreferences";
import { ReopenClosedViewShortcut } from "./ReopenClosedViewShortcut";
const ref = { environmentId: "remote", threadId: "thread-1" } as ScopedThreadRef;
@@ -400,6 +402,67 @@ describe("root reopen shortcut", () => {
);
});
+ it("reopens a closed pull request tab from another route with saved list preferences and no foreign search params", async () => {
+ setup();
+ window.localStorage.removeItem("t3.pullRequests.preferences");
+ using _cleanup = {
+ [Symbol.dispose]: () => window.localStorage.removeItem("t3.pullRequests.preferences"),
+ };
+ writePullRequestListPreferences({ involvement: "reviewing", state: "merged" });
+ useClosedViewStore.getState().remember({
+ kind: "panel-tab",
+ threadRef: PULL_REQUESTS_PANEL_REF,
+ surface: {
+ id: "pull-request:remote:project-1:github.com:pingdotgg/t3code#42",
+ kind: "pull-request",
+ environmentId: "remote",
+ projectId: "project-1",
+ host: "github.com",
+ repository: "pingdotgg/t3code",
+ number: 42,
+ },
+ });
+
+ const history = createMemoryHistory({
+ initialEntries: [
+ "/issues?who=assigned&status=closed&q=login&host=linear.app&tracker=linear&scope=ENG&key=ENG-12",
+ ],
+ });
+ const root = createRootRoute({
+ component: () => (
+ <>
+
+
+ >
+ ),
+ });
+ const router = createRouter({
+ history,
+ routeTree: root.addChildren([
+ createRoute({ getParentRoute: () => root, path: "issues" }),
+ createRoute({ getParentRoute: () => root, path: "pull-requests" }),
+ ]),
+ });
+ state.navigate.mockImplementation(router.navigate);
+ using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
+ await using _view = await render( , { router: false });
+
+ await act(() => {
+ press();
+ });
+
+ expect(router.state.location.pathname).toBe("/pull-requests");
+ expect(router.state.location.search).toEqual({
+ involvement: "reviewing",
+ state: "merged",
+ repository: "pingdotgg/t3code",
+ number: 42,
+ selectedProjectId: "project-1",
+ selectedHost: "github.com",
+ selectedEnvironmentId: "remote",
+ });
+ });
+
it("forwards address-bar focus, zoom, and panel new and close from a focused desktop page", async () => {
setup();
await using _shortcut = await renderShortcut();
diff --git a/apps/web/src/components/ReopenClosedViewShortcut.tsx b/apps/web/src/components/ReopenClosedViewShortcut.tsx
index 7fa558148e611..40b5d40b44cce 100644
--- a/apps/web/src/components/ReopenClosedViewShortcut.tsx
+++ b/apps/web/src/components/ReopenClosedViewShortcut.tsx
@@ -49,6 +49,7 @@ import {
} from "../threadRoutes";
import { toastManager } from "./ui/toast";
import { readIssueListPreferences } from "./issue/issueListPreferences";
+import { readPullRequestListPreferences } from "./pullRequest/pullRequestListPreferences";
declare module "@tanstack/react-router" {
interface HistoryState {
@@ -163,7 +164,7 @@ export function ReopenClosedViewShortcut() {
destination = globalPullRequests
? linkOptions({
to: "/pull-requests",
- search: (previous) => pullRequestsSearchForRestore(previous, selected),
+ search: pullRequestsSearchForRestore(readPullRequestListPreferences(), selected),
})
: linkOptions({
to: "/issues",
diff --git a/apps/web/src/reopenClosedView.ts b/apps/web/src/reopenClosedView.ts
index 69cedab7cbf80..96d263050fa1a 100644
--- a/apps/web/src/reopenClosedView.ts
+++ b/apps/web/src/reopenClosedView.ts
@@ -2,7 +2,6 @@ import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import type { OpenPreviewMutation } from "./browser/openFileInPreview";
import type { ClosedView, ClosedViewEntry } from "./closedViewStore";
-import type { PullRequestListPreferences } from "./components/pullRequest/pullRequestListPreferences";
import { openPreviewSession } from "./components/preview/openPreviewSession";
import {
rightPanelHostRef,
@@ -53,42 +52,21 @@ export function planNextReopen(
return { drop, restore: null };
}
-type PullRequestsSearchLike = Partial & {
- repository?: string;
- number?: number;
- selectedProjectId?: ProjectId | undefined;
- selectedHost?: string | undefined;
- selectedEnvironmentId?: EnvironmentId | undefined;
-};
-
-export function pullRequestsSearchForRestore(
- previous: S,
+export function pullRequestsSearchForRestore(
+ preferences: S,
selected: RightPanelSurface | null,
-): S & PullRequestListPreferences {
- const {
- repository: _repository,
- number: _number,
- selectedProjectId: _projectId,
- selectedHost: _host,
- selectedEnvironmentId: _environmentId,
- ...filters
- } = previous;
+) {
+ if (selected?.kind !== "pull-request") return preferences;
return {
- ...filters,
- involvement: previous.involvement ?? "all",
- state: previous.state ?? "open",
- ...(selected?.kind === "pull-request"
- ? {
- repository: selected.repository,
- number: selected.number,
- selectedProjectId: selected.projectId as ProjectId,
- ...(selected.host === undefined ? {} : { selectedHost: selected.host }),
- ...(selected.environmentId === undefined
- ? {}
- : { selectedEnvironmentId: selected.environmentId as EnvironmentId }),
- }
- : {}),
- } as S & PullRequestListPreferences;
+ ...preferences,
+ repository: selected.repository,
+ number: selected.number,
+ selectedProjectId: selected.projectId as ProjectId,
+ ...(selected.host === undefined ? {} : { selectedHost: selected.host }),
+ ...(selected.environmentId === undefined
+ ? {}
+ : { selectedEnvironmentId: selected.environmentId as EnvironmentId }),
+ };
}
export function issuesSearchForRestore(
From b61af8a5d2af5e514674bd85fe5a62e4ea8f9918 Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 08:51:24 -0600
Subject: [PATCH 043/238] fix(web,mobile): mixed add/delete review selections
no longer show backwards line ranges (#42863)
Co-authored-by: Julius Marminge
---
.../review/ReviewCommentComposerSheet.tsx | 2 +-
.../review/reviewCommentSelection.test.ts | 35 +++++++++++++++
.../features/review/reviewCommentSelection.ts | 2 +-
apps/web/src/reviewCommentContext.test.ts | 45 +++++++++++++++++++
apps/web/src/reviewCommentContext.ts | 2 +-
5 files changed, 83 insertions(+), 3 deletions(-)
diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
index 881f67e86648f..2802319289270 100644
--- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
+++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx
@@ -100,7 +100,7 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp
? firstNumber !== null
? gt("Line {line}", { line: firstNumber })
: gt("File comment")
- : firstNumber !== null && lastNumber !== null
+ : firstNumber !== null && lastNumber !== null && firstNumber < lastNumber
? gt("Lines {first}-{last}", { first: firstNumber, last: lastNumber })
: gt("{count, plural, one {{count} lines selected} other {{count} lines selected}}", {
count: selectedLines.length,
diff --git a/apps/mobile/src/features/review/reviewCommentSelection.test.ts b/apps/mobile/src/features/review/reviewCommentSelection.test.ts
index 81eb0bba4083a..e5c3e17e92e59 100644
--- a/apps/mobile/src/features/review/reviewCommentSelection.test.ts
+++ b/apps/mobile/src/features/review/reviewCommentSelection.test.ts
@@ -8,6 +8,7 @@ import {
clearReviewCommentTarget,
completeReviewCommentRange,
formatReviewCommentContext,
+ formatReviewSelectedRangeLabel,
getReviewCommentSelection,
reviewCommentSelectionScope,
selectReviewCommentSelection,
@@ -224,6 +225,40 @@ describe("review comment serialization", () => {
});
});
+describe("review selected range label", () => {
+ it("falls back to line count when unified endpoints decrease across old and new numbers", () => {
+ expect(
+ formatReviewSelectedRangeLabel({
+ ...makeTarget(),
+ lines: [
+ {
+ kind: "line",
+ id: "line-1",
+ change: "context",
+ oldLineNumber: 10,
+ newLineNumber: 13,
+ content: "line 10 of the original file",
+ additionTokenIndex: null,
+ deletionTokenIndex: null,
+ comparison: null,
+ },
+ {
+ kind: "line",
+ id: "line-2",
+ change: "delete",
+ oldLineNumber: 11,
+ newLineNumber: null,
+ content: "line 11 of the original file",
+ additionTokenIndex: null,
+ deletionTokenIndex: 0,
+ comparison: null,
+ },
+ ],
+ }),
+ ).toBe("2 lines");
+ });
+});
+
describe("review comment selection store", () => {
const changes = { id: "git:branch-range", content: "hash-1" };
const scope = reviewCommentSelectionScope(1, "env:thread", changes)!;
diff --git a/apps/mobile/src/features/review/reviewCommentSelection.ts b/apps/mobile/src/features/review/reviewCommentSelection.ts
index b5f852331acec..741f330375d3f 100644
--- a/apps/mobile/src/features/review/reviewCommentSelection.ts
+++ b/apps/mobile/src/features/review/reviewCommentSelection.ts
@@ -212,7 +212,7 @@ export function formatReviewSelectedRangeLabel(target: ReviewCommentTarget): str
const firstNumber = getReviewUnifiedLineNumber(firstLine);
const lastNumber = getReviewUnifiedLineNumber(lastLine);
- if (firstNumber === null || lastNumber === null) {
+ if (firstNumber === null || lastNumber === null || firstNumber > lastNumber) {
return lines.length === 1 ? "line" : `${lines.length} lines`;
}
diff --git a/apps/web/src/reviewCommentContext.test.ts b/apps/web/src/reviewCommentContext.test.ts
index a92e3c7ceb5df..486b77248dfce 100644
--- a/apps/web/src/reviewCommentContext.test.ts
+++ b/apps/web/src/reviewCommentContext.test.ts
@@ -85,6 +85,51 @@ describe("review comment context parsing", () => {
expect(new Set(ids).size).toBe(ids.length);
});
+ it("falls back to a line-count label when mixed diff-side line numbers decrease", () => {
+ const [fileDiff] = parsePatchFiles(
+ [
+ "diff --git a/notes.txt b/notes.txt",
+ "--- a/notes.txt",
+ "+++ b/notes.txt",
+ "@@ -1,3 +1,6 @@",
+ "+added A",
+ "+added B",
+ "+added C",
+ " line 1",
+ " line 2",
+ " line 3",
+ "@@ -8,4 +11,3 @@",
+ " line 8",
+ " line 9",
+ " line 10",
+ "-line 11",
+ ].join("\n"),
+ { cacheKeyPrefix: "review-comment-test" },
+ )[0]!.files;
+
+ const comment = buildDiffReviewComment({
+ id: "comment-inverted",
+ sectionId: "turn:2",
+ sectionTitle: "Turn 2",
+ filePath: "notes.txt",
+ fileDiff: fileDiff!,
+ range: {
+ start: 13,
+ side: "additions",
+ end: 11,
+ endSide: "deletions",
+ },
+ text: "Check this deletion.",
+ });
+
+ expect(comment).toEqual(
+ expect.objectContaining({
+ rangeLabel: "2 lines",
+ diff: "@@ -10,2 +13,1 @@\n line 10\n-line 11",
+ }),
+ );
+ });
+
it("keeps a selection's trailing blank line and whitespace in the rendered excerpt", () => {
const fileDiff = parsePatchFiles(
[
diff --git a/apps/web/src/reviewCommentContext.ts b/apps/web/src/reviewCommentContext.ts
index 81b51fd7a1bf7..a4f3f93e51053 100644
--- a/apps/web/src/reviewCommentContext.ts
+++ b/apps/web/src/reviewCommentContext.ts
@@ -440,7 +440,7 @@ function formatDiffReviewRangeLabel(lines: ReadonlyArray): strin
if (!firstLine || !lastLine) return "line";
const firstNumber = firstLine.newLineNumber ?? firstLine.oldLineNumber;
const lastNumber = lastLine.newLineNumber ?? lastLine.oldLineNumber;
- if (firstNumber === null || lastNumber === null) {
+ if (firstNumber === null || lastNumber === null || firstNumber > lastNumber) {
return lines.length === 1 ? "line" : `${lines.length} lines`;
}
From b4a5a4927f371c5e6a9108f56f1c7884b510be79 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 07:28:53 -0800
Subject: [PATCH 044/238] fix(web): reading position survives a panel resize
right after a thread opens (#42915)
---
.../preserveReadingPosition.browser.test.ts | 35 +++++++++++++++++++
apps/web/src/lib/preserveReadingPosition.ts | 5 +--
2 files changed, 38 insertions(+), 2 deletions(-)
create mode 100644 apps/web/src/lib/preserveReadingPosition.browser.test.ts
diff --git a/apps/web/src/lib/preserveReadingPosition.browser.test.ts b/apps/web/src/lib/preserveReadingPosition.browser.test.ts
new file mode 100644
index 0000000000000..0884531b7d182
--- /dev/null
+++ b/apps/web/src/lib/preserveReadingPosition.browser.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it, onTestFinished, vi } from "vite-plus/test";
+
+import { preserveReadingPosition } from "./preserveReadingPosition";
+
+describe("preserveReadingPosition", () => {
+ it("keeps the reader's line through a resize that lands before the first layout report", async () => {
+ const scroller = document.createElement("div");
+ scroller.style.cssText =
+ "width: 600px; height: 300px; overflow-y: auto; font: 16px/20px serif;";
+ // The marker fits one line at both widths, so whichever caret the probe picks shares its top.
+ scroller.innerHTML = Array.from({ length: 30 }, (_, index) =>
+ index === 15
+ ? "Marker line.
"
+ : `${"Filler words that wrap across several lines. ".repeat(8)}
`,
+ ).join("");
+ document.body.append(scroller);
+ onTestFinished(() => scroller.remove());
+ const markerText = [...scroller.querySelectorAll("p")][15]!.firstChild!;
+ const markerTop = () => {
+ const range = document.createRange();
+ range.setStart(markerText, 0);
+ range.collapse(true);
+ return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
+ };
+
+ const stop = preserveReadingPosition(scroller);
+ onTestFinished(stop);
+ scroller.scrollTop += markerTop() - 24;
+ scroller.dispatchEvent(new Event("scroll"));
+ const before = markerTop();
+ scroller.style.width = "300px";
+
+ await vi.waitFor(() => expect(Math.abs(markerTop() - before)).toBeLessThan(2));
+ });
+});
diff --git a/apps/web/src/lib/preserveReadingPosition.ts b/apps/web/src/lib/preserveReadingPosition.ts
index a80f13a85a494..1f8b2fdd8df56 100644
--- a/apps/web/src/lib/preserveReadingPosition.ts
+++ b/apps/web/src/lib/preserveReadingPosition.ts
@@ -5,13 +5,14 @@ export function preserveReadingPosition(
scroller: HTMLElement,
enabled: () => boolean = () => true,
): () => void {
- // Seeded by the observer's first report, which follows the browser's own layout; reading it
- // here would force a layout mid-commit.
+ // Seeded by the observer's first report or an earlier scroll, never read here: that would force
+ // a layout mid-commit. A resize before either is not corrected.
let width: number | null = null;
let anchor: { range: Range; top: number } | null = null;
let frame: number | null = null;
const capture = () => {
+ width ??= scroller.clientWidth;
if (frame !== null || scroller.clientWidth !== width) return;
anchor = null;
if (!enabled() || scroller.scrollTop === 0) return;
From e045a127e783c41b7ed91fcbc1d17810c7b8c459 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 07:33:57 -0800
Subject: [PATCH 045/238] fix(web): web search result links follow Open links
in (#42882)
---
.../chat/MessagesTimeline.browser.test.tsx | 57 +++++++++++++++++++
.../src/components/chat/V2ItemInspector.tsx | 56 +++++++++++++++---
2 files changed, 106 insertions(+), 7 deletions(-)
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index b31558c2a38ba..4009d7159f0f0 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -29,6 +29,7 @@ import {
import * as DateTime from "effect/DateTime";
import { Atom, AsyncResult } from "effect/reactivity";
import { describe, expect, it, onTestFinished, vi } from "vite-plus/test";
+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
import "~/index.css";
@@ -54,6 +55,7 @@ import { searchableMessageSegments } from "@t3tools/shared/threadFindText";
import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch";
import { collectThreadFindRanges } from "./threadFindHighlights";
import { toastManager } from "../ui/toast";
+import { __setClientSettingsForTests } from "../../hooks/useSettings";
import type { CitedHistory } from "./citationProcedure";
import type { TimelineNavigation } from "./timelineViewport";
import { rememberTimelinePosition } from "./timelineScrollAnchoring";
@@ -98,6 +100,26 @@ vi.mock(import("~/assets/assetUrls"), async (original) => {
};
});
+const previewAccess = vi.hoisted(() => ({ granted: false }));
+vi.mock(import("~/browser/previewRuntime"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ isPreviewAvailableFor: ((...args) =>
+ previewAccess.granted ||
+ actual.isPreviewAvailableFor(...args)) as typeof actual.isPreviewAvailableFor,
+ };
+});
+vi.mock(import("~/state/session"), async (original) => {
+ const actual = await original();
+ return {
+ ...actual,
+ readEnvironmentScope: ((...args) =>
+ previewAccess.granted ||
+ actual.readEnvironmentScope(...args)) as typeof actual.readEnvironmentScope,
+ };
+});
+
const ENVIRONMENT_ID = EnvironmentId.make("environment-local");
const CREATED_AT = "2026-03-17T19:12:28.000Z";
@@ -481,6 +503,41 @@ describe("MessagesTimeline work rows", () => {
expect(output!.closest('[role="button"]')).toBeNull();
expect(document.getElementById(toggle.getAttribute("aria-controls") ?? "")).toContain(output);
});
+ it("opens a web search result in the thread's Browser when links open in T3 Code", async () => {
+ setup();
+ previewAccess.granted = true;
+ __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, browserLinkTarget: "app" });
+ onTestFinished(() => {
+ previewAccess.granted = false;
+ __setClientSettingsForTests(DEFAULT_CLIENT_SETTINGS);
+ });
+ await using screen = await renderTimeline([
+ work("web-search", {
+ label: "https://example.com/",
+ tone: "tool",
+ itemType: "web_search",
+ projectedItem: v2Item("web_search", {
+ id: "web-search",
+ patterns: ["https://example.com/"],
+ results: [{ url: "https://example.com/", title: "Example Domain" }],
+ }),
+ }),
+ ]);
+ await click(screen.button("Web search"));
+ const link = [...screen.container.querySelectorAll("a")].find(
+ (anchor) => anchor.textContent === "Example Domain",
+ );
+ expect(link).toBeDefined();
+ // A _blank click the app leaves to the browser goes to Electron's popup handler, which
+ // sends it to the system browser.
+ let followedNatively = true;
+ await act(async () => {
+ followedNatively = link!.dispatchEvent(
+ new MouseEvent("click", { bubbles: true, cancelable: true, button: 0 }),
+ );
+ });
+ expect(followedNatively).toBe(false);
+ });
});
describe("MessagesTimeline messages", () => {
diff --git a/apps/web/src/components/chat/V2ItemInspector.tsx b/apps/web/src/components/chat/V2ItemInspector.tsx
index f1cea52d8bd8a..82009fca19092 100644
--- a/apps/web/src/components/chat/V2ItemInspector.tsx
+++ b/apps/web/src/components/chat/V2ItemInspector.tsx
@@ -1,6 +1,10 @@
import { T, Var, useGT } from "gt-react";
import type { ToolCallDiffTarget } from "../../diffPanelStore";
-import type { EnvironmentId, OrchestrationV2ProjectedTurnItem } from "@t3tools/contracts";
+import type {
+ EnvironmentId,
+ OrchestrationV2ProjectedTurnItem,
+ ScopedThreadRef,
+} from "@t3tools/contracts";
import {
isJsonToolText,
toolCallLines,
@@ -14,6 +18,9 @@ import { isJavaScriptReplTool } from "@t3tools/shared/toolActivity";
import { ExternalLinkIcon } from "lucide-react";
import { memo, type ReactNode, Suspense, use } from "react";
+import { canOpenLinksInApp, resolveLinkTarget } from "../../browser/browserLinkTarget";
+import { useOpenLink } from "../../browser/useOpenLink";
+import { useClientSettings } from "../../hooks/useSettings";
import { useRenderedAppearance } from "../../hooks/useTheme";
import { cn } from "../../lib/utils";
import { resolveDiffThemeName } from "../../lib/diffRendering";
@@ -196,6 +203,41 @@ export function FetchedToolOutput(props: {
);
}
+function WebSearchResultLink(props: {
+ readonly href: string;
+ readonly threadRef: ScopedThreadRef;
+ readonly children: ReactNode;
+}) {
+ const openLink = useOpenLink(props.threadRef);
+ // Subscribe so the synchronous _blank decision sees hydrated settings, as ChatMarkdown does.
+ const linkTargetPreference = useClientSettings((settings) => settings.browserLinkTarget);
+ return (
+ {
+ if (
+ resolveLinkTarget({
+ url: props.href,
+ event,
+ preference: linkTargetPreference,
+ canOpenInApp: canOpenLinksInApp(props.threadRef),
+ }) !== "app"
+ ) {
+ return;
+ }
+ event.preventDefault();
+ void openLink(props.href, { event }).catch(console.error);
+ }}
+ >
+ {props.children}
+
+
+ );
+}
+
function ToolCallBody(
props: ToolOutputState & {
readonly command?: string;
@@ -370,15 +412,15 @@ export const V2ItemInspector = memo(function V2ItemInspector(props: V2ItemInspec
return (
{safeHref ? (
-
{result.title ?? result.url}
-
-
+
) : (
{result.title ?? result.url ?? gt("Search result")}
From c14e9f9717739a03ad62289d82ba287bad64a5bf Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 16:34:10 +0100
Subject: [PATCH 046/238] fix(server): preserve split terminal control
sequences across scrollback clears (#42810)
Co-authored-by: Julius Marminge
---
.../server/src/terminal/Manager.clear.test.ts | 123 ++++++++++++++++++
apps/server/src/terminal/Manager.ts | 30 ++++-
apps/server/src/terminal/OutputProtocol.ts | 18 +--
apps/web/src/terminal/ghostty/core.test.ts | 28 ++++
.../src/state/terminalOutput.ts | 18 ++-
.../src/state/terminalSession.test.ts | 22 ++++
.../src/state/terminalSession.ts | 2 +-
packages/contracts/src/terminal.ts | 1 +
8 files changed, 224 insertions(+), 18 deletions(-)
create mode 100644 apps/server/src/terminal/Manager.clear.test.ts
diff --git a/apps/server/src/terminal/Manager.clear.test.ts b/apps/server/src/terminal/Manager.clear.test.ts
new file mode 100644
index 0000000000000..5e3815d9df771
--- /dev/null
+++ b/apps/server/src/terminal/Manager.clear.test.ts
@@ -0,0 +1,123 @@
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { it } from "@effect/vitest";
+import { DEFAULT_TERMINAL_ID, ThreadId } from "@t3tools/contracts";
+import { SpawnExecutableResolution } from "@t3tools/shared/shell";
+import * as Deferred from "effect/Deferred";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Stream from "effect/Stream";
+import { expect, vi } from "vite-plus/test";
+
+import * as ProcessRunner from "../processRunner.ts";
+import { makeWithOptions } from "./Manager.ts";
+
+const node = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer);
+
+it.layer(Layer.mergeAll(node, ProcessRunner.layer.pipe(Layer.provide(node))), {
+ excludeTestServices: true,
+})("TerminalManager clear", (it) => {
+ it.effect.each([
+ {
+ part: "opener",
+ publishing: "old output\r\n",
+ queued: "\u001b]0;Build ",
+ pending: "\u001b]0;Build ",
+ afterClear: "progress\u0007ready\r\n",
+ },
+ {
+ part: "CSI",
+ publishing: "old output\r\n",
+ queued: "\u001b[\n",
+ pending: "\u001b[",
+ afterClear: "mready\r\n",
+ },
+ {
+ part: "terminator",
+ publishing: "old output\r\n\u001b]0;Build ",
+ queued: "progress\u0007",
+ afterClear: "ready\r\n",
+ },
+ {
+ part: "exit",
+ publishing: "old output\r\n\u001b]0;Build ",
+ queued: "progress\u0007",
+ afterClear: "ready\r\n",
+ exit: { exitCode: 42, signal: null },
+ },
+ ])("keeps visible history correct when the title $part is queued", (row) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const logsDir = yield* fs.makeTempDirectoryScoped();
+ const onData = vi.fn<(callback: (data: string) => void) => () => void>(() => () => {});
+ const onExit = vi.fn<
+ (callback: (event: { exitCode: number; signal: number | null }) => void) => () => void
+ >(() => () => {});
+ const manager = yield* makeWithOptions({
+ logsDir,
+ ptyAdapter: {
+ spawn: () =>
+ Effect.succeed({
+ pid: 9000,
+ write: () => {},
+ resize: () => {},
+ kill: () => {},
+ onData,
+ onExit,
+ }),
+ },
+ foregroundProcessGroup: (pid) => Effect.succeed(pid),
+ processKillGraceMs: 0,
+ }).pipe(Effect.provideService(SpawnExecutableResolution, (command) => command));
+ const input = { threadId: ThreadId.make("thread-1"), terminalId: DEFAULT_TERMINAL_ID };
+ yield* manager.open({ ...input, cwd: logsDir });
+ const live = yield* Stream.toPull(manager.attachOutputStream(input, "live"));
+ yield* live;
+
+ const publishing = yield* Deferred.make();
+ const resume = yield* Deferred.make();
+ const printed = yield* Deferred.make();
+ yield* Effect.acquireRelease(
+ manager.subscribe((event) => {
+ if (event.type !== "output") return Effect.void;
+ if (event.data === row.publishing) {
+ return Deferred.succeed(publishing, undefined).pipe(
+ Effect.andThen(Deferred.await(resume)),
+ );
+ }
+ if (event.data === row.afterClear) return Deferred.succeed(printed, undefined);
+ return Effect.void;
+ }),
+ (unsubscribe) =>
+ Deferred.succeed(resume, undefined).pipe(Effect.andThen(Effect.sync(unsubscribe))),
+ );
+ const emitData = onData.mock.calls[0]![0];
+ emitData(row.publishing);
+ yield* Deferred.await(publishing);
+ yield* live;
+ emitData(row.queued);
+ if (row.exit) onExit.mock.calls[0];
+ yield* manager.clear(input);
+ const [cleared] = yield* live;
+ expect(cleared?.type).toBe("cleared");
+ yield* Deferred.succeed(resume, undefined);
+
+ if (row.exit) {
+ emitData(row.afterClear);
+ const [exited] = yield* live;
+ expect(exited).toMatchObject({ type: "exited", exitCode: row.exit.exitCode });
+ return;
+ }
+ if (row.pending) expect(cleared).toMatchObject({ pendingControlSequence: row.pending });
+ emitData(row.afterClear);
+ yield* Deferred.await(printed);
+
+ const reopened = yield* Stream.toPull(manager.attachOutputStream(input, "reopened"));
+ const [event] = yield* reopened;
+ if (event?.type !== "snapshot") throw new Error("Expected a terminal snapshot");
+ const visible = event.snapshot.history.replace(/\u001b\]0;[^\u0007]*\u0007|\u001b\[m/g, "");
+ expect(visible).toBe("ready\r\n");
+ }),
+ );
+});
diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts
index 12f72a1e228b7..9aa897b970410 100644
--- a/apps/server/src/terminal/Manager.ts
+++ b/apps/server/src/terminal/Manager.ts
@@ -3941,12 +3941,35 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
Effect.gen(function* () {
const terminalId = input.terminalId;
const session = yield* requireSession(input.threadId, terminalId);
+ let queuedExit: PendingProcessEvent | undefined;
+ // Discard pre-clear output while keeping the parser in sync with the PTY.
+ for (const event of session.pendingProcessEvents.slice(session.pendingProcessEventIndex)) {
+ if (event?.type === "exit") {
+ queuedExit = event;
+ session.pendingHistoryControlSequence = "";
+ break;
+ }
+ if (event?.type === "output") {
+ session.pendingHistoryControlSequence = sanitizeTerminalHistoryChunk(
+ session.pendingHistoryControlSequence,
+ event.data,
+ ).pendingControlSequence;
+ }
+ }
+ // Controls embedded in an unfinished CSI have already run before the clear.
+ if (session.pendingHistoryControlSequence.startsWith("\u001b[")) {
+ session.pendingHistoryControlSequence = session.pendingHistoryControlSequence.replace(
+ /[\x00-\x0f]/g,
+ "",
+ );
+ }
session.history.clear();
- session.pendingHistoryControlSequence = "";
- session.pendingProcessEvents = [];
+ session.pendingProcessEvents = queuedExit ? [queuedExit] : [];
session.pendingProcessEventIndex = 0;
- session.processEventDrainRunning = false;
const eventStamp = advanceEventSequence(session);
+ const pendingControlSequence = unfinishedSequenceReplay(
+ session.pendingHistoryControlSequence,
+ );
// A drain waits for the key to go idle, which never happens while the shell keeps
// printing; every reader of the file flushes it first.
yield* persistWorker.enqueue(toSessionKey(input.threadId, terminalId), {
@@ -3958,6 +3981,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
threadId: input.threadId,
terminalId,
sequence: eventStamp.sequence,
+ ...(pendingControlSequence === "" ? {} : { pendingControlSequence }),
});
}),
);
diff --git a/apps/server/src/terminal/OutputProtocol.ts b/apps/server/src/terminal/OutputProtocol.ts
index 84f6e40923417..1b3f48faa6427 100644
--- a/apps/server/src/terminal/OutputProtocol.ts
+++ b/apps/server/src/terminal/OutputProtocol.ts
@@ -46,14 +46,16 @@ const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) =>
? byteLengthOf(event.message)
: event.type === "activity"
? byteLengthOf(event.label)
- : "snapshot" in event
- ? byteLengthOf(event.snapshot.threadId) +
- byteLengthOf(event.snapshot.terminalId) +
- byteLengthOf(event.snapshot.history) +
- byteLengthOf(event.snapshot.cwd) +
- byteLengthOf(event.snapshot.worktreePath) +
- byteLengthOf(event.snapshot.label)
- : 0);
+ : event.type === "cleared"
+ ? byteLengthOf(event.pendingControlSequence)
+ : "snapshot" in event
+ ? byteLengthOf(event.snapshot.threadId) +
+ byteLengthOf(event.snapshot.terminalId) +
+ byteLengthOf(event.snapshot.history) +
+ byteLengthOf(event.snapshot.cwd) +
+ byteLengthOf(event.snapshot.worktreePath) +
+ byteLengthOf(event.snapshot.label)
+ : 0);
// Byte-windowed streams carry TerminalAttachStreamEvent, whose encoded form is the
// event itself, so charge it like the output queue does instead of serializing twice.
diff --git a/apps/web/src/terminal/ghostty/core.test.ts b/apps/web/src/terminal/ghostty/core.test.ts
index daa9820dddc46..4faca7a74f8d7 100644
--- a/apps/web/src/terminal/ghostty/core.test.ts
+++ b/apps/web/src/terminal/ghostty/core.test.ts
@@ -488,6 +488,34 @@ describe("GhosttyTerminalCore snapshots", () => {
expect(core.snapshot()).toEqual(reference.snapshot());
});
+ it.each([
+ {
+ sequence: "title",
+ beforeClear: "",
+ pending: "\u001b]0;Build ",
+ afterClear: "progress\u0007",
+ },
+ { sequence: "CSI", beforeClear: "\u001b[\n", pending: "\u001b[", afterClear: "m" },
+ ])("resumes a split $sequence after clearing an attached terminal", async (row) => {
+ const [core, reference] = await Promise.all([createCore(), createCore()]);
+ let state = createSession(`old output\r\n${row.beforeClear}`);
+ const initial = readTerminalOutputUpdate(state.output, INITIAL_TERMINAL_OUTPUT_CURSOR);
+ writeTerminalOutputUpdate(core, initial);
+
+ const cleared = {
+ type: "cleared",
+ threadId: "terminal-stream-test",
+ terminalId: "term-1",
+ pendingControlSequence: row.pending,
+ } as const;
+ state = applyTerminalAttachStreamEvent(state, cleared);
+ state = append(state, `${row.afterClear}ready\r\n`);
+ writeTerminalOutputUpdate(core, readTerminalOutputUpdate(state.output, initial.cursor));
+
+ reference.write("ready\r\n");
+ expect(core.snapshot()).toEqual(reference.snapshot());
+ });
+
it("drops stale text in real Ghostty for a repeated snapshot, clear, restart, and a fresh attach", async () => {
const [core, reference] = await Promise.all([createCore(), createCore()]);
let state = createSession("hello");
diff --git a/packages/client-runtime/src/state/terminalOutput.ts b/packages/client-runtime/src/state/terminalOutput.ts
index 0df9bcb7126d7..2bd870264b9e6 100644
--- a/packages/client-runtime/src/state/terminalOutput.ts
+++ b/packages/client-runtime/src/state/terminalOutput.ts
@@ -305,14 +305,19 @@ function resetOutput(
const CLEAR_TERMINAL_TEXT = "\u001b[H\u001b[2J\u001b[3J";
/** Earlier output stays retained so a replay from the start restores those modes. */
-function clearOutput(current: TerminalOutputState, maxBufferBytes: number): TerminalOutputState {
+function clearOutput(
+ current: TerminalOutputState,
+ maxBufferBytes: number,
+ pendingControlSequence = "",
+): TerminalOutputState {
+ const data = CLEAR_TERMINAL_TEXT + pendingControlSequence;
// The erase rides over the budget: trimming here would evict the output that set those modes.
const cleared = appendOutput(
{ ...current, pendingSnapshotSequenceState: undefined },
- CLEAR_TERMINAL_TEXT,
+ data,
maxBufferBytes <= 0
? maxBufferBytes
- : Math.max(maxBufferBytes, current.retainedBytes + CLEAR_TERMINAL_TEXT.length),
+ : Math.max(maxBufferBytes, current.retainedBytes + textEncoder.encode(data).byteLength),
);
return { ...cleared, textStartOffset: cleared.nextOffset };
}
@@ -327,9 +332,10 @@ export function terminalOutputReplay(output: TerminalOutputState): string {
export function terminalOutputText(output: TerminalOutputState): string {
const text = output.chunks.map((chunk) => chunk.data).join("");
const firstOffset = output.chunks[0]?.startOffset ?? output.nextOffset;
- return text.slice(
- Math.max(terminalSequenceEnd(output.sequenceState, text), output.textStartOffset - firstOffset),
- );
+ const start = Math.max(0, output.textStartOffset - firstOffset);
+ const sequenceState = terminalSequenceStateAfter(output.sequenceState, text, 0, start);
+ const visible = text.slice(start);
+ return visible.slice(terminalSequenceEnd(sequenceState, visible));
}
export function readTerminalOutputUpdate(
diff --git a/packages/client-runtime/src/state/terminalSession.test.ts b/packages/client-runtime/src/state/terminalSession.test.ts
index 19401a26c7f89..2b44a5900f20d 100644
--- a/packages/client-runtime/src/state/terminalSession.test.ts
+++ b/packages/client-runtime/src/state/terminalSession.test.ts
@@ -386,6 +386,28 @@ describe("terminal session reducers", () => {
expect(state.output.retainedBytes).toBe(8);
});
+ it("skips the rest of an unfinished title when reading text after a clear", () => {
+ let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
+ type: "snapshot",
+ snapshot: BASE_SNAPSHOT,
+ });
+ state = applyTerminalAttachStreamEvent(state, {
+ type: "cleared",
+ ...TARGET,
+ pendingControlSequence: "\u001b]0;Build ",
+ });
+ for (const data of ["pro", "gress"]) {
+ state = applyTerminalAttachStreamEvent(state, { type: "output", ...TARGET, data });
+ expect(terminalOutputText(state.output)).toBe("");
+ }
+ state = applyTerminalAttachStreamEvent(state, {
+ type: "output",
+ ...TARGET,
+ data: "\u0007ready",
+ });
+ expect(terminalOutputText(state.output)).toBe("ready");
+ });
+
it("resets for repeated snapshots and restart even when output text repeats, and erases on clear", () => {
let state = applyTerminalAttachStreamEvent(EMPTY_TERMINAL_BUFFER_STATE, {
type: "snapshot",
diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts
index a7224209920bc..4eb84e9b192ae 100644
--- a/packages/client-runtime/src/state/terminalSession.ts
+++ b/packages/client-runtime/src/state/terminalSession.ts
@@ -195,7 +195,7 @@ export function applyTerminalAttachStreamEvent(
case "cleared":
return {
...current,
- output: clearOutput(current.output, maxBufferBytes),
+ output: clearOutput(current.output, maxBufferBytes, event.pendingControlSequence),
error: null,
version: current.version + 1,
};
diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts
index 31419fe56374b..0043f87d0eaed 100644
--- a/packages/contracts/src/terminal.ts
+++ b/packages/contracts/src/terminal.ts
@@ -390,6 +390,7 @@ const TerminalErrorEvent = Schema.Struct({
const TerminalClearedEvent = Schema.Struct({
...TerminalEventBaseSchema.fields,
type: Schema.Literal("cleared"),
+ pendingControlSequence: Schema.optionalKey(Schema.String),
});
const TerminalRestartedEvent = Schema.Struct({
From 3373a78606296baa9bb6e386c242da2f9ae32e04 Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 16:34:28 +0100
Subject: [PATCH 047/238] fix(web): update terminal labels when the language
changes (#42872)
Co-authored-by: Julius Marminge
---
apps/web/src/terminal/ghostty/surface.ts | 80 ++++++++++++-------
...minal-input-follows-language-change.e2e.ts | 57 +++++++++++++
2 files changed, 106 insertions(+), 31 deletions(-)
create mode 100644 scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts
diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts
index b06a77f490742..b104e749b4756 100644
--- a/apps/web/src/terminal/ghostty/surface.ts
+++ b/apps/web/src/terminal/ghostty/surface.ts
@@ -23,6 +23,7 @@ import { isMonospaceFamily } from "../../appearanceFonts";
import { observeResize } from "../../lib/observeResize";
import { msg } from "gt-react";
import { m } from "../../i18n/messages";
+import { subscribeI18n } from "../../i18n/runtime";
const DEFAULT_TERMINAL_FONT_SIZE = 12;
const MIN_TERMINAL_FONT_SIZE = 6;
@@ -667,6 +668,7 @@ export class GhosttyTerminalSurface {
metrics: GhosttyCellMetrics,
fontFamily: string,
options: GhosttyTerminalSurfaceOptions,
+ private readonly stopObservingI18n: () => void,
) {
this.mount = mount;
this.canvas = canvas;
@@ -703,7 +705,6 @@ export class GhosttyTerminalSurface {
const input = document.createElement("textarea");
input.className = "t3-ghostty-input";
- input.setAttribute("aria-label", m(msg("Terminal input")));
input.autocapitalize = "off";
input.autocomplete = "off";
input.spellcheck = false;
@@ -714,7 +715,6 @@ export class GhosttyTerminalSurface {
scrollbar.className =
"group absolute top-1 right-px bottom-1 z-1 w-[var(--app-scrollbar-width)] cursor-default touch-none";
scrollbar.setAttribute("role", "scrollbar");
- scrollbar.setAttribute("aria-label", m(msg("Terminal scrollback")));
scrollbar.setAttribute("aria-orientation", "vertical");
scrollbar.tabIndex = 0;
scrollbar.hidden = true;
@@ -722,42 +722,59 @@ export class GhosttyTerminalSurface {
scrollbarThumb.className =
"absolute inset-x-px top-0 rounded-[3px] bg-[var(--app-scrollbar-thumb)] transition-[background-color] duration-[120ms] ease-[ease-out] group-hover:bg-[var(--app-scrollbar-thumb-hover)] group-focus-visible:bg-[var(--app-scrollbar-thumb-hover)]";
scrollbar.append(scrollbarThumb);
+ const updateAccessibleNames = () => {
+ input.setAttribute("aria-label", m(msg("Terminal input")));
+ scrollbar.setAttribute("aria-label", m(msg("Terminal scrollback")));
+ };
+ updateAccessibleNames();
mount.replaceChildren(canvas, input, scrollbar);
const context = canvas.getContext("2d", { alpha: false });
if (!context) throw new Error("Canvas 2D is unavailable");
context.fillStyle = `rgb(${options.theme.background.r}, ${options.theme.background.g}, ${options.theme.background.b})`;
context.fillRect(0, 0, canvas.width, canvas.height);
- const fontSize = terminalFontSize(options.font?.size);
+ const stopObservingI18n = subscribeI18n(updateAccessibleNames);
try {
- // Load bundled fonts before measuring; fallback metrics would size the wrong grid.
- await ensureTerminalSymbolsFont();
- } catch {}
- const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize);
- const metrics = measureGhosttyCell(context, fontSize, fontFamily);
- const grid = terminalGridSize(mount.clientWidth, mount.clientHeight, metrics, CONTENT_PADDING);
- const core = await GhosttyTerminalCore.create(
- grid.cols,
- grid.rows,
- metrics.width,
- metrics.height,
- options.theme,
- options.onReply,
- );
- const surface = new GhosttyTerminalSurface(
- mount,
- canvas,
- input,
- scrollbar,
- scrollbarThumb,
- context,
- core,
- metrics,
- fontFamily,
- options,
- );
- surface.fit();
- return surface;
+ const fontSize = terminalFontSize(options.font?.size);
+ try {
+ // Load bundled fonts before measuring; fallback metrics would size the wrong grid.
+ await ensureTerminalSymbolsFont();
+ } catch {}
+ const fontFamily = await loadTerminalFontFamily(options.font?.family, fontSize);
+ const metrics = measureGhosttyCell(context, fontSize, fontFamily);
+ const grid = terminalGridSize(
+ mount.clientWidth,
+ mount.clientHeight,
+ metrics,
+ CONTENT_PADDING,
+ );
+ const core = await GhosttyTerminalCore.create(
+ grid.cols,
+ grid.rows,
+ metrics.width,
+ metrics.height,
+ options.theme,
+ options.onReply,
+ );
+ const surface = new GhosttyTerminalSurface(
+ mount,
+ canvas,
+ input,
+ scrollbar,
+ scrollbarThumb,
+ context,
+ core,
+ metrics,
+ fontFamily,
+ options,
+ stopObservingI18n,
+ );
+ surface.fit();
+ return surface;
+ } catch (error) {
+ stopObservingI18n();
+ throw error;
+ }
}
setVisible(visible: boolean): void {
@@ -1079,6 +1096,7 @@ export class GhosttyTerminalSurface {
this.disposed = true;
this.clearHoveredLink();
this.stopObservingResize();
+ this.stopObservingI18n();
document.fonts.removeEventListener("loadingdone", this.onFontsLoaded);
this.dprMedia?.removeEventListener("change", this.onDevicePixelRatioChange);
this.dprMedia = null;
diff --git a/scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts b/scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts
new file mode 100644
index 0000000000000..05e8abbe98849
--- /dev/null
+++ b/scripts/scenarios/pending-terminal-input-follows-language-change.e2e.ts
@@ -0,0 +1,57 @@
+import { expect } from "e2e";
+
+import { test, WEB } from "./t3.ts";
+
+test(
+ "Language changes update the same terminal input during and after setup",
+ WEB,
+ async ({ t3, app, browser, screen }) => {
+ const project = await t3.project("demo");
+ const thread = await t3.thread({ project, title: "Terminal work", messages: ["Start"] });
+ await t3.open(thread);
+
+ await browser.evaluate(() => {
+ const load = FontFace.prototype.load;
+ const ready = new Promise((resolve) => {
+ window.addEventListener("release-terminal-font", () => resolve(), { once: true });
+ });
+ FontFace.prototype.load = function () {
+ return this.family.includes("Symbols Nerd Font Mono")
+ ? ready.then(() => load.call(this))
+ : load.call(this);
+ };
+ return null;
+ });
+
+ await screen.getByRole("button", "Toggle terminal drawer").tap();
+ const input = browser.locator(".t3-ghostty-input:not([data-workspace-focus-default])");
+ await expect(input).toHaveAttribute("aria-label", "Terminal input");
+ await browser.evaluate(() => {
+ document.querySelector(".t3-ghostty-input")!.setAttribute("data-original-terminal", "");
+ return null;
+ });
+
+ await screen.getByRole("button", "Settings", { exact: true }).tap();
+ await screen.getByLabel("Language", { exact: true }).tap();
+ await screen.getByText("日本語", { exact: true }).tap();
+ await screen.getByLabel("言語", { exact: true }).waitFor();
+
+ const originalInput = browser.locator(
+ ".t3-ghostty-input[data-original-terminal]:not([data-workspace-focus-default])",
+ );
+ await app.screenshot("pending-terminal-input-after-language-change");
+ await expect(originalInput).toHaveAttribute("aria-label", "ターミナルの入力");
+ await browser.evaluate(() => window.dispatchEvent(new Event("release-terminal-font")));
+
+ const readyInput = browser.locator(
+ ".t3-ghostty-input[data-original-terminal][data-workspace-focus-default]",
+ );
+ await expect(readyInput).toHaveAttribute("aria-label", "ターミナルの入力");
+ await screen.getByLabel("言語", { exact: true }).tap();
+ await screen.getByText("English", { exact: true }).tap();
+ await screen.getByLabel("Language", { exact: true }).waitFor();
+ await browser.keyboard.press("Escape");
+
+ await expect(readyInput).toHaveAttribute("aria-label", "Terminal input");
+ },
+);
From acd4fc67b930b0a9be7799f3f986e0ec46bf7a14 Mon Sep 17 00:00:00 2001
From: Marcus Takagi
Date: Wed, 25 Nov 2026 23:34:42 +0800
Subject: [PATCH 048/238] fix(web): show Labs device preferences read-only for
projects (#42884)
Co-authored-by: huyuetian
Co-authored-by: Julius Marminge
---
.../LabsSettingsPanel.scope.browser.test.tsx | 129 ++++++++++++++++++
.../components/settings/LabsSettingsPanel.tsx | 2 +
docs/user/project-settings.md | 10 +-
...boring-sidebar-read-only-in-project.e2e.ts | 26 ++++
4 files changed, 162 insertions(+), 5 deletions(-)
create mode 100644 apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx
create mode 100644 scripts/scenarios/labs-boring-sidebar-read-only-in-project.e2e.ts
diff --git a/apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx b/apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx
new file mode 100644
index 0000000000000..bce95490d461e
--- /dev/null
+++ b/apps/web/src/components/settings/LabsSettingsPanel.scope.browser.test.tsx
@@ -0,0 +1,129 @@
+import { PrimaryConnectionTarget } from "@t3tools/client-runtime/connection";
+import { EnvironmentId, ProjectId, ServerConfig } from "@t3tools/contracts";
+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
+import * as Option from "effect/Option";
+import * as Schema from "effect/Schema";
+import { expect, it, vi } from "vite-plus/test";
+
+import { render } from "../../../test/render";
+import "../../index.css";
+import { ensureClientSettingsHydrated, persistClientSettingsPatch } from "../../hooks/useSettings";
+import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping";
+import type { EnvironmentPresentation } from "../../state/environments";
+import type { Project } from "../../types";
+
+const environmentId = EnvironmentId.make("labs-settings");
+const config = Schema.decodeSync(ServerConfig)({
+ environment: {
+ environmentId,
+ label: "Desk",
+ platform: { os: "linux", arch: "x64" },
+ serverVersion: "1.0.0",
+ orchestrationProtocolVersion: 2,
+ capabilities: {},
+ },
+ auth: {
+ policy: "loopback-browser",
+ bootstrapMethods: ["one-time-token"],
+ sessionMethods: ["browser-session-cookie"],
+ sessionCookieName: "t3_session",
+ },
+ cwd: "/workspace/labs",
+ keybindingsConfigPath: "/workspace/keybindings.json",
+ keybindings: [],
+ issues: [],
+ providers: [],
+ availableEditors: [],
+ observability: {
+ logsDirectoryPath: "/workspace/logs",
+ localTracingEnabled: false,
+ otlpTracesEnabled: false,
+ otlpMetricsEnabled: false,
+ },
+ settings: {},
+});
+const environments: EnvironmentPresentation[] = [
+ {
+ environmentId,
+ label: "Desk",
+ displayUrl: "http://localhost:12345",
+ relayManaged: false,
+ entry: {
+ target: new PrimaryConnectionTarget({
+ environmentId,
+ label: "Desk",
+ httpBaseUrl: "http://localhost:12345",
+ wsBaseUrl: "ws://localhost:12345/ws",
+ }),
+ profile: Option.none(),
+ enabled: true,
+ },
+ connection: { phase: "connected", error: null, traceId: null },
+ refusedRouteIds: [],
+ serverConfig: config,
+ },
+];
+const projects: Project[] = [
+ {
+ id: ProjectId.make("labs-project"),
+ environmentId,
+ title: "Labs project",
+ workspaceRoot: "/workspace/labs",
+ repositoryIdentity: null,
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-11-14T00:00:00.000Z",
+ updatedAt: "2026-11-14T00:00:00.000Z",
+ },
+];
+
+vi.mock(import("../../state/environments"), async (original) => ({
+ ...(await original()),
+ useEnvironments: () => ({
+ isReady: true,
+ networkStatus: "online" as const,
+ environments,
+ presentationById: new Map(),
+ }),
+ usePrimaryEnvironmentId: () => environmentId,
+ usePrimaryEnvironment: () => environments[0]!,
+ readEnvironment: () => environments[0]!,
+}));
+vi.mock(import("../../state/session"), async (original) => ({
+ ...(await original()),
+ useEnvironmentScope: () => true,
+ useEnvironmentsWithScope: () => new Set([environmentId]),
+}));
+vi.mock(import("../../state/entities"), async (original) => ({
+ ...(await original()),
+ useProjects: () => projects,
+ useServerConfigs: () => new Map([[environmentId, config]]),
+}));
+
+import { LabsSettingsPanel } from "./LabsSettingsPanel";
+import { SettingsScopeProvider } from "./SettingsScopeContext";
+
+const [group] = buildSidebarProjectSnapshots({
+ projects,
+ settings: DEFAULT_CLIENT_SETTINGS,
+ primaryEnvironmentId: environmentId,
+ resolveEnvironmentLabel: () => "Desk",
+});
+
+it("shows Boring sidebar device preferences read-only while a project is selected", async () => {
+ await ensureClientSettingsHydrated();
+ await persistClientSettingsPatch(
+ { boringSidebarEnabled: true, boringSidebarMultilineRows: false },
+ async () => {},
+ );
+ await using screen = await render(
+ {}}>
+
+ ,
+ { router: "/settings/labs" },
+ );
+
+ for (const name of ["Boring sidebar (group by project)", "Two-line folder rows"]) {
+ expect(screen.getByRole("switch", { name }).element().closest("[inert]")).not.toBeNull();
+ }
+});
diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx
index 71bf6d6da55f5..d5e77b2dc28a3 100644
--- a/apps/web/src/components/settings/LabsSettingsPanel.tsx
+++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx
@@ -61,6 +61,7 @@ function BoringSidebarRow() {
return (
{
+ await t3.project("demo");
+ await t3.open("/settings/labs");
+
+ await screen.getByRole("switch", "Boring sidebar (group by project)").check();
+ await expect(screen.getByRole("switch", "Two-line folder rows")).toBeVisible();
+
+ await screen.getByRole("button", "Project scope: All projects").tap();
+ await screen.getByRole("menuitemradio").filter({ hasText: "demo" }).tap();
+ await expect(screen.getByRole("button", "Project scope: demo")).toBeVisible();
+ await app.screenshot("project-selected");
+
+ // A project cannot override a device preference, so neither switch may offer an edit.
+ await expect(
+ browser.locator('[inert] [aria-label="Boring sidebar (group by project)"]'),
+ ).toBeVisible();
+ await expect(browser.locator('[inert] [aria-label="Two-line folder rows"]')).toBeVisible();
+ },
+);
From aef22ed239b5947300d03d0d487c5d32cb4e5d7f Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 07:34:55 -0800
Subject: [PATCH 049/238] fix(server): t3 connect link says to restart a
running server, not start t3 serve (#42904)
---
apps/server/src/cli/connect.test.ts | 62 +++++++++++++++++++++++++++++
apps/server/src/cli/connect.ts | 17 +++++---
2 files changed, 73 insertions(+), 6 deletions(-)
diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.ts
index 630fe7cbfbb63..d591cb311fc61 100644
--- a/apps/server/src/cli/connect.test.ts
+++ b/apps/server/src/cli/connect.test.ts
@@ -278,3 +278,65 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))
);
},
);
+
+it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))(
+ "t3 connect link next step",
+ (it) => {
+ it.effect("tells the user to restart a server that is already running, not to start one", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-connect-link-test-" });
+ const relayClientPath = `${baseDir}/bin/cloudflared`;
+ yield* fs.makeDirectory(`${baseDir}/bin`, { recursive: true });
+ yield* fs.writeFileString(
+ relayClientPath,
+ `#!/bin/sh\necho "cloudflared version ${RelayClient.CLOUDFLARED_VERSION}"\n`,
+ );
+ yield* fs.chmod(relayClientPath, 0o755);
+ yield* fs.makeDirectory(`${baseDir}/userdata/secrets`, { recursive: true });
+ yield* fs.writeFileString(
+ `${baseDir}/userdata/secrets/cloud-cli-oauth-token.bin`,
+ JSON.stringify({
+ accessToken: "access",
+ refreshToken: "refresh",
+ expiresAtEpochMs: 4_102_444_800_000,
+ identity: "user@example.com",
+ }),
+ );
+ const state = yield* makePersistedServerRuntimeState({
+ config: { host: "127.0.0.1", devUrl: undefined },
+ port: 3773,
+ });
+ yield* persistServerRuntimeState({
+ path: `${baseDir}/userdata/server-runtime.json`,
+ state: { ...state, pid: process.pid },
+ });
+
+ yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([
+ "connect",
+ "link",
+ "--headless",
+ "--base-dir",
+ baseDir,
+ ]).pipe(
+ Effect.provide(
+ ConfigProvider.layer(
+ ConfigProvider.fromEnv({ env: { T3CODE_CLOUDFLARED_PATH: relayClientPath } }),
+ ),
+ ),
+ );
+
+ const printed = (yield* TestConsole.logLines).join("\n");
+ const restart = yield* resolveHostCliCommand("service restart", ["--base-dir", baseDir]);
+ const serve = yield* resolveHostCliCommand("serve", ["--base-dir", baseDir]);
+ assert.include(printed, "✓ Authorized as user@example.com");
+ assert.include(printed, `\`${restart.command}\``);
+ assert.notInclude(printed, `\`${serve.command}\``);
+ }).pipe(
+ Effect.scoped,
+ Effect.provideService(HostProcess.Environment, {}),
+ Effect.provide(Layer.fresh(TestConsole.layer)),
+ ),
+ );
+ },
+);
diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts
index 8ef202c2d014f..8dfb794d36c05 100644
--- a/apps/server/src/cli/connect.ts
+++ b/apps/server/src/cli/connect.ts
@@ -649,12 +649,17 @@ const connectLinkCommand = Command.make("link", {
yield* Console.log("T3 Connect\n");
const linked = yield* linkEnvironmentForConnect(flags);
if (linked) {
- const serveCommand = yield* resolveHostCliHint("serve", flags.baseDir);
- yield* Console.log(
- flags.publishOnly
- ? `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start T3 to publish agent activity (no managed tunnel).`
- : `✓ Authorized${connectedAs(linked.identity)}\n\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.`,
- );
+ const config = yield* ServerConfig.ServerConfig;
+ const running = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
+ const purpose = flags.publishOnly
+ ? "publish agent activity (no managed tunnel)"
+ : "make this machine reachable";
+ const next = Option.isSome(running)
+ ? `A T3 Code server is already running. Restart it to ${purpose}: run \`${yield* resolveHostCliHint("service restart", flags.baseDir)}\` for the background service, or stop the server and start it again.`
+ : flags.publishOnly
+ ? `Start T3 to ${purpose}.`
+ : `Start the server with \`${yield* resolveHostCliHint("serve", flags.baseDir)}\` to ${purpose}.`;
+ yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}\n\nNext\n ${next}`);
}
}),
),
From 831f2408825c1c79ddb4e1256d8fe9ba9234befc Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 09:35:09 -0600
Subject: [PATCH 050/238] fix(server): extensionless empty ZIP files are
detected as application/zip (#42899)
Co-authored-by: Julius Marminge
---
apps/server/src/workspace/WorkspaceFileSystem.test.ts | 7 ++++++-
apps/server/src/workspace/fileHeaderMimeType.ts | 3 ++-
2 files changed, 8 insertions(+), 2 deletions(-)
diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
index 7fd184a1f1e9b..98b34bba97ac9 100644
--- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts
+++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts
@@ -153,11 +153,16 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
image,
new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
);
+ const archive = path.join(cwd, "archive");
+ const emptyZip = new Uint8Array(22);
+ emptyZip.set([0x50, 0x4b, 0x05, 0x06]);
+ yield* fs.writeFile(archive, emptyZip);
expect(
- (yield* service.getMetadata({ paths: [path.join(cwd, "run"), image] })).entries,
+ (yield* service.getMetadata({ paths: [path.join(cwd, "run"), image, archive] })).entries,
).toEqual([
{ kind: "file", byteLength: script.length, mimeType: "text/x-python" },
{ kind: "file", byteLength: 8, mimeType: "image/png" },
+ { kind: "file", byteLength: 22, mimeType: "application/zip" },
]);
}),
);
diff --git a/apps/server/src/workspace/fileHeaderMimeType.ts b/apps/server/src/workspace/fileHeaderMimeType.ts
index 0c31a734ca730..889f101ac2d81 100644
--- a/apps/server/src/workspace/fileHeaderMimeType.ts
+++ b/apps/server/src/workspace/fileHeaderMimeType.ts
@@ -3,7 +3,8 @@ export function fileHeaderMimeType(bytes: Uint8Array): string | undefined {
signature.every((byte, index) => bytes[offset + index] === byte);
if (startsWith([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) return "image/png";
if (startsWith([0xff, 0xd8, 0xff])) return "image/jpeg";
- if (startsWith([0x50, 0x4b, 0x03, 0x04])) return "application/zip";
+ if (startsWith([0x50, 0x4b, 0x03, 0x04]) || startsWith([0x50, 0x4b, 0x05, 0x06]))
+ return "application/zip";
if (startsWith([0x52, 0x49, 0x46, 0x46]) && startsWith([0x57, 0x45, 0x42, 0x50], 8))
return "image/webp";
const header = new TextDecoder().decode(bytes);
From 14cc3d1d38e42040a247a506d2a5586087b3adda Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 07:35:25 -0800
Subject: [PATCH 051/238] fix(server): OpenCode /goal length rejection names
the limit (#42905)
---
.../Adapters/OpenCode2AdapterV2.test.ts | 33 +++++++++++++++++++
.../provider-core/src/server/failure.test.ts | 6 ++++
packages/provider-core/src/server/failure.ts | 19 +++++++++++
3 files changed, 58 insertions(+)
diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
index 16193d12e242e..f5279d24116fd 100644
--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
@@ -8662,6 +8662,39 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}),
);
+ // regression: #42892
+ it.effect("shows OpenCode's goal length limit when it rejects a /goal objective", () =>
+ Effect.gen(function* () {
+ const objective = "a".repeat(4001);
+ const { runtime, thread } = yield* resumed(
+ [
+ out("command.list", ""),
+ reply("command.list", { location: { directory: WORK }, data: [{ name: "goal" }] }),
+ out("message.list", { sessionID: SESSION, order: "desc", limit: "1" }),
+ reply("message.list", { data: [], cursor: {} }),
+ out("session.command", { sessionID: SESSION, name: "goal", text: objective }),
+ reply("session.command", {
+ status: 500,
+ body: {
+ _tag: "CommandExecutionError",
+ command: "goal",
+ message: "A goal objective is limited to 4000 characters (got 4001).",
+ },
+ }),
+ ],
+ { version: "2.2.5" },
+ );
+ const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
+ const input = turnInput(thread);
+ yield* runtime
+ .startTurn({ ...input, message: { ...input.message, text: `/goal ${objective}` } })
+ .pipe(Effect.ignore);
+ const ended = yield* Fiber.join(terminal);
+ assert.equal(ended?.status, "failed");
+ assert.include(ended?.failure?.message ?? "", "4000 characters (got 4001)");
+ }),
+ );
+
it.effect("reads an existing OpenCode 2.2.5 goal when resuming a session", () =>
Effect.gen(function* () {
const runtime = yield* openCode2ReplayRuntime(
diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts
index b052beef8110d..6dfda1bf15db8 100644
--- a/packages/provider-core/src/server/failure.test.ts
+++ b/packages/provider-core/src/server/failure.test.ts
@@ -220,6 +220,12 @@ it("keeps unrecognized reasons and provider text out of category messages", () =
method: "turn/start",
message: "goal objective must be at most 4000 characters",
},
+ { _tag: "CommandExecutionError", command: "goal", message: "private-goal-output" },
+ {
+ _tag: "CommandExecutionError",
+ command: "review",
+ message: "A goal objective is limited to 4000 characters (got 4001).",
+ },
]) {
assert.equal(
makeProviderFailure({ cause: { _tag: "ProviderAdapterTurnStartError", cause } }).message,
diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts
index 43984aaaab5b6..871820d22bb9d 100644
--- a/packages/provider-core/src/server/failure.ts
+++ b/packages/provider-core/src/server/failure.ts
@@ -87,6 +87,10 @@ export function providerProcessExitGuidance(output: unknown): string {
const CODEX_GOAL_VALIDATION_MESSAGE =
/^goal objective must (?:not be empty|be at most \d{1,6} characters)$/u;
+// OpenCode's /goal command rejecting an objective longer than it accepts.
+const OPENCODE_GOAL_LENGTH_REJECTION =
+ /^A goal objective is limited to \d{1,6} characters \(got \d{1,9}\)\.$/u;
+
// codex_config::ConstraintError::InvalidValue for a managed requirements.toml or cloud policy.
const CODEX_ACCESS_REQUIREMENT_REJECTION =
/invalid value for `(approval_policy|sandbox_mode)`: `([A-Za-z]{1,32})` is not in the allowed set /u;
@@ -169,6 +173,21 @@ function curatedCauseMessages(cause: unknown): {
}
break;
}
+ case "CommandExecutionError": {
+ // Only OpenCode's fixed-shape goal length text is shown; other command output stays hidden.
+ const rejection = stringField(cause, "message");
+ if (
+ (cause as Record).command === "goal" &&
+ rejection !== undefined &&
+ OPENCODE_GOAL_LENGTH_REJECTION.test(rejection)
+ ) {
+ return {
+ known: `OpenCode rejected the goal: ${rejection} Shorten it and send /goal again.`,
+ category: categoryMessage(),
+ };
+ }
+ break;
+ }
case "AcpProcessExitedError":
case "CodexAppServerProcessExitedError": {
const exit = `provider process exited${processExitStatus(cause)}`;
From 83a7c75b88b45c8076a0c42cd442bed3b243f6a0 Mon Sep 17 00:00:00 2001
From: nikalezah <67012982+nikalezah@users.noreply.github.com>
Date: Wed, 25 Nov 2026 20:35:41 +0500
Subject: [PATCH 052/238] fix(web,mobile): adding a project from a draft's
picker no longer leaves the draft behind (#42889)
Co-authored-by: Julius Marminge
---
.../projects/AddProjectScreen.logic.test.ts | 29 ++++++++-
.../projects/AddProjectScreen.logic.ts | 32 ++++++++++
.../features/projects/AddProjectScreen.tsx | 52 +++++++++++-----
apps/web/src/commandPaletteBus.ts | 8 ++-
.../src/components/CommandPalette.logic.ts | 15 ++++-
apps/web/src/components/CommandPalette.tsx | 31 +++++++++-
.../src/components/chat/DraftHeroHeadline.tsx | 33 +++--------
apps/web/src/hooks/useNewProject.ts | 8 +--
apps/web/src/lib/moveDraftToProject.test.ts | 59 +++++++++++++++++++
apps/web/src/lib/moveDraftToProject.ts | 42 +++++++++++++
.../add-project-takes-the-draft.e2e.ts | 29 +++++++++
11 files changed, 286 insertions(+), 52 deletions(-)
create mode 100644 apps/web/src/lib/moveDraftToProject.test.ts
create mode 100644 apps/web/src/lib/moveDraftToProject.ts
create mode 100644 scripts/scenarios/add-project-takes-the-draft.e2e.ts
diff --git a/apps/mobile/src/features/projects/AddProjectScreen.logic.test.ts b/apps/mobile/src/features/projects/AddProjectScreen.logic.test.ts
index 492dc5fc11d35..56fec18809391 100644
--- a/apps/mobile/src/features/projects/AddProjectScreen.logic.test.ts
+++ b/apps/mobile/src/features/projects/AddProjectScreen.logic.test.ts
@@ -2,7 +2,8 @@ import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect
import { EnvironmentId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
-import { resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
+import { newTaskFlowKey } from "../threads/new-task-flow-state";
+import { chooserDraftKey, resolveAddProjectEnvironment } from "./AddProjectScreen.logic";
const ENVIRONMENT_A = EnvironmentId.make("environment-a");
const ENVIRONMENT_B = EnvironmentId.make("environment-b");
@@ -21,3 +22,29 @@ describe("resolveAddProjectEnvironment", () => {
).toBeNull();
});
});
+
+describe("chooserDraftKey", () => {
+ const home = { key: "home", name: "Home" };
+ const draftRoute = { key: "thread", name: "Thread", params: { draft: { requestId: "r1" } } };
+ const chooser = { key: "chooser", name: "NewTaskProject" };
+ const addProject = [
+ { key: "add", name: "AddProject" },
+ { key: "local", name: "AddProjectLocal" },
+ ];
+ const flowDraftKeys = new Map([[newTaskFlowKey(draftRoute), "new-task:typed"]]);
+ const readFlowDraftKey = (flowKey: string) => flowDraftKeys.get(flowKey) ?? null;
+
+ it("picks the added project for the draft whose chooser opened Add project", () => {
+ expect(chooserDraftKey([home, draftRoute, chooser, ...addProject], readFlowDraftKey)).toBe(
+ "new-task:typed",
+ );
+ const savedChooser = { ...chooser, params: { draftId: "new-task:saved" } };
+ expect(chooserDraftKey([home, savedChooser, ...addProject], readFlowDraftKey)).toBe(
+ "new-task:saved",
+ );
+ });
+
+ it("picks no draft when Add project opened outside the chooser", () => {
+ expect(chooserDraftKey([home, draftRoute, ...addProject], readFlowDraftKey)).toBeNull();
+ });
+});
diff --git a/apps/mobile/src/features/projects/AddProjectScreen.logic.ts b/apps/mobile/src/features/projects/AddProjectScreen.logic.ts
index 4d1f199e63612..a294d87ad6a9e 100644
--- a/apps/mobile/src/features/projects/AddProjectScreen.logic.ts
+++ b/apps/mobile/src/features/projects/AddProjectScreen.logic.ts
@@ -3,6 +3,9 @@ import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect
import { type EnvironmentId, FilesystemBrowseError } from "@t3tools/contracts";
import * as Schema from "effect/Schema";
+import { newTaskFlowKey } from "../threads/new-task-flow-state";
+import { isDraftThreadRoute, type NewTaskDraftRouteParams } from "../threads/thread-route-state";
+
const isFilesystemBrowseError = Schema.is(FilesystemBrowseError);
/** Clone destinations may name folders that do not exist yet; cloning creates them. */
@@ -40,3 +43,32 @@ export function resolveAddProjectEnvironment<
) ?? null
);
}
+
+interface StackRoute {
+ readonly key: string;
+ readonly name: string;
+ readonly params?: object;
+}
+
+const firstParam = (value: string | string[] | undefined) =>
+ Array.isArray(value) ? value[0] : value;
+
+/**
+ * The draft whose project chooser opened Add project, so the added project is picked for it as
+ * choosing one in the chooser is. Null when Add project opened from anywhere else.
+ */
+export function chooserDraftKey(
+ routes: ReadonlyArray,
+ readFlowDraftKey: (flowKey: string) => string | null,
+): string | null {
+ const chooserIndex = routes.findLastIndex((route) => !route.name.startsWith("AddProject"));
+ const chooser = routes[chooserIndex];
+ if (chooser?.name !== "NewTaskProject") return null;
+ const savedDraftId = firstParam((chooser.params as { draftId?: string | string[] })?.draftId);
+ if (savedDraftId !== undefined) return savedDraftId;
+ const draftRoute = routes[chooserIndex - 1];
+ if (draftRoute === undefined || !isDraftThreadRoute(draftRoute)) return null;
+ const flowKey = newTaskFlowKey(draftRoute);
+ const draft = (draftRoute.params as { draft: NewTaskDraftRouteParams }).draft;
+ return (flowKey && readFlowDraftKey(flowKey)) ?? firstParam(draft.draftId) ?? null;
+}
diff --git a/apps/mobile/src/features/projects/AddProjectScreen.tsx b/apps/mobile/src/features/projects/AddProjectScreen.tsx
index 8de3c67a1825c..4a5ae565dc74c 100644
--- a/apps/mobile/src/features/projects/AddProjectScreen.tsx
+++ b/apps/mobile/src/features/projects/AddProjectScreen.tsx
@@ -102,11 +102,14 @@ import {
useSavedRemoteConnections,
} from "../../state/use-remote-environment-registry";
import {
+ chooserDraftKey,
isMissingCloneParentBrowseFailure,
resolveAddProjectEnvironment,
} from "./AddProjectScreen.logic";
+import { readNewTaskFlowState } from "../threads/new-task-flow-state";
import {
createNewTaskDraft,
+ retargetSavedNewTaskDraft,
setComposerDraftText,
waitForComposerDraftsLoaded,
} from "../../state/use-composer-drafts";
@@ -755,7 +758,7 @@ function getActiveRoute(navigation: {
function useOpenNewTaskDraft() {
const navigation = useNavigation>();
const selectDetail = useSelectWorkspaceDetail();
- return (
+ return async (
params: {
environmentId: EnvironmentId;
projectId: ProjectId;
@@ -765,16 +768,35 @@ function useOpenNewTaskDraft() {
},
originRoute: NavigationState["routes"][number] | undefined,
) => {
- const activeRoute = getActiveRoute(navigation);
- // A warm link can change the task without replacing its native route key.
- if (
- !originRoute ||
- activeRoute?.key !== originRoute.key ||
- activeRoute.name !== originRoute.name ||
- activeRoute.params !== originRoute.params
- )
- return;
- selectDetail({ name: "Thread", params: { draft: params } });
+ const isStillOnOrigin = () => {
+ const activeRoute = getActiveRoute(navigation);
+ // A warm link can change the task without replacing its native route key.
+ return (
+ originRoute !== undefined &&
+ activeRoute?.key === originRoute.key &&
+ activeRoute.name === originRoute.name &&
+ activeRoute.params === originRoute.params
+ );
+ };
+ if (!isStillOnOrigin()) return;
+ const chooserDraft =
+ params.draftId === undefined
+ ? chooserDraftKey(
+ navigation.getState()?.routes ?? [],
+ (flowKey) => readNewTaskFlowState(flowKey).draftKey,
+ )
+ : null;
+ const carried =
+ chooserDraft !== null &&
+ (await retargetSavedNewTaskDraft(chooserDraft, {
+ environmentId: params.environmentId,
+ projectId: params.projectId,
+ }).catch(() => false));
+ if (!isStillOnOrigin()) return;
+ selectDetail({
+ name: "Thread",
+ params: { draft: carried ? { ...params, draftId: chooserDraft } : params },
+ });
};
}
@@ -832,7 +854,7 @@ function useOpenExistingProject(environment: EnvironmentOption | null) {
? existing.title
: m(msg("{title} is still archived. Try again later.", { title: existing.title })),
);
- openNewTaskDraft(
+ void openNewTaskDraft(
{
environmentId: existing.environmentId,
projectId: existing.id,
@@ -912,7 +934,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
);
return result;
}
- openNewTaskDraft(
+ void openNewTaskDraft(
{
environmentId: environment.environmentId,
projectId,
@@ -1306,7 +1328,7 @@ export function AddProjectNewScreen(props: { readonly environmentId?: string | s
);
return;
}
- openNewTaskDraft(
+ void openNewTaskDraft(
{
environmentId: environment.environmentId,
projectId,
@@ -1627,7 +1649,7 @@ export function AddProjectDestinationScreen(props: {
),
);
} else {
- openNewTaskDraft(
+ void openNewTaskDraft(
{
environmentId: environment.environmentId,
projectId,
diff --git a/apps/web/src/commandPaletteBus.ts b/apps/web/src/commandPaletteBus.ts
index 2766f6db6b391..4e2ab43931380 100644
--- a/apps/web/src/commandPaletteBus.ts
+++ b/apps/web/src/commandPaletteBus.ts
@@ -1,5 +1,6 @@
import type { EnvironmentId, PullRequestLinkedThreadsResult } from "@t3tools/contracts";
+import type { DraftId } from "./composerDraftStore";
import { dispatchCommandPalette, isCommandPaletteMounted } from "./commandPaletteStore";
export interface CommandPaletteLinkedThreads {
@@ -9,6 +10,8 @@ export interface CommandPaletteLinkedThreads {
export interface CommandPaletteOpenDetail {
readonly open?: "add-project" | "new-thread-in";
+ /** With add-project: the draft the new project is picked for. */
+ readonly draftId?: DraftId | null;
readonly query?: string;
readonly linkedThreads?: CommandPaletteLinkedThreads;
}
@@ -20,7 +23,10 @@ export function openCommandPalette(detail: CommandPaletteOpenDetail = {}): void
if (detail.open === "new-thread-in") {
dispatchCommandPalette({ _tag: "OpenNewThreadIn" });
} else if (detail.open === "add-project") {
- dispatchCommandPalette({ _tag: "OpenAddProject" });
+ dispatchCommandPalette({
+ _tag: "OpenAddProject",
+ ...(detail.draftId ? { draftId: detail.draftId } : {}),
+ });
} else if (detail.query !== undefined) {
dispatchCommandPalette({
_tag: "OpenSearch",
diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts
index 8fc6f18fa4bd2..964a8557dd4d6 100644
--- a/apps/web/src/components/CommandPalette.logic.ts
+++ b/apps/web/src/components/CommandPalette.logic.ts
@@ -12,6 +12,7 @@ import {
} from "@t3tools/shared/paletteSearch";
import { threadSearchSubject } from "@t3tools/client-runtime/state/thread-search";
import type { CommandPaletteLinkedThreads } from "../commandPaletteBus";
+import type { DraftId } from "../composerDraftStore";
import {
addProjectRemoteSourceLabel,
addProjectRemoteSourcePathHint,
@@ -80,7 +81,12 @@ export function browseInputEndPaddingClass(input: {
export type SearchOverlayMode = "command" | "files" | "content";
export type CommandPaletteOpenIntent =
- | { readonly kind: "add-project" | "new-thread-in" | "change-theme" }
+ | { readonly kind: "new-thread-in" | "change-theme" }
+ | {
+ readonly kind: "add-project";
+ /** The draft a project is being picked for; one with user content moves to it. */
+ readonly draftId?: DraftId;
+ }
| {
readonly kind: "search";
readonly query: string;
@@ -106,7 +112,7 @@ export type CommandPaletteUiAction =
readonly query: string;
readonly linkedThreads?: CommandPaletteLinkedThreads;
}
- | { readonly _tag: "OpenAddProject" }
+ | { readonly _tag: "OpenAddProject"; readonly draftId?: DraftId }
| { readonly _tag: "OpenNewThreadIn" }
| { readonly _tag: "OpenChangeTheme" }
| {
@@ -161,7 +167,10 @@ export function reduceCommandPaletteUiState(
...(action.linkedThreads ? { linkedThreads: action.linkedThreads } : {}),
});
case "OpenAddProject":
- return openWithIntent({ kind: "add-project" });
+ return openWithIntent({
+ kind: "add-project",
+ ...(action.draftId ? { draftId: action.draftId } : {}),
+ });
case "OpenNewThreadIn":
return openWithIntent({ kind: "new-thread-in" });
case "OpenChangeTheme":
diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx
index 745b96bcdb549..52803134a54a0 100644
--- a/apps/web/src/components/CommandPalette.tsx
+++ b/apps/web/src/components/CommandPalette.tsx
@@ -57,7 +57,9 @@ import {
SourceControlProviderKind,
PRIMARY_LOCAL_ENVIRONMENT_ID,
resolveEnvironmentMachineKind,
+ type ScopedProjectRef,
} from "@t3tools/contracts";
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
import { useLocation, useNavigate } from "@tanstack/react-router";
import {
ArrowLeftIcon,
@@ -106,6 +108,7 @@ import { useDesktopLocalBootstraps } from "../connection/useDesktopLocalBootstra
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
import { copyThreadReference } from "../lib/copyThreadReference";
+import { moveDraftToProject } from "../lib/moveDraftToProject";
import {
queueWorkspaceFocusFromPalette,
restoreWorkspaceFocusFromPalette,
@@ -583,7 +586,25 @@ function OpenCommandPaletteDialog(props: {
const [isCreatingNewProject, setIsCreatingNewProject] = useState(false);
// State lags a render behind, so a repeated Enter could start a second create.
const newProjectSubmittingRef = useRef(false);
- const createNewProject = useNewProject();
+ // "Add project" from a draft's project picker picks the new project for that draft.
+ const [addProjectDraftId] = useState(() =>
+ props.openIntent?.kind === "add-project" ? (props.openIntent.draftId ?? null) : null,
+ );
+ const moveDraftToAddedProject = async (project: EnvironmentProject): Promise => {
+ if (addProjectDraftId === null || !moveDraftToProject(addProjectDraftId, project)) {
+ return false;
+ }
+ await navigate({ to: "/draft/$draftId", params: { draftId: addProjectDraftId } });
+ return true;
+ };
+ const openAddedProject = async (projectRef: ScopedProjectRef): Promise => {
+ // A moved draft is keyed from the project record, so wait for it to reach this client.
+ const project =
+ addProjectDraftId === null ? null : await waitForProject(projectRef, 3_000).catch(() => null);
+ if (project !== null && (await moveDraftToAddedProject(project))) return;
+ await handleNewThread(projectRef);
+ };
+ const createNewProject = useNewProject(openAddedProject);
const cloneLookupGeneration = useRef(0);
const [isRemoteProjectLookingUp, setIsRemoteProjectLookingUp] = useState(false);
const [isRemoteProjectCloning, setIsRemoteProjectCloning] = useState(false);
@@ -2051,6 +2072,10 @@ function OpenCommandPaletteDialog(props: {
input: { projectId: existing.id, archived: false },
}).then((result) => reportProjectFailure(gt("Failed to unarchive project"), result));
}
+ if (await moveDraftToAddedProject(existing)) {
+ setOpen(false);
+ return;
+ }
const latestThread = getLatestThreadForProject(
threads.filter((thread) => thread.environmentId === existing.environmentId),
existing.id,
@@ -2119,7 +2144,7 @@ function OpenCommandPaletteDialog(props: {
}
const navigationResult = await settlePromise(() =>
- handleNewThread(scopeProjectRef(input.environmentId, projectId)),
+ openAddedProject(scopeProjectRef(input.environmentId, projectId)),
);
if (navigationResult._tag === "Failure") {
const error = squashAtomCommandFailure(navigationResult);
@@ -2384,7 +2409,7 @@ function OpenCommandPaletteDialog(props: {
startResult.value.projectId,
);
await waitForProject(projectRef, 3_000).catch(() => null);
- const navigationResult = await settlePromise(() => handleNewThread(projectRef));
+ const navigationResult = await settlePromise(() => openAddedProject(projectRef));
if (navigationResult._tag === "Failure") {
const error = squashAtomCommandFailure(navigationResult);
toastManager.add(
diff --git a/apps/web/src/components/chat/DraftHeroHeadline.tsx b/apps/web/src/components/chat/DraftHeroHeadline.tsx
index 8f55d1ca51ba0..c01ad1ee78fc5 100644
--- a/apps/web/src/components/chat/DraftHeroHeadline.tsx
+++ b/apps/web/src/components/chat/DraftHeroHeadline.tsx
@@ -1,5 +1,5 @@
import type { DraftId } from "~/composerDraftStore";
-import { composerDraftHasUserContent, useComposerDraftStore } from "~/composerDraftStore";
+import { useComposerDraftStore } from "~/composerDraftStore";
import { resolveEnvironmentMachineKind, type ScopedProjectRef } from "@t3tools/contracts";
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
@@ -13,16 +13,11 @@ import { shortcutLabelForCommand } from "~/keybindings";
import { primaryServerKeybindingsAtom } from "~/state/server";
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
import { useOrderWhileOpen } from "~/hooks/useOrderWhileOpen";
+import { moveDraftToProject } from "~/lib/moveDraftToProject";
import { useProjectPin } from "~/hooks/useProjectGroupUpdate";
import { useScratchProject } from "~/hooks/useScratchProject";
import { isTriagePrompt } from "@t3tools/shared/triagePrompt";
-import { useClientSettings } from "~/hooks/useSettings";
-import { seedDraftModelSelection } from "~/lib/seedDraftModelSelection";
-import {
- deriveLogicalProjectKeyFromSettings,
- pickableProjectGroups,
- selectProjectGroupingSettings,
-} from "@t3tools/client-runtime/state/project-grouping";
+import { pickableProjectGroups } from "@t3tools/client-runtime/state/project-grouping";
import {
buildSidebarProjectPickerEntries,
projectGroupsSpanEnvironments,
@@ -71,16 +66,11 @@ export function DraftHeroHeadline({
const projects = useProjects();
const { environments } = useEnvironments();
const primaryEnvironmentId = usePrimaryEnvironmentId();
- const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
- const setLogicalProjectDraftThreadId = useComposerDraftStore(
- (store) => store.setLogicalProjectDraftThreadId,
- );
- const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
// A boolean, so typing in a draft does not re-render the hero.
const isTriageDraftPrompt = useComposerDraftStore((store) =>
draftId ? isTriagePrompt(store.getComposerDraft(draftId)?.prompt ?? "") : false,
);
- const openAddProject = () => openCommandPalette({ open: "add-project" });
+ const openAddProject = () => openCommandPalette({ open: "add-project", draftId });
const { scratchEnvironmentId, scratchWorkspaceRootFor, openScratchProject } = useScratchProject();
const openProjectDraft = useNewThreadHandler();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
@@ -172,19 +162,14 @@ export function DraftHeroHeadline({
? `${session.environmentId}:${session.projectId}:${session.logicalProjectKey}`
: null;
};
- // Retargeting an empty draft would overwrite the project's draft and strand browser tabs.
- const selectProject = (project: (typeof projects)[number], logicalProjectKey: string) => {
+ const selectProject = (project: (typeof projects)[number]) => {
if (!draftId) {
return;
}
pendingScratchRef.current = null;
- const projectRef = scopeProjectRef(project.environmentId, project.id);
- if (!composerDraftHasUserContent(getComposerDraft(draftId))) {
- void openProjectDraft(projectRef);
- return;
+ if (!moveDraftToProject(draftId, project)) {
+ void openProjectDraft(scopeProjectRef(project.environmentId, project.id));
}
- setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId);
- seedDraftModelSelection(draftId, projectRef);
};
const startScratch = async (): Promise => {
if (scratchTargetEnvironmentId === null || isScratchDraft) {
@@ -198,7 +183,7 @@ export function DraftHeroHeadline({
return false;
}
pendingScratchRef.current = null;
- selectProject(project, deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings));
+ selectProject(project);
return true;
};
@@ -229,7 +214,7 @@ export function DraftHeroHeadline({
if (!entry || item.value === activeProjectKey) {
return;
}
- selectProject(entry.targetProject, entry.group.projectKey);
+ selectProject(entry.targetProject);
}}
>
diff --git a/apps/web/src/hooks/useNewProject.ts b/apps/web/src/hooks/useNewProject.ts
index f542435f55552..a4594ad913559 100644
--- a/apps/web/src/hooks/useNewProject.ts
+++ b/apps/web/src/hooks/useNewProject.ts
@@ -7,7 +7,7 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
-import type { EnvironmentId } from "@t3tools/contracts";
+import type { EnvironmentId, ScopedProjectRef } from "@t3tools/contracts";
import { msg } from "gt-react";
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
@@ -16,7 +16,6 @@ import { waitForProject } from "~/state/entities";
import { projectEnvironment } from "~/state/projects";
import { sourceControlEnvironment } from "~/state/sourceControl";
import { useAtomCommand } from "~/state/use-atom-command";
-import { useNewThreadHandler } from "./useHandleNewThread";
import { suggestAppAccessForRemote } from "../components/sourceControlAppAccessToast";
function errorMessage(error: unknown): string {
@@ -25,12 +24,11 @@ function errorMessage(error: unknown): string {
: m(msg("An error occurred."));
}
-export function useNewProject() {
+export function useNewProject(openProject: (projectRef: ScopedProjectRef) => Promise) {
const createNew = useAtomCommand(projectEnvironment.createNew, { reportFailure: false });
const publishRepository = useAtomCommand(sourceControlEnvironment.publishRepository, {
reportFailure: false,
});
- const handleNewThread = useNewThreadHandler();
const publishNewRepository = async (input: {
readonly environmentId: EnvironmentId;
@@ -141,7 +139,7 @@ export function useNewProject() {
return null;
});
if (project === null) return true;
- await handleNewThread(projectRef).catch((error: unknown) => {
+ await openProject(projectRef).catch((error: unknown) => {
toastManager.add(
stackedThreadToast({
type: "error",
diff --git a/apps/web/src/lib/moveDraftToProject.test.ts b/apps/web/src/lib/moveDraftToProject.test.ts
new file mode 100644
index 0000000000000..67ee5c6dd1edc
--- /dev/null
+++ b/apps/web/src/lib/moveDraftToProject.test.ts
@@ -0,0 +1,59 @@
+import { scopeProjectRef } from "@t3tools/client-runtime/environment";
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
+import { EnvironmentId, ProjectId } from "@t3tools/contracts";
+import { beforeEach, describe, expect, it } from "vite-plus/test";
+
+import { DraftId, useComposerDraftStore } from "../composerDraftStore";
+import { moveDraftToProject } from "./moveDraftToProject";
+
+const environmentId = EnvironmentId.make("environment-local");
+const draftId = DraftId.make("draft-1");
+
+function makeProject(name: string): EnvironmentProject {
+ return {
+ id: ProjectId.make(name),
+ environmentId,
+ title: name,
+ workspaceRoot: `/work/${name}`,
+ repositoryIdentity: null,
+ defaultModelSelection: null,
+ createdAt: "2026-03-01T00:00:00.000Z",
+ updatedAt: "2026-03-01T00:00:00.000Z",
+ scripts: [],
+ };
+}
+
+const current = makeProject("current");
+const added = makeProject("added");
+const currentRef = scopeProjectRef(environmentId, current.id);
+const addedRef = scopeProjectRef(environmentId, added.id);
+
+beforeEach(() => {
+ useComposerDraftStore.setState({
+ draftsByThreadKey: {},
+ draftThreadsByThreadKey: {},
+ logicalProjectDraftThreadKeyByLogicalProjectKey: {},
+ });
+ useComposerDraftStore.getState().setProjectDraftThreadId(currentRef, draftId);
+});
+
+describe("moveDraftToProject", () => {
+ it("moves a draft the user wrote in, leaving no draft behind in its old project", () => {
+ const store = useComposerDraftStore.getState();
+ store.setPrompt(draftId, "Plan the next project");
+
+ expect(moveDraftToProject(draftId, added)).toBe(true);
+
+ expect(store.getDraftSessionByProjectRef(addedRef)?.draftId).toBe(draftId);
+ expect(store.getDraftSessionByProjectRef(currentRef)).toBeNull();
+ expect(store.getComposerDraft(draftId)?.prompt).toBe("Plan the next project");
+ });
+
+ it("leaves an empty draft in its project", () => {
+ expect(moveDraftToProject(draftId, added)).toBe(false);
+
+ const store = useComposerDraftStore.getState();
+ expect(store.getDraftSessionByProjectRef(currentRef)?.draftId).toBe(draftId);
+ expect(store.getDraftSessionByProjectRef(addedRef)).toBeNull();
+ });
+});
diff --git a/apps/web/src/lib/moveDraftToProject.ts b/apps/web/src/lib/moveDraftToProject.ts
new file mode 100644
index 0000000000000..290897b305273
--- /dev/null
+++ b/apps/web/src/lib/moveDraftToProject.ts
@@ -0,0 +1,42 @@
+import { scopeProjectRef } from "@t3tools/client-runtime/environment";
+import {
+ deriveLogicalProjectKeyFromSettings,
+ selectProjectGroupingSettings,
+} from "@t3tools/client-runtime/state/project-grouping";
+import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
+
+import {
+ composerDraftHasUserContent,
+ type DraftId,
+ useComposerDraftStore,
+} from "../composerDraftStore";
+import { getClientSettings } from "../hooks/useSettings";
+import { seedDraftModelSelection } from "./seedDraftModelSelection";
+
+/**
+ * Moves an unsent draft the user wrote in to `project`, keeping its content. Returns false for an
+ * empty draft, which the caller should leave alone and open the project's own draft instead:
+ * moving it would replace that draft and strand browser tabs on it.
+ */
+export function moveDraftToProject(draftId: DraftId, project: EnvironmentProject): boolean {
+ const store = useComposerDraftStore.getState();
+ const session = store.getDraftSession(draftId);
+ if (
+ session === null ||
+ session.promotedTo != null ||
+ !composerDraftHasUserContent(store.getComposerDraft(draftId))
+ ) {
+ return false;
+ }
+ const projectRef = scopeProjectRef(project.environmentId, project.id);
+ store.setLogicalProjectDraftThreadId(
+ deriveLogicalProjectKeyFromSettings(
+ project,
+ selectProjectGroupingSettings(getClientSettings()),
+ ),
+ projectRef,
+ draftId,
+ );
+ seedDraftModelSelection(draftId, projectRef);
+ return true;
+}
diff --git a/scripts/scenarios/add-project-takes-the-draft.e2e.ts b/scripts/scenarios/add-project-takes-the-draft.e2e.ts
new file mode 100644
index 0000000000000..b6d79a2ff3a53
--- /dev/null
+++ b/scripts/scenarios/add-project-takes-the-draft.e2e.ts
@@ -0,0 +1,29 @@
+import { expect } from "e2e";
+
+import { test, WEB } from "./t3.ts";
+
+test(
+ "A project added from the draft's project picker takes the draft's prompt with it",
+ WEB,
+ async ({ t3, app, screen, browser }) => {
+ const workspace = await t3.project("demo", { "next/README.md": "" });
+ await t3.open();
+
+ const composer = screen.getByRole("textbox");
+ await composer.fill("Plan the next project");
+ // The draft's project picker has no accessible name of its own.
+ const projectPicker = browser.locator("[data-draft-project-trigger]");
+ await projectPicker.tap();
+ await screen.getByRole("option", "Add project").tap();
+ await screen.getByText("Local folder").tap();
+ await screen.getByRole("combobox").fill(`${workspace}/next`);
+ await browser.keyboard.press("Enter");
+
+ await expect(projectPicker).toHaveText("next");
+ await app.screenshot("after-add");
+ await expect(composer).toContainText("Plan the next project");
+ await expect(
+ screen.getByRole("button", "Plan the next project, Unsent draft", { exact: false }),
+ ).toBeHidden();
+ },
+);
From 2891419b9301d89109c86814aeae639428705508 Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 16:35:57 +0100
Subject: [PATCH 053/238] fix(web): localize terminal excerpt line ranges
(#42886)
Co-authored-by: Julius Marminge
---
.../chat/ComposerPendingTerminalContexts.tsx | 8 +-----
...TerminalContextInlineChip.browser.test.tsx | 27 +++++++++++++++++++
.../chat/TerminalContextInlineChip.tsx | 7 +++--
.../chat/UserMessageContextChips.tsx | 1 -
apps/web/src/i18n/translations/de.json | 2 ++
apps/web/src/i18n/translations/en.json | 2 ++
apps/web/src/i18n/translations/es.json | 2 ++
apps/web/src/i18n/translations/fr.json | 2 ++
apps/web/src/i18n/translations/ja.json | 2 ++
apps/web/src/i18n/translations/ko.json | 2 ++
apps/web/src/i18n/translations/pt-BR.json | 2 ++
apps/web/src/i18n/translations/ru.json | 2 ++
apps/web/src/i18n/translations/sv.json | 2 ++
apps/web/src/i18n/translations/zh.json | 2 ++
14 files changed, 53 insertions(+), 10 deletions(-)
create mode 100644 apps/web/src/components/chat/TerminalContextInlineChip.browser.test.tsx
diff --git a/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx b/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx
index 0e2aa6e27ad96..196b5b37be832 100644
--- a/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx
+++ b/apps/web/src/components/chat/ComposerPendingTerminalContexts.tsx
@@ -1,8 +1,4 @@
-import {
- type TerminalContextDraft,
- formatTerminalContextLabel,
- isTerminalContextExpired,
-} from "~/lib/terminalContext";
+import { type TerminalContextDraft, isTerminalContextExpired } from "~/lib/terminalContext";
import type { ContextPresentationCapability } from "../contextPresentationRegistry";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
@@ -15,12 +11,10 @@ export function ComposerPendingTerminalContextChip({
context,
detailsMode,
}: ComposerPendingTerminalContextChipProps) {
- const label = formatTerminalContextLabel(context);
const expired = isTerminalContextExpired(context);
return (
{
+ initializeI18n(() => {});
+ const translations = await getTranslationsSnapshot("ja");
+ await using screen = await render(
+
+
+ ,
+ );
+
+ await expect.element(screen.getByText(label, { exact: true })).toBeVisible();
+});
diff --git a/apps/web/src/components/chat/TerminalContextInlineChip.tsx b/apps/web/src/components/chat/TerminalContextInlineChip.tsx
index ea2b353b5be03..db048410f9a97 100644
--- a/apps/web/src/components/chat/TerminalContextInlineChip.tsx
+++ b/apps/web/src/components/chat/TerminalContextInlineChip.tsx
@@ -5,7 +5,6 @@ import type { ContextPresentationCapability } from "../contextPresentationRegist
import { ContextChipPopover, ContextChipShell } from "../contextChipParts";
interface TerminalContextInlineChipProps {
- label: string;
terminalLabel: string;
lineStart: number;
lineEnd: number;
@@ -15,8 +14,12 @@ interface TerminalContextInlineChipProps {
}
export function TerminalContextInlineChip(props: TerminalContextInlineChipProps) {
- const { label, terminalLabel, lineStart, lineEnd, text, detailsMode, expired = false } = props;
+ const { terminalLabel, lineStart, lineEnd, text, detailsMode, expired = false } = props;
const gt = useGT();
+ const label =
+ lineStart === lineEnd
+ ? gt("{terminalLabel} line {lineStart}", { terminalLabel, lineStart })
+ : gt("{terminalLabel} lines {lineStart}-{lineEnd}", { terminalLabel, lineStart, lineEnd });
if (!expired && text.length > 0 && detailsMode === "popover") {
return (
diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsx
index 56363dfafb3f4..891bce5296265 100644
--- a/apps/web/src/components/chat/UserMessageContextChips.tsx
+++ b/apps/web/src/components/chat/UserMessageContextChips.tsx
@@ -444,7 +444,6 @@ const userMessageContextPresentationRegistry = createContextPresentationRegistry
record.kind === "terminal" ? (
Date: Wed, 25 Nov 2026 16:37:03 +0100
Subject: [PATCH 054/238] fix(server): separate nested EPUB list items in
attachment text (#42891)
Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com>
Co-authored-by: Julius Marminge
---
.../server/src/provider/documentTextWorker.ts | 30 +++++++++++++++++--
.../src/provider/userInputAttachments.test.ts | 6 +++-
2 files changed, 32 insertions(+), 4 deletions(-)
diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts
index 4c4504a8b6024..0e9604c300bed 100644
--- a/apps/server/src/provider/documentTextWorker.ts
+++ b/apps/server/src/provider/documentTextWorker.ts
@@ -12,7 +12,13 @@ const MAX_EXPANDED = 32 * 1024 * 1024;
const MAX_OUTPUT = 1_000_000;
const CELL_START = Symbol("cell-start");
const CELL_END = Symbol("cell-end");
-type TextPart = string | typeof CELL_START | typeof CELL_END | { fallback: string };
+const LINE_START = Symbol("line-start");
+type TextPart =
+ | string
+ | typeof CELL_START
+ | typeof CELL_END
+ | typeof LINE_START
+ | { fallback: string };
const TRUNCATED = "\n\n[Extracted text truncated at document extraction limits.]";
// Parts the document never displays: the XHTML head, tracked deletions and moves, field codes,
@@ -257,6 +263,7 @@ function* paragraphs(node: XmlNode): Generator {
yield* text(child);
yield "\n";
} else {
+ if (node.name === "li" && ["ol", "ul"].includes(child.name)) yield LINE_START;
yield* paragraphs(child);
if (["li", "div", "section", "dt", "dd"].includes(child.name)) yield "\n";
}
@@ -946,16 +953,24 @@ async function* document(path: string, extension: string): AsyncGenerator {
let result = "";
let remaining = MAX_OUTPUT;
let cellDepth = 0;
let started = false;
let space = false;
+ let midLine = false;
let truncated = false;
try {
// Charge raw text before normalization so repeated whitespace also exhausts the budget.
- for await (const part of document(path, extension)) {
+ for await (let part of document(path, extension)) {
if (part === CELL_START) {
if (cellDepth++ === 0) {
started = false;
@@ -968,6 +983,11 @@ export async function extractDocumentText(path: string, extension: string): Prom
if (cellDepth > 0 && started) space = true;
continue;
}
+ if (part === LINE_START) {
+ // A nested list starts its own line unless its parent item's text already ended one.
+ if (!midLine) continue;
+ part = "\n";
+ }
if (typeof part !== "string" && started) continue;
const raw = typeof part === "string" ? part : part.fallback;
let value = raw.slice(0, remaining).replaceAll("\0", "");
@@ -978,9 +998,13 @@ export async function extractDocumentText(path: string, extension: string): Prom
if (trimmed) {
result += (started && (space || value.startsWith(" ")) ? " " : "") + trimmed;
started = true;
+ midLine = true;
}
space = value.endsWith(" ") || (!value && space);
- } else result += value;
+ } else {
+ result += value;
+ midLine = endsMidLine(value) ?? midLine;
+ }
if (remaining === 0) throw new Truncation("Output budget");
}
} catch (error) {
diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts
index ea61fab1ce990..c7f3a2e9a1cc7 100644
--- a/apps/server/src/provider/userInputAttachments.test.ts
+++ b/apps/server/src/provider/userInputAttachments.test.ts
@@ -1497,7 +1497,8 @@ describe("question answer paths", () => {
"OEBPS/a.xhtml":
'Last chapter
Price 10 8 old
',
"OEBPS/b.xhtml":
- 'My Novel First chapter Larkspur
Direct divDirect sectionDirect item emphasis trailing
Account: A Balance: 731 Currency: USD
Heading Total Important value 731 BeforeAfter Neighbor
Port 443 Timeout 30 seconds Draft note
Hidden block
Hidden nested
Findable note
Decorative note
Prefixed note
',
+ 'My Novel First chapter Larkspur
Direct divDirect sectionDirect item emphasis trailing
Account: A Balance: 731 Currency: USD
Heading Total Important value 731 BeforeAfter Neighbor
Port 443 Timeout 30 seconds Draft note
Hidden block
Hidden nested
Findable note
Decorative note
Prefixed note
Before boardingCheck passportsCompare names Confirm gate Board promptly Before landing
' +
+ "Indented\n ",
"OEBPS/c.xhtml": 'Root hidden
',
},
expected: [
@@ -1513,6 +1514,9 @@ describe("question answer paths", () => {
"Before Inner After\tNeighbor",
"Port\n443\nTimeout\n30 seconds",
"Findable note\nDecorative note\nPrefixed note",
+ "Before boarding\nCheck passports\nCompare names\n\nConfirm gate\n\nBoard promptly",
+ "Before landing\nCollect bags",
+ "Indented\n Alpha",
"## Chapter 2",
"Last chapter",
"Price 10 8 old",
From 0f55a0dc37aa0e79846106f9cf9f4df88cdb8b7c Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 09:49:26 -0600
Subject: [PATCH 055/238] fix(web): empty files and folders in archive previews
show 0 bytes instead of 1 KB (#42900)
Co-authored-by: Julius Marminge
---
apps/mobile/src/i18n/translations/de.json | 1 +
apps/mobile/src/i18n/translations/en.json | 1 +
apps/mobile/src/i18n/translations/es.json | 1 +
apps/mobile/src/i18n/translations/fr.json | 1 +
apps/mobile/src/i18n/translations/ja.json | 1 +
apps/mobile/src/i18n/translations/ko.json | 1 +
apps/mobile/src/i18n/translations/pt-BR.json | 1 +
apps/mobile/src/i18n/translations/ru.json | 1 +
apps/mobile/src/i18n/translations/sv.json | 1 +
apps/mobile/src/i18n/translations/zh.json | 1 +
.../AttachmentFilePreview.browser.test.tsx | 27 +++++++++++++++++++
.../src/state/attachments.test.ts | 2 ++
.../client-runtime/src/state/attachments.ts | 1 +
13 files changed, 40 insertions(+)
diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json
index 3b62045baa01e..9efa66206a9cc 100644
--- a/apps/mobile/src/i18n/translations/de.json
+++ b/apps/mobile/src/i18n/translations/de.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.",
"368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.",
"e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.",
+ "13b14784f8707ddd": "0 Byte",
"b2bc6bd92ea24e5c": "{size} MB",
"88f84178edbb7f57": "{size} KB",
"5a78fd0a1d8e9945": "{count} MB",
diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json
index 2e482d69aa7f4..223ace0c6dd48 100644
--- a/apps/mobile/src/i18n/translations/en.json
+++ b/apps/mobile/src/i18n/translations/en.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host} sent an incompatible server configuration.",
"368c4d4f99c66bfb": "Update the client and server to compatible versions.",
"e5fd422e445391fc": "Upload failed. Tap to retry.",
+ "13b14784f8707ddd": "0 bytes",
"b2bc6bd92ea24e5c": "{size} MB",
"88f84178edbb7f57": "{size} KB",
"5a78fd0a1d8e9945": "{count} MB",
diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json
index 9f513dfccd516..26a58f6c58f64 100644
--- a/apps/mobile/src/i18n/translations/es.json
+++ b/apps/mobile/src/i18n/translations/es.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.",
"368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.",
"e5fd422e445391fc": "Error al subir. Toca para reintentar.",
+ "13b14784f8707ddd": "0 bytes",
"b2bc6bd92ea24e5c": "{size} MB",
"88f84178edbb7f57": "{size} KB",
"5a78fd0a1d8e9945": "{count} MB",
diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json
index 63a62d7f03188..bf46c964394e1 100644
--- a/apps/mobile/src/i18n/translations/fr.json
+++ b/apps/mobile/src/i18n/translations/fr.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.",
"368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.",
"e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.",
+ "13b14784f8707ddd": "0 octet",
"b2bc6bd92ea24e5c": "{size} Mo",
"88f84178edbb7f57": "{size} Ko",
"5a78fd0a1d8e9945": "{count} Mo",
diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json
index f0c24995414d9..480c4e959f147 100644
--- a/apps/mobile/src/i18n/translations/ja.json
+++ b/apps/mobile/src/i18n/translations/ja.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。",
"368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。",
"e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。",
+ "13b14784f8707ddd": "0 バイト",
"b2bc6bd92ea24e5c": "{size} MB",
"88f84178edbb7f57": "{size} KB",
"5a78fd0a1d8e9945": "{count} MB",
diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json
index e0c188e8c878d..34fe2af053545 100644
--- a/apps/mobile/src/i18n/translations/ko.json
+++ b/apps/mobile/src/i18n/translations/ko.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.",
"368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.",
"e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.",
+ "13b14784f8707ddd": "0바이트",
"b2bc6bd92ea24e5c": "{size}MB",
"88f84178edbb7f57": "{size} KB",
"5a78fd0a1d8e9945": "{count} MB",
diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json
index 386b5dc53afbf..72870adc6d774 100644
--- a/apps/mobile/src/i18n/translations/pt-BR.json
+++ b/apps/mobile/src/i18n/translations/pt-BR.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.",
"368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.",
"e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.",
+ "13b14784f8707ddd": "0 bytes",
"b2bc6bd92ea24e5c": "{size} MB",
"88f84178edbb7f57": "{size} KB",
"5a78fd0a1d8e9945": "{count} MB",
diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json
index c3197052b5fa7..7a48ee5eafdd1 100644
--- a/apps/mobile/src/i18n/translations/ru.json
+++ b/apps/mobile/src/i18n/translations/ru.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.",
"368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.",
"e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.",
+ "13b14784f8707ddd": "0 байт",
"b2bc6bd92ea24e5c": "{size} МБ",
"88f84178edbb7f57": "{size} КБ",
"5a78fd0a1d8e9945": "{count} МБ",
diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json
index fa0454bb9f430..a79f24906759e 100644
--- a/apps/mobile/src/i18n/translations/sv.json
+++ b/apps/mobile/src/i18n/translations/sv.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.",
"368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.",
"e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.",
+ "13b14784f8707ddd": "0 byte",
"b2bc6bd92ea24e5c": "{size} MB",
"88f84178edbb7f57": "{size} kB",
"5a78fd0a1d8e9945": "{count} MB",
diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json
index 5eb155844e938..58c5f8b4e70cd 100644
--- a/apps/mobile/src/i18n/translations/zh.json
+++ b/apps/mobile/src/i18n/translations/zh.json
@@ -686,6 +686,7 @@
"56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。",
"368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。",
"e5fd422e445391fc": "上传失败。点按以重试。",
+ "13b14784f8707ddd": "0 字节",
"b2bc6bd92ea24e5c": "{size} MB",
"88f84178edbb7f57": "{size} KB",
"5a78fd0a1d8e9945": "{count} MB",
diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
index 83da950e44993..0a7dc74c1f691 100644
--- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
@@ -289,6 +289,33 @@ describe("bounded binary previews", () => {
}
});
+ it("shows 0 bytes for empty archive entries and folders", async () => {
+ const zip = new JSZip();
+ zip.file("empty.txt", "");
+ zip.folder("empty-dir");
+ zip.file("pkg/__init__.py", "");
+ zip.file("readme.txt", "hello");
+ const bytes = await zip.generateAsync({ type: "arraybuffer" });
+ const src = URL.createObjectURL(new Blob([bytes]));
+ try {
+ await using screen = await render( );
+ const rows = () =>
+ [...screen.container.querySelectorAll("tbody tr")].map((row) =>
+ [...row.querySelectorAll("td")].slice(0, 2).map((cell) => cell.textContent?.trim()),
+ );
+ await vi.waitFor(() => {
+ expect(rows()).toEqual([
+ ["empty-dir", "0 bytes"],
+ ["pkg", "0 bytes"],
+ ["empty.txt", "0 bytes"],
+ ["readme.txt", "1 KB"],
+ ]);
+ }, 10_000);
+ } finally {
+ URL.revokeObjectURL(src);
+ }
+ });
+
it("uses a PAX size override for the following TAR payload and bounds it", async () => {
const archive = (size: string) => {
const header = (name: string, size: number, type: string) => {
diff --git a/packages/client-runtime/src/state/attachments.test.ts b/packages/client-runtime/src/state/attachments.test.ts
index 0860e7fde5eb8..2c26ad67317e3 100644
--- a/packages/client-runtime/src/state/attachments.test.ts
+++ b/packages/client-runtime/src/state/attachments.test.ts
@@ -145,6 +145,8 @@ describe("verifyPersistedAttachmentUpload", () => {
describe("formatAttachmentSize", () => {
it.each([
+ [0, "0 bytes"],
+ [1, "1 KB"],
[1_047_552, "1023 KB"],
[1_047_553, "1.0 MB"],
[1_048_575, "1.0 MB"],
diff --git a/packages/client-runtime/src/state/attachments.ts b/packages/client-runtime/src/state/attachments.ts
index 03494e139f1f6..8bca7348d867b 100644
--- a/packages/client-runtime/src/state/attachments.ts
+++ b/packages/client-runtime/src/state/attachments.ts
@@ -208,6 +208,7 @@ export function formatAttachmentSize(
sizeBytes: number,
resolve: MFunctionType = mFallback,
): string {
+ if (sizeBytes === 0) return resolve(msg("0 bytes"));
const kilobytes = Math.max(1, Math.ceil(sizeBytes / 1024));
// Pick the unit after rounding, so 1023.5 KB reads "1.0 MB", not "1024 KB".
return kilobytes >= 1024
From 9e385083d6255d4f4a94153ed25533f309f0da16 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 07:52:14 -0800
Subject: [PATCH 056/238] fix(client-runtime): a composer send right after Stop
queues instead of failing to steer (#42918)
---
.../src/state/use-thread-composer-state.ts | 10 +++-
.../src/state/threadWorkflows.test.ts | 59 ++++++++++---------
.../src/state/threadWorkflows.ts | 12 ++++
3 files changed, 52 insertions(+), 29 deletions(-)
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index 5033ef4e8e894..278b9eb67599b 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -7,7 +7,10 @@ import { readEnvironmentScope } from "./session";
import { useAtomValue } from "@effect/atom-react";
import { compactBeforeSendTokens } from "@t3tools/client-runtime/state/context-window";
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
-import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows";
+import {
+ runStopRequested,
+ threadSteersDuringCompaction,
+} from "@t3tools/client-runtime/state/thread-workflows";
import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
import {
announcedRun,
@@ -421,7 +424,10 @@ export function useThreadComposerState(input: {
run: selectedThreadProjection?.projection.runs.find((run) => run.id === activeRunId),
messages: selectedThreadMessages,
});
- const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !compactionBlocksSteer;
+ const canSteerActiveTurn =
+ queueWorkflow?.canPromoteToSteer === true &&
+ !compactionBlocksSteer &&
+ !runStopRequested(selectedThreadProjection?.projection, activeRunId);
// A stop or a restart holds the queue, completion wakes included, until it
// is resumed; the queue sheet lists only the user's own messages.
const queueHeld = queueWorkflow?.isHeld === true;
diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts
index fd8092a996a66..d3e522e3cd7cb 100644
--- a/packages/client-runtime/src/state/threadWorkflows.test.ts
+++ b/packages/client-runtime/src/state/threadWorkflows.test.ts
@@ -35,33 +35,38 @@ const capabilities = (input?: {
describe("thread workflows", () => {
it.each([
- ["queue only", { queued: true }, false, false],
- ["session still attaching", undefined, false, true],
- ["native steering", { steer: true }, false, true],
- ["interrupt and restart", { interrupt: true, restartSteer: true }, false, true],
- ["restart without interrupt", { restartSteer: true }, false, false],
- ["explicit compaction", { steer: true }, true, false],
- ] as const)("gates composer steering for %s", (_, turns, compactCommandIsActive, expected) => {
- const projection = {
- thread: { id: "thread", activeProviderThreadId: "provider-thread" },
- runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }],
- providerThreads: [{ id: "provider-thread", providerSessionId: "session" }],
- providerSessions: [
- ...(turns === undefined
- ? []
- : [{ id: "session", status: "running", capabilities: capabilities(turns) }]),
- { id: "other", status: "ready", capabilities: capabilities({ steer: true }) },
- ],
- messages: [],
- } as unknown as OrchestrationV2ThreadProjection;
- expect(
- threadCanSteer(projection, {
- compactCommandIsActive,
- compactionRunning: false,
- activeRunId: projection.runs[0]!.id,
- }),
- ).toBe(expected);
- });
+ ["queue only", { queued: true }, false, false, false],
+ ["session still attaching", undefined, false, false, true],
+ ["native steering", { steer: true }, false, false, true],
+ ["interrupt and restart", { interrupt: true, restartSteer: true }, false, false, true],
+ ["restart without interrupt", { restartSteer: true }, false, false, false],
+ ["explicit compaction", { steer: true }, true, false, false],
+ ["a run Stop has reached", { steer: true }, false, true, false],
+ ] as const)(
+ "gates composer steering for %s",
+ (_, turns, compactCommandIsActive, stopRequested, expected) => {
+ const projection = {
+ thread: { id: "thread", activeProviderThreadId: "provider-thread" },
+ runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }],
+ providerThreads: [{ id: "provider-thread", providerSessionId: "session" }],
+ providerSessions: [
+ ...(turns === undefined
+ ? []
+ : [{ id: "session", status: "running", capabilities: capabilities(turns) }]),
+ { id: "other", status: "ready", capabilities: capabilities({ steer: true }) },
+ ],
+ messages: [],
+ turnItems: stopRequested ? [{ runId: "active", type: "run_interrupt_request" }] : [],
+ } as unknown as OrchestrationV2ThreadProjection;
+ expect(
+ threadCanSteer(projection, {
+ compactCommandIsActive,
+ compactionRunning: false,
+ activeRunId: projection.runs[0]!.id,
+ }),
+ ).toBe(expected);
+ },
+ );
it("skips message history classification when no runs are queued", () => {
let metadataReads = 0;
diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts
index 9e3d1eb4512b2..2931a93ec8fdb 100644
--- a/packages/client-runtime/src/state/threadWorkflows.ts
+++ b/packages/client-runtime/src/state/threadWorkflows.ts
@@ -110,6 +110,17 @@ function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]):
);
}
+/** The server rejects a steer into a run that Stop has reached, though the run still reads as running. */
+export function runStopRequested(
+ projection: Pick | null | undefined,
+ runId: Run["id"] | null | undefined,
+): boolean {
+ if (projection == null || runId == null) return false;
+ return projection.turnItems.some(
+ (item) => item.runId === runId && item.type === "run_interrupt_request",
+ );
+}
+
export function threadCanSteer(
projection: Projection | null,
input: {
@@ -121,6 +132,7 @@ export function threadCanSteer(
const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns;
// A steer submitted before the session attaches can wait for its provider turn.
if (turns && !supportsSteering(turns)) return false;
+ if (runStopRequested(projection, input.activeRunId)) return false;
return !compactionBlocksSteering({
compactCommandIsActive: input.compactCommandIsActive,
compactionRunning: input.compactionRunning,
From 67918f51ccf79e8873349f3dc35c839689dba884 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 08:03:47 -0800
Subject: [PATCH 057/238] fix(web): Show more in Thread Details keeps every
repository listed (#42919)
---
.../chat/ThreadDetailsCard.browser.test.tsx | 68 ++++++++++++++++++-
.../src/components/chat/ThreadDetailsCard.tsx | 4 +-
.../chat/ThreadRepositorySections.tsx | 5 +-
3 files changed, 72 insertions(+), 5 deletions(-)
diff --git a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx
index b03b58e10f4e2..7d5fa03cf1879 100644
--- a/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx
+++ b/apps/web/src/components/chat/ThreadDetailsCard.browser.test.tsx
@@ -1,6 +1,6 @@
import { StrictMode } from "react";
-import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
-import { expect, it } from "vite-plus/test";
+import { EnvironmentId, ProjectId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
+import { expect, it, vi } from "vite-plus/test";
import { page } from "vite-plus/test/browser";
import { act, render } from "../../../test/render";
import { selectThreadPanelOpen, useRightPanelStore } from "../../rightPanelStore";
@@ -8,6 +8,13 @@ import { PopoverCreateHandle } from "../ui/popover";
import { ChatCanvasContext } from "./ChatCanvasContext";
import { resolveChatCanvasLayout } from "./chatCanvasLayout";
import { ThreadDetailsCard } from "./ThreadDetailsCard";
+import { ThreadRepositorySections } from "./ThreadRepositorySections";
+import { useThreadRepositoryPinsStore } from "../../threadRepositoryPinsStore";
+
+vi.mock(import("~/state/query"), async (original) => ({
+ ...(await original()),
+ useEnvironmentQuery: () => ({ data: null, error: null }) as never,
+}));
const threadA: ScopedThreadRef = {
environmentId: EnvironmentId.make("environment"),
@@ -212,3 +219,60 @@ it("stays full while expanded issue rows overflow", async () => {
.element(page.getByRole("region", { name: "Thread details" }))
.toHaveAttribute("data-density", "full");
});
+
+it("keeps the repository list reachable after Show more expands it", async () => {
+ using fixture = setup();
+ for (let index = 1; index <= 30; index++) {
+ useThreadRepositoryPinsStore
+ .getState()
+ .pin(threadB, { repositoryPath: `/repos/repo-${index}`, name: `repo-${index}` });
+ }
+ await using _screen = await render(
+
+ {},
+ measureDetailsCard: () => {},
+ detailsCardTopInset: 0,
+ preferredDetailsCard: placement,
+ detailsCardPlacement: placement,
+ }}
+ >
+
+ {(density) =>
+ // As ThreadDetailsPanel does, essential density drops the repository section.
+ density === "essential" ? null : (
+ {}}
+ explainsEmpty={false}
+ showActions={false}
+ />
+ )
+ }
+
+
+ ,
+ );
+ await page.getByRole("button", { name: "Show 26 more" }).click();
+
+ await expect.element(page.getByRole("button", { name: "Show fewer" })).toBeVisible();
+ await expect
+ .element(page.getByRole("region", { name: "Thread details" }))
+ .not.toHaveAttribute("data-density", "essential");
+});
diff --git a/apps/web/src/components/chat/ThreadDetailsCard.tsx b/apps/web/src/components/chat/ThreadDetailsCard.tsx
index aadb47d0724ce..87fae983e4163 100644
--- a/apps/web/src/components/chat/ThreadDetailsCard.tsx
+++ b/apps/web/src/components/chat/ThreadDetailsCard.tsx
@@ -80,10 +80,10 @@ export function ThreadDetailsCard({
const measure = () => {
const frame = element.closest("[data-thread-details-card]");
const next = element.offsetHeight + (frame ? frame.offsetHeight - frame.clientHeight : 0);
- // PR and issue lists, servers, lineage, side chats and automations scroll as they grow.
+ // PR and issue lists, servers, repositories, lineage, side chats and automations scroll as they grow.
// Counting them toward density would hide the section and workspace controls when the user asks to see more.
const lists = element.querySelectorAll(
- "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-details-issue-list], [data-thread-automations-panel], [data-thread-details-server-overflow]",
+ "[data-thread-relationships-panel], [data-thread-side-chats-panel], [data-thread-details-pr-list], [data-thread-details-issue-list], [data-thread-automations-panel], [data-thread-details-server-overflow], [data-thread-details-repository-overflow]",
);
const fittingHeight =
next - Array.from(lists).reduce((sum, list) => sum + list.offsetHeight, 0);
diff --git a/apps/web/src/components/chat/ThreadRepositorySections.tsx b/apps/web/src/components/chat/ThreadRepositorySections.tsx
index f984037d5a96e..1aece09919816 100644
--- a/apps/web/src/components/chat/ThreadRepositorySections.tsx
+++ b/apps/web/src/components/chat/ThreadRepositorySections.tsx
@@ -77,6 +77,7 @@ const RepositorySection = memo(function RepositorySection(props: {
cwd: string;
removable: boolean;
expanded: boolean;
+ overflow: boolean;
owner: { readonly threadId?: ThreadId; readonly projectId?: ProjectId };
showActions: boolean;
onToggle: (key: string) => void;
@@ -99,6 +100,7 @@ const RepositorySection = memo(function RepositorySection(props: {
setExpandedKey((current) => (current === key ? null : key));
const remove = (key: string) => unpin(threadRef, key);
- const renderSection = (section: ThreadRepositorySection) => (
+ const renderSection = (section: ThreadRepositorySection, index: number) => (
= THREAD_REPOSITORY_SECTIONS_VISIBLE}
owner={owner}
showActions={props.showActions}
onToggle={toggle}
From a76e5547844b11688454f8f41095597d196eccfe Mon Sep 17 00:00:00 2001
From: Theo Browne
Date: Wed, 25 Nov 2026 08:26:40 -0800
Subject: [PATCH 058/238] test(web): Files panel Refresh test no longer fails
on a late tree render (#42935)
Co-authored-by: Claude Opus 5.5
---
.../web/src/components/files/FileBrowserPanel.browser.test.tsx | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
index ecf51be124491..c7c58e689431d 100644
--- a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
+++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx
@@ -373,9 +373,10 @@ describe("FileBrowserPanel", () => {
await vi.waitFor(() => expect(findTreeRow("src/")!.getAttribute("aria-expanded")).toBe("true"));
// Refresh revalidates the folders behind the rows on screen: the open one and the root.
+ // The tree can render its rows again at any time, so compare folders, not calls.
revalidate.mockClear();
await userEvent.click(page.getByRole("button", { name: "Refresh workspace files" }));
- expect(revalidate.mock.calls).toEqual([["src"], [""]]);
+ expect(new Set(revalidate.mock.calls.flat())).toEqual(new Set(["src", ""]));
});
describe("revealing a folder while folders above it are still loading", () => {
const roots = Array.from({ length: 12 }, (_, index): ProjectEntry => {
From 867a9f0aec31d3629b779fb3dc70b2c4ade8e867 Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 17:32:31 +0100
Subject: [PATCH 059/238] fix(terminal): keep line breaks when joining a
running terminal (#42927)
Co-authored-by: Julius Marminge
---
packages/contracts/src/terminal.test.ts | 25 +++++++++++
packages/contracts/src/terminal.ts | 55 ++++++++++++++++++++-----
2 files changed, 70 insertions(+), 10 deletions(-)
diff --git a/packages/contracts/src/terminal.test.ts b/packages/contracts/src/terminal.test.ts
index 16b3ed1d38eb9..dcbb338ccf789 100644
--- a/packages/contracts/src/terminal.test.ts
+++ b/packages/contracts/src/terminal.test.ts
@@ -4,16 +4,41 @@ import { describe, expect, it } from "vite-plus/test";
import {
chunkTerminalWrite,
DEFAULT_TERMINAL_ID,
+ retainTerminalSnapshotHistory,
+ skipTerminalSnapshotContinuation,
TERMINAL_WRITE_MAX_LENGTH,
TerminalError,
TerminalOpenInput,
TerminalProviderEnvironmentError,
+ terminalSequenceStateAfter,
} from "./terminal.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
const encodeTerminalError = Schema.encodeUnknownSync(TerminalError);
const decodeTerminalError = Schema.decodeUnknownSync(TerminalError);
+describe("terminal snapshot replay after an omitted DCS", () => {
+ const pendingDcs = "\u001bPz";
+ const state = terminalSequenceStateAfter(0, pendingDcs);
+
+ it.each([
+ ["a next-line control", "\u0085ready", "\u001bEready"],
+ ["a tab stop before carriage return and tab", "\u0088\r\tready", "\u001bH\r\tready"],
+ ["a byte after a string terminator", "\u1700ready", "\ufffdready"],
+ ])("preserves %s in a continuation", (_name, data, replay) => {
+ expect(skipTerminalSnapshotContinuation(state, data)).toEqual({ state: 0, data: replay });
+ });
+
+ it.each([
+ [8, "\u0085ready", "\u001bEready"],
+ [8, "\u2140ready", "\u001bEready"],
+ [10, "\u2140ready", "\u001bE\ufffdready"],
+ ])("keeps the line break within a %i-byte history budget", (budget, rest, replay) => {
+ const history = pendingDcs + "z".repeat(50) + rest;
+ expect(retainTerminalSnapshotHistory(history, budget)).toEqual({ history: replay });
+ });
+});
+
function decodeSync(schema: S, input: unknown): Schema.Schema.Type {
return Schema.decodeUnknownSync(schema as never)(input) as Schema.Schema.Type;
}
diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts
index 0043f87d0eaed..be05d30a7aa1e 100644
--- a/packages/contracts/src/terminal.ts
+++ b/packages/contracts/src/terminal.ts
@@ -19,7 +19,11 @@ const SEQUENCE_SOS_PM_APC = 5;
const SEQUENCE_OSC = 6;
// Bits above the low three hold a high surrogate until its other half arrives.
-function nextTerminalSequenceState(state: number, unit: number): number {
+function nextTerminalSequenceState(
+ state: number,
+ unit: number,
+ onC1ReturnToGround?: (byte: number, remainingBytes: number) => void,
+): number {
if (unit === 0x1b) return SEQUENCE_ESCAPE;
if (state === TERMINAL_SEQUENCE_GROUND || unit === 0x18 || unit === 0x1a) {
return TERMINAL_SEQUENCE_GROUND;
@@ -62,7 +66,10 @@ function nextTerminalSequenceState(state: number, unit: number): number {
if (byte === 0x90) mode = SEQUENCE_DCS;
else if (byte === 0x9b) mode = SEQUENCE_CSI;
else if (byte === 0x98 || byte >= 0x9e) mode = SEQUENCE_SOS_PM_APC;
- else return TERMINAL_SEQUENCE_GROUND;
+ else {
+ onC1ReturnToGround?.(byte, shift / 6);
+ return TERMINAL_SEQUENCE_GROUND;
+ }
}
return mode;
}
@@ -97,6 +104,25 @@ export function terminalSequenceEnd(state: number, text: string): number {
return index;
}
+function scanSnapshotContinuation(state: number, data: string, limit = data.length) {
+ let control = "";
+ let replacementCount = 0;
+ const replayC1 = (byte: number, remainingBytes: number) => {
+ // Replay IND, NEL, HTS and RI from ground. Any bytes parsed after the control
+ // are now stray UTF-8 continuation bytes.
+ if (byte === 0x84 || byte === 0x85 || byte === 0x88 || byte === 0x8d) {
+ control = "\u001b" + String.fromCharCode(byte - 0x40);
+ }
+ replacementCount = remainingBytes;
+ };
+ let end = 0;
+ while (state !== TERMINAL_SEQUENCE_GROUND && end < limit) {
+ state = nextTerminalSequenceState(state, data.charCodeAt(end), replayC1);
+ end += 1;
+ }
+ return { state, end, control, replacementCount };
+}
+
/** Skip the continuation of an omitted snapshot prefix, retaining any new escape sequence. */
export function skipTerminalSnapshotContinuation(state: number, data: string) {
if (data.length === 0) return { state, data };
@@ -108,17 +134,20 @@ export function skipTerminalSnapshotContinuation(state: number, data: string) {
}
const escape = data.indexOf("\u001b");
- const prefix = escape < 0 ? data : data.slice(0, escape);
- const end = terminalSequenceEnd(state, prefix);
- const next = terminalSequenceStateAfter(state, prefix, 0, end);
- if (next === TERMINAL_SEQUENCE_GROUND || escape < 0) {
- return { state: next, data: data.slice(end) };
+ const {
+ state: next,
+ end,
+ control,
+ replacementCount,
+ } = scanSnapshotContinuation(state, data, escape < 0 ? data.length : escape);
+ if (next === TERMINAL_SEQUENCE_GROUND || end === data.length) {
+ return { state: next, data: control + "\ufffd".repeat(replacementCount) + data.slice(end) };
}
// Hold a final ESC until we know whether it starts a new sequence or completes ST.
- if (escape + 1 === data.length) return { state: SEQUENCE_ESCAPE, data: "" };
+ if (end + 1 === data.length) return { state: SEQUENCE_ESCAPE, data: "" };
return {
state: TERMINAL_SEQUENCE_GROUND,
- data: data.slice(data[escape + 1] === "\\" ? escape + 2 : escape),
+ data: data.slice(data[end + 1] === "\\" ? end + 2 : end),
};
}
@@ -152,7 +181,13 @@ export function retainedTerminalHistory(history: string, maxBytes: number): stri
0,
history.length - retained.length,
);
- return retained.slice(terminalSequenceEnd(state, retained));
+ const { end, control, replacementCount } = scanSnapshotContinuation(state, retained);
+ const tail = retained.slice(end);
+ if (replacementCount === 0) return control + tail;
+ // The two-byte ESC form fits where the consumed code point did. Each replacement
+ // glyph takes three bytes, so keep only as many as fit alongside the control and tail.
+ const available = maxBytes - historyEncoder.encode(tail).byteLength - control.length;
+ return control + "\ufffd".repeat(Math.min(replacementCount, Math.floor(available / 3))) + tail;
}
/** Keep a whole unfinished prefix when possible, or skip its continuation during replay. */
From 4122ddbb16d7b08e0edfd40683003d0de2819a0e Mon Sep 17 00:00:00 2001
From: Simone
Date: Wed, 25 Nov 2026 17:42:22 +0100
Subject: [PATCH 060/238] fix(server): separate ruby readings in EPUB
attachment text (#42911)
Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com>
Co-authored-by: Julius Marminge
---
apps/server/src/provider/documentTextWorker.ts | 18 ++++++++++++++++++
.../src/provider/userInputAttachments.test.ts | 3 ++-
2 files changed, 20 insertions(+), 1 deletion(-)
diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts
index 0e9604c300bed..8d0688b551373 100644
--- a/apps/server/src/provider/documentTextWorker.ts
+++ b/apps/server/src/provider/documentTextWorker.ts
@@ -93,6 +93,22 @@ function collapseOdfWhitespace(paragraph: XmlNode) {
if (tail && afterSpace) tail.node.children[tail.index] = tail.value.slice(0, -1);
}
+function separateRubyReadings(ruby: XmlNode) {
+ const parts = ruby.children.filter((part) =>
+ typeof part === "string"
+ ? part.trim() !== ""
+ : !HIDDEN.has(part.name) && (part.name !== "rp" || part.hasText),
+ );
+ const isFallback = (part: XmlNode | string | undefined) =>
+ typeof part !== "string" && part?.name === "rp";
+ for (const [index, part] of parts.entries()) {
+ if (typeof part === "string" || part.name !== "rt" || !part.hasText) continue;
+ if (isFallback(parts[index - 1]) || isFallback(parts[index + 1])) continue;
+ part.children.unshift("(");
+ part.children.push(")");
+ }
+}
+
function xml(source: string, extension: string): XmlNode {
const odf = [".odt", ".ods", ".odp"].includes(extension);
const root: XmlNode = { name: "root", attrs: {}, children: [] };
@@ -146,6 +162,8 @@ function xml(source: string, extension: string): XmlNode {
parent.children.pop();
return;
}
+ if (extension === ".epub" && node.name === "ruby" && stack[1]?.name === "html")
+ separateRubyReadings(node);
if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return;
if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return;
parent.hasText = true;
diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts
index c7f3a2e9a1cc7..824a9f48422e7 100644
--- a/apps/server/src/provider/userInputAttachments.test.ts
+++ b/apps/server/src/provider/userInputAttachments.test.ts
@@ -1495,7 +1495,7 @@ describe("question answer paths", () => {
"OEBPS/book.opf":
' ',
"OEBPS/a.xhtml":
- 'Last chapter
Price 10 8 old
',
+ 'Last chapter
Price 10 8 old
山路やまみち を歩く。東京( とうきょう ) に着く。川 を見る。海うみ まで。
',
"OEBPS/b.xhtml":
'My Novel First chapter Larkspur
Direct divDirect sectionDirect item emphasis trailing
Account: A Balance: 731 Currency: USD
Heading Total Important value 731 BeforeAfter Neighbor
Port 443 Timeout 30 seconds Draft note
Hidden block
Hidden nested
Findable note
Decorative note
Prefixed note
Before boardingCheck passportsCompare names Confirm gate Board promptly Before landing
' +
"Indented\n ",
@@ -1520,6 +1520,7 @@ describe("question answer paths", () => {
"## Chapter 2",
"Last chapter",
"Price 10 8 old",
+ "山路(やまみち)を歩く。東京(とうきょう)に着く。川を見る。海(うみ) まで。",
"## Chapter 3",
],
absent: [
From 4568a1b7414585f9eae82a955a0d123da3d1ed47 Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 10:47:09 -0600
Subject: [PATCH 061/238] fix(web): unsupported file preview no longer calls
extensionless filenames a file type (#42932)
Co-authored-by: Julius Marminge
---
.../AttachmentFilePreview.browser.test.tsx | 19 +++++++++++++++++++
.../files/AttachmentFilePreview.tsx | 11 ++++++++---
apps/web/src/i18n/translations/de.json | 2 +-
apps/web/src/i18n/translations/en.json | 2 +-
apps/web/src/i18n/translations/es.json | 2 +-
apps/web/src/i18n/translations/fr.json | 2 +-
apps/web/src/i18n/translations/ja.json | 2 +-
apps/web/src/i18n/translations/ko.json | 2 +-
apps/web/src/i18n/translations/pt-BR.json | 2 +-
apps/web/src/i18n/translations/ru.json | 2 +-
apps/web/src/i18n/translations/sv.json | 2 +-
apps/web/src/i18n/translations/zh.json | 2 +-
12 files changed, 37 insertions(+), 13 deletions(-)
diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
index 0a7dc74c1f691..46af0f57af84c 100644
--- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
@@ -2340,3 +2340,22 @@ it.each([
`Unsupported PDF ${directory} asset.`,
);
});
+
+it.each([
+ ["firmware", "Save it to open in an app that supports this format."],
+ [".cache", "Save it to open in an app that supports this format."],
+ ["a.dir/firmware", "Save it to open in an app that supports this format."],
+ ["blob.foo", "Save it to open in an app that supports foo files."],
+] as const)(
+ "describes unsupported binary attachment %s without misreading its name as an extension",
+ async (name, expected) => {
+ const file = new Blob([new Uint8Array([0, 1, 2, 3])], { type: "application/octet-stream" });
+ await using screen = await render(
+ ,
+ );
+ await expect
+ .element(screen.getByText("No preview for this file", { exact: true }))
+ .toBeVisible();
+ await expect.element(screen.getByText(expected, { exact: true })).toBeVisible();
+ },
+);
diff --git a/apps/web/src/components/files/AttachmentFilePreview.tsx b/apps/web/src/components/files/AttachmentFilePreview.tsx
index ba2b69ad7c783..4c7abcc34e0df 100644
--- a/apps/web/src/components/files/AttachmentFilePreview.tsx
+++ b/apps/web/src/components/files/AttachmentFilePreview.tsx
@@ -284,6 +284,11 @@ export function AttachmentFilePreview(props: {
});
};
+ const basename = props.name.split(/[\\/]/).at(-1) ?? "";
+ const dotIndex = basename.lastIndexOf(".");
+ const extension =
+ dotIndex > 0 && dotIndex < basename.length - 1 ? basename.slice(dotIndex + 1) : null;
+
const body = failure ? (
No preview for this file
- {props.name.split(".").at(-1) ? (
+ {extension ? (
- Save it to open in an app that supports {props.name.split(".").at(-1)} files.
+ Save it to open in an app that supports {extension} files.
) : (
- Save it to open in an app that supports this format files.
+ Save it to open in an app that supports this format.
)}
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json
index 24dc666ae6301..c6af3d3c04e4b 100644
--- a/apps/web/src/i18n/translations/de.json
+++ b/apps/web/src/i18n/translations/de.json
@@ -5574,7 +5574,7 @@
},
"-Dateien unterstützt."
],
- "774654575f014b55": "Speichere sie, um sie in einer App zu öffnen, die dieses Dateiformat unterstützt.",
+ "d3170aa2bb08efbd": "Speichere sie, um sie in einer App zu öffnen, die dieses Dateiformat unterstützt.",
"46f943a30e259620": "Audio nicht verfügbar. {name} öffnen",
"e2cf6b944d1d095d": "Audio nicht verfügbar. {name} erneut versuchen",
"f08fb460ad4617d6": "{name} wird geladen",
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index bc506f66b3252..9c06b25632e08 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -5575,7 +5575,7 @@
},
" files."
],
- "774654575f014b55": "Save it to open in an app that supports this format files.",
+ "d3170aa2bb08efbd": "Save it to open in an app that supports this format.",
"46f943a30e259620": "Audio unavailable. Open {name}",
"e2cf6b944d1d095d": "Audio unavailable. Retry {name}",
"f08fb460ad4617d6": "Loading {name}",
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index 23551a07bf28e..578276a00e78d 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -5573,7 +5573,7 @@
},
"."
],
- "774654575f014b55": "Guárdalo para abrirlo en una app compatible con este formato de archivo.",
+ "d3170aa2bb08efbd": "Guárdalo para abrirlo en una app compatible con este formato de archivo.",
"46f943a30e259620": "Audio no disponible. Abrir {name}",
"e2cf6b944d1d095d": "Audio no disponible. Reintentar {name}",
"f08fb460ad4617d6": "Cargando {name}",
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index 91cbcc50b21da..3a26b9305572b 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -5574,7 +5574,7 @@
},
"."
],
- "774654575f014b55": "Enregistrez-le pour l’ouvrir dans une app qui prend en charge ce format de fichier.",
+ "d3170aa2bb08efbd": "Enregistrez-le pour l’ouvrir dans une app qui prend en charge ce format de fichier.",
"46f943a30e259620": "Audio indisponible. Ouvrir {name}",
"e2cf6b944d1d095d": "Audio indisponible. Réessayer {name}",
"f08fb460ad4617d6": "Chargement de {name}",
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index c1556ac19d8a7..1fb5dfff0591d 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -5555,7 +5555,7 @@
},
" ファイルに対応したアプリで開くには、保存してください。"
],
- "774654575f014b55": "この形式のファイルに対応したアプリで開くには、保存してください。",
+ "d3170aa2bb08efbd": "この形式のファイルに対応したアプリで開くには、保存してください。",
"46f943a30e259620": "音声を利用できません。{name} を開く",
"e2cf6b944d1d095d": "音声を利用できません。{name} を再試行",
"f08fb460ad4617d6": "{name} を読み込んでいます",
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index e871b3772a96f..a0ac24a5a0c26 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -5553,7 +5553,7 @@
},
" 파일을 지원하는 앱에서 여세요."
],
- "774654575f014b55": "저장한 후 이 형식을 지원하는 앱에서 여세요.",
+ "d3170aa2bb08efbd": "저장한 후 이 형식을 지원하는 앱에서 여세요.",
"46f943a30e259620": "오디오를 사용할 수 없음. {name} 열기",
"e2cf6b944d1d095d": "오디오를 사용할 수 없음. {name} 다시 시도",
"f08fb460ad4617d6": "{name} 불러오는 중",
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index b70fc50ee9b57..23f825cfae590 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -5573,7 +5573,7 @@
},
"."
],
- "774654575f014b55": "Salve-o para abrir em um app compatível com este formato.",
+ "d3170aa2bb08efbd": "Salve-o para abrir em um app compatível com este formato.",
"46f943a30e259620": "Áudio indisponível. Abrir {name}",
"e2cf6b944d1d095d": "Áudio indisponível. Tentar {name} novamente",
"f08fb460ad4617d6": "Carregando {name}",
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index 94ab0714d3c77..cae6ba120f711 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -5573,7 +5573,7 @@
},
"."
],
- "774654575f014b55": "Сохраните его, чтобы открыть в приложении, поддерживающем файлы этого формата.",
+ "d3170aa2bb08efbd": "Сохраните его, чтобы открыть в приложении, поддерживающем файлы этого формата.",
"46f943a30e259620": "Аудио недоступно. Открыть {name}",
"e2cf6b944d1d095d": "Аудио недоступно. Повторить {name}",
"f08fb460ad4617d6": "Загрузка {name}",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index ee4146130336a..811c6ceabd7fe 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -5574,7 +5574,7 @@
},
"-filer."
],
- "774654575f014b55": "Spara den för att öppna den i en app som stöder det här filformatet.",
+ "d3170aa2bb08efbd": "Spara den för att öppna den i en app som stöder det här filformatet.",
"46f943a30e259620": "Ljudet är inte tillgängligt. Öppna {name}",
"e2cf6b944d1d095d": "Ljudet är inte tillgängligt. Försök igen med {name}",
"f08fb460ad4617d6": "Läser in {name}",
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index bd2e9e6692961..5f4d8cfc31658 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -5579,7 +5579,7 @@
},
" 文件的应用中打开。"
],
- "774654575f014b55": "保存后可在支持此格式文件的应用中打开。",
+ "d3170aa2bb08efbd": "保存后可在支持此格式文件的应用中打开。",
"46f943a30e259620": "音频不可用。打开 {name}",
"e2cf6b944d1d095d": "音频不可用。重试 {name}",
"f08fb460ad4617d6": "正在加载 {name}",
From 41d5875e5de1e1e790fccb945369df23a1d8dd2d Mon Sep 17 00:00:00 2001
From: Marcus Takagi
Date: Thu, 26 Nov 2026 00:55:36 +0800
Subject: [PATCH 062/238] fix(server): Antigravity live sessions no longer
overwrite default thinking levels (#42931)
Co-authored-by: huyuetian
Co-authored-by: Julius Marminge
---
apps/server/scripts/acp-mock-agent.ts | 36 ++++
.../Adapters/AntigravityAdapterV2.ts | 16 +-
.../src/provider/AntigravityProvider.test.ts | 169 ++++++++++++++++++
.../src/provider/AntigravityProvider.ts | 90 ++++++++--
.../Drivers/AntigravityDriver.test.ts | 165 +++++++++++++++++
.../src/provider/Drivers/AntigravityDriver.ts | 8 +-
apps/server/src/provider/ProviderRegistry.ts | 20 ++-
7 files changed, 482 insertions(+), 22 deletions(-)
diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts
index a27eaac473810..567df6929e5dd 100644
--- a/apps/server/scripts/acp-mock-agent.ts
+++ b/apps/server/scripts/acp-mock-agent.ts
@@ -18,6 +18,8 @@ import { beginAcpMockPrompt } from "./acpMockCancellationState.ts";
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
const antigravityProfile = process.env.T3_ACP_ANTIGRAVITY === "1";
+const antigravityThoughtLevel = process.env.T3_ACP_ANTIGRAVITY_THOUGHT_LEVEL === "1";
+const antigravityResumeThoughtLevel = process.env.T3_ACP_RESUME_THOUGHT_LEVEL;
// GitHub Copilot CLI advertises URL-shaped session mode ids.
const copilotModesProfile = process.env.T3_ACP_COPILOT_MODES === "1";
const copilotModeId = (name: string) =>
@@ -124,6 +126,7 @@ let currentModeId = antigravityProfile
? copilotModeId("agent")
: "ask";
let currentModelId = antigravityProfile ? "gemini-test-low" : "default";
+let currentAntigravityThoughtLevel = "high";
let parameterizedModelPicker = false;
let currentReasoning = "medium";
let currentContext = "272k";
@@ -180,6 +183,30 @@ function configOptions(): ReadonlyArray {
currentValue: currentModeId,
options: availableModes.map((mode) => ({ value: mode.id, name: mode.name })),
},
+ ...(antigravityThoughtLevel
+ ? [
+ {
+ configId: "thought_level",
+ name: "Thinking Level",
+ category: "thought_level",
+ type: "select" as const,
+ currentValue: currentAntigravityThoughtLevel,
+ options:
+ currentModelId === "gemini-test-high"
+ ? [
+ { value: "low", name: "Low" },
+ { value: "medium", name: "Medium" },
+ { value: "high", name: "High" },
+ ]
+ : [
+ { value: "low", name: "Low" },
+ { value: "medium", name: "Medium" },
+ { value: "high", name: "High" },
+ { value: "xhigh", name: "Extra" },
+ ],
+ },
+ ]
+ : []),
];
}
if (parameterizedModelPicker) {
@@ -665,6 +692,9 @@ const program = Effect.gen(function* () {
},
});
if (antigravityProfile) {
+ if (antigravityResumeThoughtLevel) {
+ currentAntigravityThoughtLevel = antigravityResumeThoughtLevel;
+ }
yield* publishAntigravityCommands(request.sessionId);
}
return {
@@ -893,6 +923,12 @@ const program = Effect.gen(function* () {
}
if (request.configId === "model" && typeof request.value === "string") {
currentModelId = request.value;
+ if (antigravityProfile && antigravityThoughtLevel) {
+ currentAntigravityThoughtLevel = request.value === "gemini-test-high" ? "medium" : "high";
+ }
+ }
+ if (request.configId === "thought_level" && typeof request.value === "string") {
+ currentAntigravityThoughtLevel = request.value;
}
if (request.configId === "agent" && typeof request.value === "string") {
currentAgent = request.value;
diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
index b8174495e28c7..a2e53801a3b24 100644
--- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts
@@ -101,6 +101,7 @@ export interface AntigravityAdapterV2Options {
readonly onSessionStarted?: (
started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
cwd: string,
+ session?: { readonly resumed: boolean },
) => Effect.Effect;
readonly onSessionEvent?: AcpAdapterV2Flavor["onSessionEvent"];
readonly nativeLogging?: Parameters[0]["nativeLogging"];
@@ -204,13 +205,16 @@ export function makeAntigravityAcpAdapterFlavor(
});
},
start: () =>
- runtime
- .start()
- .pipe(
- Effect.tap(
- (started) => options.onSessionStarted?.(started, input.cwd) ?? Effect.void,
- ),
+ runtime.start().pipe(
+ Effect.tap(
+ (started) =>
+ options.onSessionStarted?.(started, input.cwd, {
+ resumed:
+ input.resumeSessionId !== undefined &&
+ started.sessionId === input.resumeSessionId,
+ }) ?? Effect.void,
),
+ ),
} satisfies typeof runtime;
},
Effect.provideService(SecureRandom.SecureRandom, options.random),
diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts
index 219b4c0f5dbbd..9a2e5b1443060 100644
--- a/apps/server/src/provider/AntigravityProvider.test.ts
+++ b/apps/server/src/provider/AntigravityProvider.test.ts
@@ -589,6 +589,175 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {
}),
);
+ it.effect(
+ "does not let live session thinking-level or model changes overwrite catalog defaults",
+ () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness();
+ yield* harness.initialize;
+ const thinking = (
+ currentValue: string,
+ levels: ReadonlyArray = ["low", "medium", "high", "xhigh"],
+ ) =>
+ ({
+ id: "thought_level",
+ name: "Thinking Level",
+ category: "thought_level",
+ type: "select",
+ currentValue,
+ options: levels.map((value) => ({ value, name: value })),
+ }) satisfies EffectAcpSchema.SessionConfigOption;
+ const catalogModels = {
+ ...modelConfig,
+ currentValue: "neon",
+ options: [
+ { value: "neon", name: "Neon" },
+ { value: "carbon", name: "Carbon" },
+ ],
+ } satisfies EffectAcpSchema.SessionConfigOption;
+ yield* harness.provider.onSessionStarted(
+ {
+ ...started,
+ sessionSetupResult: {
+ sessionId: "session-fresh",
+ configOptions: [catalogModels, thinking("high")],
+ },
+ },
+ "/workspace",
+ );
+
+ // A live chat session setting thought_level=xhigh must not pollute the catalog default.
+ yield* harness.provider.onConfigOptionsUpdated([catalogModels, thinking("xhigh")]);
+ // A live chat session switching to another model with a custom level must neither move
+ // isDefault nor overwrite cached thinking defaults for that model.
+ const switchedToCarbon = {
+ ...catalogModels,
+ currentValue: "carbon",
+ } satisfies EffectAcpSchema.SessionConfigOption;
+ yield* harness.provider.onConfigOptionsUpdated([
+ switchedToCarbon,
+ thinking("low", ["low", "medium", "high"]),
+ ]);
+
+ const snapshot = yield* harness.provider.snapshot.getSnapshot;
+ const neon = snapshot.models.find((model) => model.slug === "neon");
+ const carbon = snapshot.models.find((model) => model.slug === "carbon");
+ expect(neon?.isDefault).toBe(true);
+ expect(neon?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
+ expect(neon?.capabilities?.optionDescriptors?.[0]).toMatchObject({
+ id: "thought_level",
+ currentValue: "high",
+ });
+ expect(carbon?.isDefault).toBeUndefined();
+ expect(carbon?.capabilities?.optionDescriptors).toEqual([]);
+
+ // Updating an observed model's choices keeps its recorded default while still offered,
+ // and falls back if the agent removes that default.
+ yield* harness.provider.onConfigOptionsUpdated([
+ catalogModels,
+ thinking("max", ["low", "medium", "high", "xhigh", "max"]),
+ ]);
+ const expanded = (yield* harness.provider.snapshot.getSnapshot).models.find(
+ (model) => model.slug === "neon",
+ )?.capabilities?.optionDescriptors?.[0];
+ expect(expanded).toMatchObject({
+ id: "thought_level",
+ currentValue: "high",
+ options: [
+ { id: "low" },
+ { id: "medium" },
+ { id: "high" },
+ { id: "xhigh" },
+ { id: "max" },
+ ],
+ });
+
+ yield* harness.provider.onConfigOptionsUpdated([
+ catalogModels,
+ thinking("medium", ["low", "medium"]),
+ ]);
+ const narrowed = (yield* harness.provider.snapshot.getSnapshot).models.find(
+ (model) => model.slug === "neon",
+ )?.capabilities?.optionDescriptors?.[0];
+ expect(narrowed).toMatchObject({
+ id: "thought_level",
+ currentValue: "medium",
+ options: [{ id: "low" }, { id: "medium" }],
+ });
+
+ // A catalog probe records each model's default level and keeps the default model intact.
+ yield* harness.provider.onConfigOptionsUpdated(
+ [switchedToCarbon, thinking("medium", ["low", "medium", "high"])],
+ { fromCatalogProbe: true },
+ );
+ const probed = yield* harness.provider.snapshot.getSnapshot;
+ expect(probed.models.find((model) => model.slug === "neon")?.isDefault).toBe(true);
+ expect(
+ probed.models.find((model) => model.slug === "carbon")?.capabilities
+ ?.optionDescriptors?.[0],
+ ).toMatchObject({ id: "thought_level", currentValue: "medium" });
+
+ // After a restart, resuming a session on another model at xhigh leaves unobserved
+ // models and default identity unset so the registry retains the cached defaults.
+ const restarted = yield* makeHarness();
+ yield* restarted.initialize;
+ yield* restarted.provider.onSessionStarted(
+ {
+ ...started,
+ sessionSetupResult: {
+ sessionId: "session-resumed",
+ configOptions: [switchedToCarbon, thinking("xhigh")],
+ },
+ },
+ "/workspace",
+ { resumed: true },
+ );
+ const merged = mergeProviderSnapshot(
+ probed,
+ yield* restarted.provider.snapshot.getSnapshot,
+ );
+ const mergedNeon = merged.models.find((model) => model.slug === "neon");
+ const mergedCarbon = merged.models.find((model) => model.slug === "carbon");
+ expect(mergedNeon?.isDefault).toBe(true);
+ expect(mergedNeon?.aliases).toContain(ANTIGRAVITY_DEFAULT_MODEL);
+ expect(mergedNeon?.capabilities?.optionDescriptors?.[0]).toMatchObject({
+ id: "thought_level",
+ currentValue: "medium",
+ });
+ expect(mergedCarbon?.isDefault).toBeUndefined();
+ expect(mergedCarbon?.aliases).toBeUndefined();
+ expect(mergedCarbon?.capabilities?.optionDescriptors?.[0]).toMatchObject({
+ id: "thought_level",
+ currentValue: "medium",
+ });
+
+ // A later authoritative session start replaces the cached default model.
+ yield* restarted.provider.onSessionStarted(
+ {
+ ...started,
+ sessionSetupResult: {
+ sessionId: "session-fresh-after-restart",
+ configOptions: [switchedToCarbon, thinking("low", ["low", "medium", "high"])],
+ },
+ },
+ "/workspace",
+ );
+ const updatedAfterFresh = mergeProviderSnapshot(
+ merged,
+ yield* restarted.provider.snapshot.getSnapshot,
+ );
+ expect(updatedAfterFresh.models.find((model) => model.slug === "neon")?.isDefault).toBe(
+ undefined,
+ );
+ expect(updatedAfterFresh.models.find((model) => model.slug === "carbon")?.isDefault).toBe(
+ true,
+ );
+ expect(
+ updatedAfterFresh.models.find((model) => model.slug === "carbon")?.aliases,
+ ).toContain(ANTIGRAVITY_DEFAULT_MODEL);
+ }),
+ );
+
it.effect("does not guess a version before a custom launcher's first handshake", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts
index 434a81a5123eb..2c23ea821f54a 100644
--- a/apps/server/src/provider/AntigravityProvider.ts
+++ b/apps/server/src/provider/AntigravityProvider.ts
@@ -15,6 +15,7 @@ import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
+import * as Equal from "effect/Equal";
import * as FiberHandle from "effect/FiberHandle";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
@@ -73,9 +74,38 @@ function thinkingCapabilities(config: ThinkingConfig | null | undefined) {
return createModelCapabilities({ optionDescriptors: [descriptor] });
}
+function selectOptionValues(config: ThinkingConfig): ReadonlyArray {
+ return config.options.flatMap((entry) =>
+ "value" in entry ? [entry.value] : entry.options.map((option) => option.value),
+ );
+}
+
+function mergeLiveThinkingConfig(
+ existing: ThinkingConfig | null | undefined,
+ next: ThinkingConfig | null,
+): ThinkingConfig | null | undefined {
+ if (existing === undefined) return undefined;
+ if (next === null) return null;
+ if (existing === null) return undefined;
+ return selectOptionValues(next).includes(existing.currentValue)
+ ? { ...next, currentValue: existing.currentValue }
+ : next;
+}
+
+function sessionModelSlug(setup: SessionSetupResult): string | undefined {
+ const config = setup.configOptions?.find(
+ (option) => option.id === "model" || option.category === "model",
+ );
+ return config?.type === "select" ? config.currentValue : setup.models?.currentModelId;
+}
+
export function buildAntigravityModelsFromSession(
setup: SessionSetupResult,
thinkingLevels: AntigravityThinkingLevels = new Map(),
+ options?: {
+ readonly defaultModel?: string | undefined;
+ readonly authoritative?: boolean;
+ },
): ReadonlyArray {
const config = setup.configOptions?.find(
(option) => option.id === "model" || option.category === "model",
@@ -91,6 +121,15 @@ export function buildAntigravityModelsFromSession(
name: model.name,
})) ?? [])
: [];
+ const authoritative = options?.authoritative ?? true;
+ const defaultModel =
+ options?.defaultModel !== undefined
+ ? entries.some((entry) => entry.value === options.defaultModel)
+ ? options.defaultModel
+ : currentValue
+ : authoritative
+ ? currentValue
+ : undefined;
const currentThinking = antigravityThinkingConfig(setup.configOptions);
const seen = new Set();
// The agent can list two IDs under one name; label the later ones so the picker tells them apart.
@@ -102,13 +141,15 @@ export function buildAntigravityModelsFromSession(
const name = names.has(baseName) ? `${baseName} (${entry.value})` : baseName;
names.add(baseName);
const observed =
- entry.value === currentValue ? (currentThinking ?? null) : thinkingLevels.get(entry.value);
+ authoritative && entry.value === currentValue
+ ? (currentThinking ?? null)
+ : thinkingLevels.get(entry.value);
return [
{
slug: entry.value,
name,
isCustom: false,
- ...(entry.value === currentValue
+ ...(entry.value === defaultModel
? { isDefault: true, aliases: [ANTIGRAVITY_DEFAULT_MODEL] }
: {}),
// Levels differ per model; an unobserved model reports none so the registry keeps its cached ones.
@@ -235,14 +276,23 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
// Preserve disk-discovered skills when callbacks replace workspace commands; the registry will not rescan them.
const discoveredSkills = new Map();
const thinkingLevels = new Map();
+ let defaultModelSlug: string | undefined;
const observeThinkingLevels = (
configOptions: ReadonlyArray | null | undefined,
+ authoritative: boolean,
) => {
const model = configOptions?.find(
(option) => option.id === "model" || option.category === "model",
);
- if (model?.type === "select" && model.currentValue) {
- thinkingLevels.set(model.currentValue, antigravityThinkingConfig(configOptions) ?? null);
+ if (model?.type !== "select" || !model.currentValue) return;
+ const next = antigravityThinkingConfig(configOptions) ?? null;
+ if (authoritative) {
+ thinkingLevels.set(model.currentValue, next);
+ return;
+ }
+ const merged = mergeLiveThinkingConfig(thinkingLevels.get(model.currentValue), next);
+ if (merged !== undefined) {
+ thinkingLevels.set(model.currentValue, merged);
}
};
const rememberRuntimeModes = Effect.fn("AntigravityProvider.rememberRuntimeModes")(function* (
@@ -401,9 +451,15 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (
started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
cwd?: string,
+ session?: { readonly resumed?: boolean },
) {
if (!settings.enabled) return;
- observeThinkingLevels(started.sessionSetupResult.configOptions);
+ const authoritative = session?.resumed !== true;
+ if (authoritative) {
+ const modelSlug = sessionModelSlug(started.sessionSetupResult);
+ if (modelSlug) defaultModelSlug = modelSlug;
+ }
+ observeThinkingLevels(started.sessionSetupResult.configOptions, authoritative);
const before = yield* SubscriptionRef.get(metadata);
const supportsTextGeneration = yield* options.supportsTextGeneration;
const updatedAt = DateTime.formatIso(yield* DateTime.now);
@@ -431,7 +487,10 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
label: options.auth?.label ?? "Google account",
},
checkedAt: updatedAt,
- models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels),
+ models: buildAntigravityModelsFromSession(started.sessionSetupResult, thinkingLevels, {
+ defaultModel: defaultModelSlug,
+ authoritative,
+ }),
supportedRuntimeModes,
supportsTextGeneration,
...(cwd
@@ -457,12 +516,20 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* (
configOptions: ReadonlyArray,
+ update?: { readonly fromCatalogProbe?: boolean },
) {
- observeThinkingLevels(configOptions);
- const models = buildAntigravityModelsFromSession({ configOptions }, thinkingLevels);
- yield* SubscriptionRef.update(metadata, (state) => {
- if (state.draft.auth.status !== "authenticated") return state;
- return { ...state, draft: { ...state.draft, models } };
+ // Only catalog probes report a model's default level; live sessions carry per-thread overrides.
+ const authoritative = update?.fromCatalogProbe === true;
+ observeThinkingLevels(configOptions, authoritative);
+ const models = buildAntigravityModelsFromSession({ configOptions }, thinkingLevels, {
+ defaultModel: defaultModelSlug,
+ authoritative,
+ });
+ yield* SubscriptionRef.updateSome(metadata, (state) => {
+ if (state.draft.auth.status !== "authenticated" || Equal.equals(state.draft.models, models)) {
+ return Option.none();
+ }
+ return Option.some({ ...state, draft: { ...state.draft, models } });
});
});
@@ -531,6 +598,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
yield* rememberRuntimeModes(previousModes, RUNTIME_MODES_WITHOUT_AUTO);
discoveredSkills.clear();
thinkingLevels.clear();
+ defaultModelSlug = undefined;
});
const snapshotForCwd = Effect.fn("AntigravityProvider.snapshotForCwd")(function* (
diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts
index 38fbf987d7a88..19451dd10ce16 100644
--- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts
+++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts
@@ -4,19 +4,27 @@ import { expect, it } from "@effect/vitest";
import {
ANTIGRAVITY_DEFAULT_MODEL,
EnvironmentId,
+ MessageId,
+ NodeId,
+ ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ProviderSessionId,
+ RunAttemptId,
+ RunId,
ThreadId,
type AntigravitySettings,
+ type ServerProvider,
} from "@t3tools/contracts";
import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
+import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { HttpClient } from "effect/http";
@@ -703,4 +711,161 @@ it.layer(layerTest)("AntigravityDriver", (it) => {
expect(yield* fs.exists(legacyRoot)).toBe(false);
}),
);
+
+ it.effect.skipIf(windowsHost)(
+ "keeps catalog default thinking levels when a chat session selects another level",
+ () =>
+ Effect.gen(function* () {
+ const h = yield* makeHarness({
+ environment: [
+ { name: "T3_ACP_ANTIGRAVITY_THOUGHT_LEVEL", value: "1" },
+ { name: "T3_ACP_RESUME_THOUGHT_LEVEL", value: "xhigh" },
+ ],
+ });
+ yield* h.refresh();
+ const levelOf = (snapshot: ServerProvider, slug: string) => {
+ const option = snapshot.models
+ .find((model) => model.slug === slug)
+ ?.capabilities?.optionDescriptors?.find(
+ (descriptor) => descriptor.id === "thought_level",
+ );
+ return option?.type === "select" ? option.currentValue : undefined;
+ };
+
+ const refreshed = yield* h.instance.snapshot.getSnapshot;
+ expect(levelOf(refreshed, "gemini-test-low")).toBe("high");
+ expect(levelOf(refreshed, "gemini-test-high")).toBe("medium");
+
+ const threadId = ThreadId.make("thread-antigravity-thought-level");
+ const xhighSelection = {
+ instanceId: h.instance.instanceId,
+ model: "gemini-test-low",
+ options: [{ id: "thought_level", value: "xhigh" }],
+ };
+ const nativeSessionId = yield* Effect.scoped(
+ Effect.gen(function* () {
+ const workspace = yield* h.fs.makeTempDirectoryScoped({ prefix: "t3-ag-thought-" });
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ cwd: workspace,
+ });
+ const session = yield* h.instance.orchestrationAdapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make(
+ "provider-session-antigravity-thought-level",
+ ),
+ modelSelection: xhighSelection,
+ runtimePolicy,
+ });
+ const providerThread = yield* session.ensureThread({
+ threadId,
+ modelSelection: xhighSelection,
+ runtimePolicy,
+ });
+ const now = yield* DateTime.now;
+ yield* session.startTurn({
+ appThread: {
+ createdBy: "user",
+ creationSource: "web",
+ id: threadId,
+ projectId: ProjectId.make("project-antigravity-thought-level"),
+ title: "Antigravity thought level",
+ providerInstanceId: h.instance.instanceId,
+ modelSelection: xhighSelection,
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ activeProviderThreadId: providerThread.id,
+ lineage: {
+ parentThreadId: null,
+ relationshipToParent: null,
+ rootThreadId: threadId,
+ },
+ forkedFrom: null,
+ createdAt: now,
+ updatedAt: now,
+ archivedAt: null,
+ settledOverride: null,
+ settledAt: null,
+ lastVisitedAt: null,
+ deletedAt: null,
+ },
+ threadId,
+ runId: RunId.make("run-antigravity-thought-level"),
+ runOrdinal: 1,
+ providerTurnOrdinal: 1,
+ attemptId: RunAttemptId.make("attempt-antigravity-thought-level"),
+ rootNodeId: NodeId.make("node-antigravity-thought-level"),
+ providerThread,
+ message: {
+ createdBy: "user",
+ creationSource: "web",
+ messageId: MessageId.make("message-antigravity-thought-level"),
+ text: "Say ok.",
+ attachments: [],
+ },
+ modelSelection: xhighSelection,
+ runtimePolicy,
+ });
+ yield* session.events.pipe(
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
+ Stream.runDrain,
+ );
+ const nativeId = providerThread.nativeThreadRef?.nativeId;
+ if (!nativeId) {
+ return yield* Effect.die("Expected Antigravity session to have a native thread id");
+ }
+ return nativeId;
+ }),
+ );
+
+ const afterLiveSession = yield* h.instance.snapshot.getSnapshot;
+ expect(levelOf(afterLiveSession, "gemini-test-low")).toBe("high");
+ expect(levelOf(afterLiveSession, "gemini-test-high")).toBe("medium");
+ expect(
+ afterLiveSession.models.find((model) => model.slug === "gemini-test-low")?.isDefault,
+ ).toBe(true);
+ expect(
+ (yield* h.readRequests)
+ .filter(
+ (request) =>
+ request.method === "session/set_config_option" &&
+ request.params?.configId === "thought_level",
+ )
+ .map((request) => request.params?.value),
+ ).toEqual(["xhigh"]);
+
+ // Resuming a session whose saved level is xhigh must also keep the catalog default.
+ yield* Effect.scoped(
+ Effect.gen(function* () {
+ const workspace = yield* h.fs.makeTempDirectoryScoped({
+ prefix: "t3-ag-thought-resume-",
+ });
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
+ runtimeMode: "approval-required",
+ interactionMode: "default",
+ cwd: workspace,
+ });
+ const resumed = yield* h.instance.orchestrationAdapter.openSession({
+ threadId,
+ providerSessionId: ProviderSessionId.make(
+ "provider-session-antigravity-thought-level-resumed",
+ ),
+ modelSelection: xhighSelection,
+ runtimePolicy,
+ initialNativeThreadId: nativeSessionId,
+ });
+ yield* resumed.ensureThread({
+ threadId,
+ modelSelection: xhighSelection,
+ runtimePolicy,
+ });
+ }),
+ );
+ expect(levelOf(yield* h.instance.snapshot.getSnapshot, "gemini-test-low")).toBe("high");
+ yield* h.assertClosed;
+ }),
+ );
});
diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts
index fa1c5fffa3233..36c8e68123c08 100644
--- a/apps/server/src/provider/Drivers/AntigravityDriver.ts
+++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts
@@ -507,7 +507,7 @@ export const AntigravityDriver: ProviderDriver<
return Deferred.succeed(event.acknowledge, undefined).pipe(Effect.asVoid);
}
if (event._tag === "ConfigOptionsUpdated") {
- return provider.onConfigOptionsUpdated(event.configOptions);
+ return provider.onConfigOptionsUpdated(event.configOptions, { fromCatalogProbe: true });
}
return event._tag === "AvailableCommandsUpdated"
? provider.onAvailableCommands(event.availableCommands)
@@ -631,8 +631,10 @@ export const AntigravityDriver: ProviderDriver<
),
),
profileDirectory,
- onSessionStarted: (started, cwd) =>
- provider.onSessionStarted(started, cwd).pipe(Effect.andThen(authFlow.onSignedInElsewhere)),
+ onSessionStarted: (started, cwd, session) =>
+ provider
+ .onSessionStarted(started, cwd, session)
+ .pipe(Effect.andThen(authFlow.onSignedInElsewhere)),
onSessionEvent: (event, cwd) => {
if (event._tag === "ConfigOptionsUpdated") {
return provider.onConfigOptionsUpdated(event.configOptions);
diff --git a/apps/server/src/provider/ProviderRegistry.ts b/apps/server/src/provider/ProviderRegistry.ts
index 27401b64e64d8..0ef0c74cefe5b 100644
--- a/apps/server/src/provider/ProviderRegistry.ts
+++ b/apps/server/src/provider/ProviderRegistry.ts
@@ -289,14 +289,30 @@ const mergeProviderModels = (
}
const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
+ const preserveDefault =
+ nextModels.length > 0 && !nextModels.some((model) => model.isDefault === true);
const mergedModels = nextModels.map((model) => {
const previousModel = previousBySlug.get(model.slug);
- if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
+ if (!previousModel) {
return model;
}
+ const retainCapabilities = !hasModelCapabilities(model) && hasModelCapabilities(previousModel);
+ const retainDefault = preserveDefault && previousModel.isDefault === true;
+ if (!retainCapabilities && !retainDefault) {
+ return model;
+ }
+ const aliases = retainDefault
+ ? [...new Set([...(model.aliases ?? []), ...(previousModel.aliases ?? [])])]
+ : undefined;
return {
...model,
- capabilities: previousModel.capabilities,
+ ...(retainCapabilities ? { capabilities: previousModel.capabilities } : {}),
+ ...(retainDefault
+ ? {
+ isDefault: true,
+ ...(aliases && aliases.length > 0 ? { aliases } : {}),
+ }
+ : {}),
};
});
const nextSlugs = new Set(nextModels.map((model) => model.slug));
From a3a4592cf53e070aa4dc6f82f6c66ea977f03318 Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 18:01:48 +0100
Subject: [PATCH 063/238] fix(web): release terminal reply ownership when the
drawer closes (#42897)
Co-authored-by: Julius Marminge
---
apps/server/src/terminal/Manager.test.ts | 34 ++++
apps/server/src/terminal/Manager.ts | 15 +-
.../ThreadTerminalDrawer.browser.test.tsx | 163 ++++++++++++++----
.../src/components/ThreadTerminalDrawer.tsx | 73 +++++---
.../terminal/terminalInputWriter.ts | 16 +-
.../src/state/terminalSession.ts | 12 ++
packages/contracts/src/terminal.ts | 9 +
.../terminal-query-after-viewer-closes.e2e.ts | 156 +++++++++++++++++
8 files changed, 419 insertions(+), 59 deletions(-)
create mode 100644 scripts/scenarios/terminal-query-after-viewer-closes.e2e.ts
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts
index dbc3bb95e8adf..9773e2dd19350 100644
--- a/apps/server/src/terminal/Manager.test.ts
+++ b/apps/server/src/terminal/Manager.test.ts
@@ -1013,6 +1013,40 @@ it.layer(
}),
);
+ it.effect("rejects conditional paste chunks when the process has gone", () =>
+ Effect.gen(function* () {
+ const { manager, ptyAdapter } = yield* createManager();
+ const input = openInput();
+ const original = yield* manager.open(input);
+ if (original.pid === null) throw new Error("Expected a running terminal");
+ expect(original.supportsConditionalWrites).toBe(true);
+ const pasteChunk = {
+ threadId: input.threadId,
+ terminalId: original.terminalId,
+ data: "\x1b[200~paste",
+ expectedPid: original.pid,
+ };
+ yield* manager.write(pasteChunk);
+ yield* manager.close({ threadId: input.threadId, terminalId: original.terminalId });
+ expect(yield* manager.write(pasteChunk).pipe(Effect.flip)).toMatchObject({
+ _tag: "TerminalProcessChangedError",
+ });
+ yield* manager.open(input);
+ expect(yield* manager.write(pasteChunk).pipe(Effect.flip)).toMatchObject({
+ _tag: "TerminalProcessChangedError",
+ });
+ yield* manager.write({
+ threadId: input.threadId,
+ terminalId: original.terminalId,
+ data: "after",
+ });
+ expect(ptyAdapter.processes.map(({ writes }) => writes)).toEqual([
+ [pasteChunk.data],
+ ["after"],
+ ]);
+ }),
+ );
+
it.effect("supports multiple terminals per thread independently", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts
index 9aa897b970410..d71f4e2266c9a 100644
--- a/apps/server/src/terminal/Manager.ts
+++ b/apps/server/src/terminal/Manager.ts
@@ -16,6 +16,7 @@ import {
TerminalError,
TerminalHistoryError,
TerminalNotRunningError,
+ TerminalProcessChangedError,
TerminalProviderInstanceNotFoundError,
TerminalProviderEnvironmentError,
TerminalResizeError,
@@ -421,6 +422,7 @@ function snapshot(
worktreePath: session.worktreePath,
status: session.status,
pid: session.pid,
+ supportsConditionalWrites: true,
...snapshotHistory(session, supportsSnapshotSequenceState),
exitCode: session.exitCode,
exitSignal: session.exitSignal,
@@ -3878,8 +3880,19 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const write: TerminalManager["Service"]["write"] = Effect.fn("terminal.write")(
function* (input, viewerId) {
const terminalId = input.terminalId;
- const session = yield* requireSession(input.threadId, terminalId);
+ const found = yield* getSession(input.threadId, terminalId);
+ if (Option.isNone(found)) {
+ if (input.expectedPid !== undefined) return yield* new TerminalProcessChangedError();
+ return yield* new TerminalSessionLookupError({ threadId: input.threadId, terminalId });
+ }
+ const session = found.value;
const process = session.process;
+ if (
+ input.expectedPid !== undefined &&
+ (process?.pid !== input.expectedPid || session.status !== "running")
+ ) {
+ return yield* new TerminalProcessChangedError();
+ }
if (!process || session.status !== "running") {
if (session.status === "exited") return;
return yield* new TerminalNotRunningError({
diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
index 7632d01b5f907..ce66728a146ff 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.browser.test.tsx
@@ -5,9 +5,11 @@ import {
import {
EnvironmentId,
ThreadId,
+ TerminalProcessChangedError,
type ScopedThreadRef,
type FilesystemEntryMetadata,
type ResolvedKeybindingsConfig,
+ type TerminalSummary,
} from "@t3tools/contracts";
import { Cause } from "effect";
import { compileResolvedKeybindingsConfig, DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings";
@@ -23,23 +25,34 @@ import ThreadTerminalDrawer from "./ThreadTerminalDrawer";
const fixture = vi.hoisted(() => ({
statusByThreadId: new Map(),
+ supportsConditionalWrites: true,
pendingSurfaces: [] as Array<() => void>,
typeIntoSurface: null as ((data: string) => void) | null,
pressKey: null as ((event: KeyboardEvent) => boolean) | null,
- writes: [] as Array<{ threadId: string; data: string }>,
+ writes: [] as Array<{ threadId: string; data: string; expectedPid?: number }>,
messages: [] as string[],
resetSessions: () => {},
+ terminalMetadata: (
+ _environmentId: EnvironmentId,
+ ): Atom.Atom>> =>
+ Atom.make(AsyncResult.success([])),
+ setMetadataPid: (_thread: ScopedThreadRef, _pid: number) => {},
setSession: (
_thread: ScopedThreadRef,
_status: "closed" | "starting" | "running",
_version: number,
_generation?: number,
) => {},
- sessionEvent: (_thread: ScopedThreadRef, _type: "snapshot" | "restarted", _pid = 123) => {},
+ sessionEvent: (
+ _thread: ScopedThreadRef,
+ _type: "snapshot" | "restarted" | "closed",
+ _pid = 123,
+ ) => {},
surfaceOptions: [] as GhosttyTerminalSurfaceOptions[],
reportedSize: null as { cols: number; rows: number } | null,
resizeCommand: {},
- runWrite: (): Promise<{ _tag: "Success" }> => Promise.resolve({ _tag: "Success" }),
+ runWrite: (): Promise<{ _tag: "Success" } | AsyncResult.Failure> =>
+ Promise.resolve({ _tag: "Success" }),
runResize: (_input: unknown): Promise> =>
Promise.resolve(AsyncResult.success(undefined)),
metadata: new Map<
@@ -97,6 +110,8 @@ vi.mock("../state/terminalSessions", async () => {
Atom.make({
...EMPTY_TERMINAL_SESSION_STATE,
summary: summary(threadId, 123),
+ pid: 123,
+ supportsConditionalWrites: fixture.supportsConditionalWrites,
status: fixture.statusByThreadId.get(threadId) ?? "closed",
version: 1,
});
@@ -110,6 +125,17 @@ vi.mock("../state/terminalSessions", async () => {
fixture.resetSessions = () => {
sessions = new Map();
};
+ const metadata = Atom.family((_environmentId: EnvironmentId) =>
+ Atom.make>>(
+ AsyncResult.waiting(AsyncResult.success([])),
+ ).pipe(Atom.keepAlive),
+ );
+ fixture.terminalMetadata = metadata;
+ fixture.setMetadataPid = (thread, pid) =>
+ appAtomRegistry.set(
+ metadata(thread.environmentId),
+ AsyncResult.waiting(AsyncResult.success([summary(thread.threadId, pid)])),
+ );
fixture.setSession = (thread, status, version, generation) => {
appAtomRegistry.set(session(thread.environmentId, thread.threadId), {
...EMPTY_TERMINAL_SESSION_STATE,
@@ -125,24 +151,28 @@ vi.mock("../state/terminalSessions", async () => {
const current = appAtomRegistry.get(atom);
appAtomRegistry.set(atom, {
...current,
- summary: summary(thread.threadId, pid),
...applyTerminalAttachStreamEvent(current, {
- type,
threadId: thread.threadId,
terminalId: "term-1",
- snapshot: {
- threadId: thread.threadId,
- terminalId: "term-1",
- cwd: "/repo",
- worktreePath: null,
- status: "running",
- pid,
- history: "",
- exitCode: null,
- exitSignal: null,
- label: "Terminal 1",
- updatedAt: "2026-11-15T00:00:00.000Z",
- },
+ ...(type === "closed"
+ ? { type }
+ : {
+ type,
+ snapshot: {
+ threadId: thread.threadId,
+ terminalId: "term-1",
+ cwd: "/repo",
+ worktreePath: null,
+ status: "running",
+ pid,
+ supportsConditionalWrites: fixture.supportsConditionalWrites,
+ history: "",
+ exitCode: null,
+ exitSignal: null,
+ label: "Terminal 1",
+ updatedAt: "2026-11-15T00:00:00.000Z",
+ },
+ }),
}),
});
};
@@ -157,10 +187,16 @@ vi.mock("../state/session", () => ({
}));
vi.mock("../state/use-atom-command", () => ({
useAtomCommand:
- (command: object) => async (args: { input: { threadId: string; data?: string } }) => {
+ (command: object) =>
+ async (args: { input: { threadId: string; data?: string; expectedPid?: number } }) => {
if (command === fixture.resizeCommand) return fixture.runResize(args);
if (args.input.data !== undefined) {
- fixture.writes.push({ threadId: args.input.threadId, data: args.input.data });
+ const { threadId, data, expectedPid } = args.input;
+ fixture.writes.push({
+ threadId,
+ data,
+ ...(expectedPid === undefined ? {} : { expectedPid }),
+ });
return fixture.runWrite();
}
return { _tag: "Success" };
@@ -173,7 +209,12 @@ vi.mock("../state/server", async () => {
return { serverEnvironment: { configValueAtom: () => config } };
});
vi.mock("../state/terminal", () => ({
- terminalEnvironment: { write: {}, resize: fixture.resizeCommand },
+ terminalEnvironment: {
+ write: {},
+ resize: fixture.resizeCommand,
+ metadata: ({ environmentId }: { environmentId: EnvironmentId }) =>
+ fixture.terminalMetadata(environmentId),
+ },
}));
vi.mock("../state/preview", () => ({ previewEnvironment: { open: {} } }));
vi.mock("../state/projects", async () => {
@@ -264,6 +305,7 @@ function setup(originalStatus: "starting" | "exited" = "exited") {
fixture.reportedSize = null;
fixture.runResize = () => Promise.resolve(AsyncResult.success(undefined));
fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
+ fixture.supportsConditionalWrites = true;
fixture.metadata.clear();
useRightPanelStore.setState(useRightPanelStore.getInitialState());
useTerminalUiStateStore.setState(useTerminalUiStateStore.getInitialState());
@@ -450,12 +492,16 @@ it("drops the rest of a split paste when the shell restarts mid-paste", async ()
});
it.each([
- { pid: 123, closes: true },
- { pid: 456, closes: false },
+ { pid: 123, guarded: true, recovers: true },
+ { pid: 456, guarded: true, recovers: true },
+ { pid: 123, guarded: false, recovers: true },
+ { pid: 456, guarded: false, recovers: false },
])(
- "closes interrupted bracket framing only for its process (PID $pid)",
- async ({ pid, closes }) => {
+ "recovers interrupted paste with conditional writes $guarded and attachment PID $pid",
+ async ({ pid, guarded, recovers }) => {
const { other: threadRef } = setup();
+ fixture.supportsConditionalWrites = guarded;
+ if (!guarded) fixture.setMetadataPid(threadRef, 123);
let settleWrite = () => {};
fixture.runWrite = () =>
new Promise((resolve) => {
@@ -480,14 +526,73 @@ it.each([
expect(
fixture.messages.filter((message) => message.includes("paste interrupted")),
).toHaveLength(1);
- expect(fixture.writes.map(({ data }) => data)).toEqual([
- large.slice(0, 65_536),
- ...(closes ? ["\x1b[201~"] : []),
- "after",
+ const identity = guarded ? { expectedPid: 123 } : {};
+ expect(fixture.writes.map(({ threadId: _, ...write }) => write)).toEqual([
+ { data: large.slice(0, 65_536), ...identity },
+ ...(recovers ? [{ data: "\x1b[201~", ...identity }] : []),
+ { data: "after" },
]);
},
);
+it.each(["metadata first", "closed"] as const)(
+ "clears legacy paste recovery when the process is gone (%s)",
+ async (change) => {
+ const { other: threadRef } = setup();
+ fixture.supportsConditionalWrites = false;
+ fixture.setMetadataPid(threadRef, 123);
+ let failWrite = () => {};
+ fixture.runWrite = () =>
+ new Promise((resolve) => {
+ failWrite = () => {
+ fixture.runWrite = () => Promise.resolve({ _tag: "Success" });
+ resolve(AsyncResult.failure(Cause.die(new Error("acknowledgement lost"))));
+ };
+ });
+ await using _screen = await render( {}} />);
+ await act(async () => {
+ fixture.pendingSurfaces.shift()?.();
+ });
+ const paste = `\x1b[200~${"p".repeat(70_000)}\x1b[201~`;
+ fixture.typeIntoSurface?.(paste);
+ await act(async () => {
+ if (change === "closed") fixture.sessionEvent(threadRef, "closed");
+ else fixture.setMetadataPid(threadRef, 456);
+ failWrite();
+ });
+ expect(fixture.writes.map(({ data }) => data)).toEqual([paste.slice(0, 65_536)]);
+ await act(async () => {
+ // After close, reopen without a PID change to expose any stale recovery obligation.
+ fixture.sessionEvent(threadRef, "snapshot", change === "closed" ? 123 : 456);
+ fixture.typeIntoSurface?.("after");
+ });
+ expect(fixture.writes.map(({ data }) => data)).toEqual([paste.slice(0, 65_536), "after"]);
+ },
+);
+
+it("stops a split paste on its original process once that process is replaced", async () => {
+ const { other: threadRef } = setup();
+ fixture.runWrite = async () =>
+ fixture.writes.length >= 2 && fixture.writes.at(-1)?.expectedPid !== undefined
+ ? AsyncResult.failure(Cause.fail(new TerminalProcessChangedError()))
+ : { _tag: "Success" };
+ await using _screen = await render( {}} />);
+ await act(async () => {
+ fixture.pendingSurfaces.shift()?.();
+ });
+ const paste = `\x1b[200~${"p".repeat(140_000)}\x1b[201~`;
+ await act(async () => {
+ fixture.typeIntoSurface?.(paste);
+ fixture.typeIntoSurface?.("after");
+ });
+ expect(fixture.writes.map(({ data, expectedPid }) => ({ data, expectedPid }))).toEqual([
+ { data: paste.slice(0, 65_536), expectedPid: 123 },
+ { data: paste.slice(65_536, 131_072), expectedPid: 123 },
+ { data: "\x1b[201~", expectedPid: 123 },
+ { data: "after", expectedPid: undefined },
+ ]);
+});
+
it("closes an interrupted paste after disposal before input from a remounted view", async () => {
const { other: threadRef } = setup();
let settleWrite = () => {};
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index b3871f5b28970..9bc43233585d7 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -29,6 +29,7 @@ import {
AuthFilesystemReadScope,
AuthOrchestrationOperateScope,
AuthTerminalOperateScope,
+ TerminalProcessChangedError,
type ContextMenuItem,
type ProviderInstanceId,
type ResolvedKeybindingsConfig,
@@ -451,6 +452,8 @@ function terminalContextMenuItems(options: {
];
}
+const isTerminalProcessChanged = Schema.is(TerminalProcessChangedError);
+
/**
* A writable session's output generation. A new one is a fresh PTY (or a
* reconnect) that has not seen the surface's grid yet.
@@ -962,14 +965,17 @@ function TerminalSessionViewport({
}
};
- const readInputSession = () => appAtomRegistry.get(terminalSessionAtom);
const canWriteInput = () => readEnvironmentScope(environmentId, AuthTerminalOperateScope);
- const writeInputChunk = (data: string, kind?: "binary" | "reply") =>
+ const writeInputChunk = (data: string, kind?: "binary" | "reply", expectedPid?: number) =>
retainedTerminalWrite.current({
environmentId,
- input: kind
- ? { threadId, terminalId, data, [kind]: true }
- : { threadId, terminalId, data },
+ input: {
+ threadId,
+ terminalId,
+ data,
+ ...(kind === undefined ? {} : { [kind]: true }),
+ ...(expectedPid === undefined ? {} : { expectedPid }),
+ },
});
const sendTerminalInput = (
data: string,
@@ -984,7 +990,6 @@ function TerminalSessionViewport({
if (generation === null) return;
const writeInput = terminalInputWriter(
JSON.stringify([environmentId, threadId, terminalId]),
- () => appAtomRegistry.mount(terminalSessionAtom),
);
let reported = false;
const report = (message: string) => {
@@ -994,35 +999,63 @@ function TerminalSessionViewport({
};
return writeInput(
data,
- async (chunk) => {
- const currentSession = readInputSession();
+ async (chunk, split) => {
+ if (terminalRef.current !== terminal) return "not-dispatched";
+ const currentSession = appAtomRegistry.get(terminalSessionAtom);
if (
- terminalRef.current !== terminal ||
currentSession.lifecycleVersion !== lifecycleVersion ||
writableSessionGeneration(currentSession, canWriteInput()) !== generation
) {
return "not-dispatched";
}
- const result = await writeInputChunk(chunk, kind);
+ const expectedPid =
+ split && session.supportsConditionalWrites ? session.pid : undefined;
+ if (expectedPid === null) return "not-dispatched";
+ const result = await writeInputChunk(chunk, kind, expectedPid);
if (result._tag === "Success") return true;
+ const error = squashAtomCommandFailure(result);
+ if (isTerminalProcessChanged(error)) return "not-dispatched";
if (terminalRef.current === terminal && !isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
report(thrownErrorMessage(error, m) ?? fallbackError);
}
return false;
},
- // Close the bracket only for the process that saw it open; wait while its pid is unknown.
+ // The attachment's PID stays with the paste even after the viewport detaches.
async () => {
- const pid = session.summary?.pid ?? null;
- const current = readInputSession();
- const currentPid = current.summary?.pid ?? null;
- if (currentPid === null) return false;
- if (pid !== null && currentPid !== pid) return true;
- if (writableSessionGeneration(current, canWriteInput()) === null) return false;
- const result = await writeInputChunk("\x1b[201~");
+ if (session.pid === null) return true;
+ if (!canWriteInput()) return false;
+ if (!session.supportsConditionalWrites) {
+ const attached =
+ terminalRef.current === terminal ? appAtomRegistry.get(terminalSessionAtom) : null;
+ if (attached && attached.version > 0) {
+ if (attached.status === "closed" || attached.status === "exited") return true;
+ if (attached.pid !== null && attached.pid !== session.pid) return true;
+ }
+ const metadata = appAtomRegistry.get(
+ terminalEnvironment.metadata({ environmentId, input: null }),
+ );
+ if (!AsyncResult.isSuccess(metadata)) return false;
+ const current = metadata.value.find(
+ (item) => item.threadId === threadId && item.terminalId === terminalId,
+ );
+ if (current?.pid == null) return false;
+ if (attached) {
+ // An unguarded write needs both streams to agree the original PTY is running.
+ if (attached.status !== "running" || attached.pid !== current.pid) return false;
+ } else if (current.pid !== session.pid || current.status === "exited") {
+ return true;
+ }
+ if (current.status !== "running" || current.pid !== session.pid) return false;
+ }
+ const result = await writeInputChunk(
+ "\x1b[201~",
+ undefined,
+ session.supportsConditionalWrites ? session.pid : undefined,
+ );
if (result._tag === "Success") return true;
+ const error = squashAtomCommandFailure(result);
+ if (isTerminalProcessChanged(error)) return true;
if (!isAtomCommandInterrupted(result)) {
- const error = squashAtomCommandFailure(result);
report(thrownErrorMessage(error, m) ?? m(msg("Failed to close interrupted paste")));
}
return false;
diff --git a/apps/web/src/components/terminal/terminalInputWriter.ts b/apps/web/src/components/terminal/terminalInputWriter.ts
index 4d269ae86eab4..ab7e7033ee7e2 100644
--- a/apps/web/src/components/terminal/terminalInputWriter.ts
+++ b/apps/web/src/components/terminal/terminalInputWriter.ts
@@ -1,7 +1,7 @@
import { chunkTerminalWrite } from "@t3tools/contracts";
/** Sends one chunk of terminal input; resolves false when it failed and the rest should drop. */
-type SendTerminalChunk = (chunk: string) => Promise;
+type SendTerminalChunk = (chunk: string, split: boolean) => Promise;
/**
* Orders one terminal's input into writes that fit `terminal.write`. A split write goes one chunk
@@ -30,15 +30,15 @@ export function createTerminalInputWriter(onIdle = () => {}) {
interrupted();
return;
}
- const bracketed =
- chunks.length > 1 && data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~");
+ const split = chunks.length > 1;
+ const bracketed = split && data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~");
let opened = false;
try {
for (const chunk of chunks) {
- const result = await send(chunk);
+ const result = await send(chunk, split);
if (result !== true) {
if (result !== "not-dispatched") opened = bracketed;
- if (chunks.length > 1) interrupted();
+ if (split) interrupted();
return;
}
opened = bracketed;
@@ -55,7 +55,7 @@ export function createTerminalInputWriter(onIdle = () => {}) {
return (
data: string,
send: SendTerminalChunk,
- recover: () => Promise = async () => (await send("\x1b[201~")) === true,
+ recover: () => Promise = async () => (await send("\x1b[201~", true)) === true,
interrupted = () => {},
): Promise => {
const idle = () => {
@@ -93,13 +93,11 @@ export function createTerminalInputWriter(onIdle = () => {}) {
const writers = new Map>();
/** Retain ordering and framing obligations until acknowledged, across terminal view remounts. */
-export function terminalInputWriter(key: string, retain: () => () => void) {
+export function terminalInputWriter(key: string) {
const existing = writers.get(key);
if (existing) return existing;
- const release = retain();
const writer = createTerminalInputWriter(() => {
if (writers.get(key) === writer) writers.delete(key);
- release();
});
writers.set(key, writer);
return writer;
diff --git a/packages/client-runtime/src/state/terminalSession.ts b/packages/client-runtime/src/state/terminalSession.ts
index 4eb84e9b192ae..6ad955c32afc9 100644
--- a/packages/client-runtime/src/state/terminalSession.ts
+++ b/packages/client-runtime/src/state/terminalSession.ts
@@ -34,6 +34,8 @@ export interface TerminalGrid {
export interface TerminalSessionState {
readonly summary: TerminalSummary | null;
+ readonly pid: number | null;
+ readonly supportsConditionalWrites: boolean;
readonly output: TerminalOutputState;
/** Null when the server predates shared terminal geometry. */
readonly grid: TerminalGrid | null;
@@ -46,6 +48,8 @@ export interface TerminalSessionState {
}
export interface TerminalBufferState {
+ readonly pid: number | null;
+ readonly supportsConditionalWrites: boolean;
readonly output: TerminalOutputState;
readonly grid: TerminalGrid | null;
readonly status: TerminalSessionSnapshot["status"] | "closed";
@@ -75,6 +79,8 @@ export function selectRunningSubprocessTerminalIds(
}
export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze({
+ pid: null,
+ supportsConditionalWrites: false,
output: EMPTY_TERMINAL_OUTPUT_STATE,
grid: null,
status: "closed",
@@ -86,6 +92,8 @@ export const EMPTY_TERMINAL_BUFFER_STATE = Object.freeze({
export const EMPTY_TERMINAL_SESSION_STATE = Object.freeze({
summary: null,
+ pid: null,
+ supportsConditionalWrites: false,
output: EMPTY_TERMINAL_OUTPUT_STATE,
grid: null,
status: "closed",
@@ -115,6 +123,8 @@ function terminalBufferStateFromSnapshot(
current: TerminalBufferState = EMPTY_TERMINAL_BUFFER_STATE,
): TerminalBufferState {
return {
+ pid: snapshot.pid,
+ supportsConditionalWrites: snapshot.supportsConditionalWrites === true,
output: resetOutput(current.output, snapshot, maxBufferBytes),
grid: nextGrid(current.grid, snapshot),
status: snapshot.status,
@@ -147,6 +157,8 @@ export function combineTerminalSessionState(
): TerminalSessionState {
return {
summary,
+ pid: buffer.pid,
+ supportsConditionalWrites: buffer.supportsConditionalWrites,
output: buffer.output,
grid: buffer.grid,
status: buffer.version > 0 ? buffer.status : (summary?.status ?? buffer.status),
diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts
index be05d30a7aa1e..93d5164e9b98b 100644
--- a/packages/contracts/src/terminal.ts
+++ b/packages/contracts/src/terminal.ts
@@ -283,6 +283,8 @@ export const TerminalWriteInput = Schema.Struct({
// A renderer's answer to a terminal query (DA, DSR, DECRQM). Every attached renderer
// answers, so the server passes on one viewer's replies; older servers ignore it.
reply: Schema.optionalKey(Schema.Boolean),
+ // Reject the write if the process that owns the paste has gone.
+ expectedPid: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),
});
export type TerminalWriteInput = Schema.Codec.Encoded;
@@ -329,6 +331,7 @@ export const TerminalSessionSnapshot = Schema.Struct({
worktreePath: Schema.NullOr(TrimmedNonEmptyStringSchema),
status: TerminalSessionStatus,
pid: Schema.NullOr(Schema.Int.check(Schema.isGreaterThan(0))),
+ supportsConditionalWrites: Schema.optional(Schema.Boolean),
history: Schema.String,
// Parser state of an unfinished prefix omitted after the replayable history.
historySequenceState: Schema.optional(
@@ -605,6 +608,11 @@ export class TerminalResizeError extends Schema.TaggedError
}
}
+export class TerminalProcessChangedError extends Schema.TaggedError()(
+ "TerminalProcessChangedError",
+ {},
+) {}
+
export const TerminalError = Schema.Union([
TerminalCwdError,
TerminalHistoryError,
@@ -612,6 +620,7 @@ export const TerminalError = Schema.Union([
TerminalProviderInstanceNotFoundError,
TerminalProviderEnvironmentError,
TerminalNotRunningError,
+ TerminalProcessChangedError,
TerminalWriteError,
TerminalResizeError,
]);
diff --git a/scripts/scenarios/terminal-query-after-viewer-closes.e2e.ts b/scripts/scenarios/terminal-query-after-viewer-closes.e2e.ts
new file mode 100644
index 0000000000000..d51087e0641cc
--- /dev/null
+++ b/scripts/scenarios/terminal-query-after-viewer-closes.e2e.ts
@@ -0,0 +1,156 @@
+///
+import { expect } from "e2e";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+
+import { runPromise, test, WEB } from "./t3.ts";
+
+const PROBE = String.raw`import { existsSync, writeFileSync } from "node:fs";
+const file = (name) => new URL(name, import.meta.url);
+const ask = () => process.stdout.write("\x1b[6n");
+let buffer = "";
+let secondQuery = false;
+process.stdin.setRawMode(true);
+process.stdin.on("data", (chunk) => {
+ buffer += chunk.toString();
+ if (buffer.includes("s")) writeFileSync(file("second-ready"), "ready");
+ if (!/\x1b\[\d+;\d+R/.test(buffer)) return;
+ buffer = buffer.replace(/\x1b\[\d+;\d+R/, "");
+ if (secondQuery) {
+ writeFileSync(file("answer"), "reply received");
+ process.stdout.write("\r\nReply received\r\n");
+ } else {
+ writeFileSync(file("first-ready"), "ready");
+ }
+});
+ask();
+const timer = setInterval(() => {
+ if (!existsSync(file("ask-again"))) return;
+ clearInterval(timer);
+ secondQuery = true;
+ process.stdout.write("\r\nWaiting for cursor position...\r\n");
+ ask();
+}, 50);
+`;
+
+test(
+ "A second viewer answers terminal queries after the first viewer closes during a pending write",
+ WEB,
+ async ({ t3, app, browser, screen }) => {
+ await browser.emulateMedia({ colorScheme: "dark" });
+ const project = await t3.project("demo", { "cursor-probe.mjs": PROBE });
+ const thread = await t3.thread({ project, title: "Shared terminal", messages: ["hello"] });
+ const read = (name: string) =>
+ runPromise(
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ return yield* fs.readFileString(`${project}/${name}`);
+ }).pipe(Effect.orElseSucceed(() => "")),
+ );
+
+ // Delay one ordinary keystroke on the first connection to model a write in flight.
+ await browser.addInitScript(() => {
+ if (window !== window.top) return;
+ const send = WebSocket.prototype.send;
+ WebSocket.prototype.send = function (data) {
+ if (
+ document.body?.dataset.holdTerminalWrite === "true" &&
+ typeof data === "string" &&
+ data.includes('"data":"x"')
+ ) {
+ document.body.dataset.terminalWritePending = "true";
+ const socket = this;
+ window.addEventListener("release-terminal-write", () => send.call(socket, data), {
+ once: true,
+ });
+ return;
+ }
+ return send.call(this, data);
+ };
+ });
+
+ await t3.open(thread);
+ const toggle = screen.getByRole("button", "Toggle terminal drawer");
+ const first = screen.getByLabel("Terminal input");
+ await browser.evaluate(() => {
+ const frame = document.createElement("iframe");
+ frame.id = "second-viewer";
+ frame.src = location.pathname;
+ frame.style.cssText =
+ "position:fixed;inset:0;width:100%;height:100%;border:0;z-index:2147483647";
+ document.body.append(frame);
+ return null;
+ });
+ const second = browser.frameLocator("#second-viewer");
+ const secondInput = second.getByLabel("Terminal input");
+ const secondToggle = second.getByRole("button", "Toggle terminal drawer");
+ await secondToggle.waitFor();
+ const showSecond = (show: boolean) =>
+ browser.evaluate((visible) => {
+ document.querySelector("#second-viewer")!.style.display = visible
+ ? ""
+ : "none";
+ return null;
+ }, show);
+ await showSecond(false);
+ await toggle.tap();
+ await expect
+ .poll(
+ async () => {
+ await first.focus();
+ await browser.keyboard.type(`echo ready > '${project}/shell-ready'`);
+ await browser.keyboard.press("Enter");
+ return read("shell-ready");
+ },
+ { timeout: 20_000 },
+ )
+ .toBe("ready\n");
+ await browser.keyboard.type(`'${process.execPath}' '${project}/cursor-probe.mjs'`);
+ await browser.keyboard.press("Enter");
+ await expect.poll(() => read("first-ready")).toBe("ready");
+
+ await showSecond(true);
+ await secondToggle.tap();
+ await secondInput.waitFor();
+ await expect
+ .poll(async () => {
+ await secondInput.focus();
+ await browser.keyboard.type("s");
+ return read("second-ready");
+ })
+ .toBe("ready");
+
+ await showSecond(false);
+ await first.focus();
+ await browser.evaluate(() => {
+ document.body.dataset.holdTerminalWrite = "true";
+ return null;
+ });
+ await browser.keyboard.type("x");
+ await expect
+ .poll(() => browser.evaluate(() => document.body.dataset.terminalWritePending ?? ""))
+ .toBe("true");
+
+ try {
+ await toggle.tap();
+ await first.waitFor({ state: "hidden" });
+ await showSecond(true);
+ await runPromise(
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.writeFileString(`${project}/ask-again`, "");
+ }),
+ );
+ try {
+ await expect.poll(() => read("answer")).toBe("reply received");
+ } finally {
+ await app.screenshot("query-after-first-viewer-closes");
+ }
+ } finally {
+ await browser.evaluate(() => {
+ window.dispatchEvent(new Event("release-terminal-write"));
+ return null;
+ });
+ }
+ },
+);
From 1c4622955aa6f961eddf7e024a741c0993013cbe Mon Sep 17 00:00:00 2001
From: xandev641 <143331243+xandev641@users.noreply.github.com>
Date: Wed, 25 Nov 2026 18:02:29 +0100
Subject: [PATCH 064/238] fix(mobile): keep CSV headings below the iPad
navigation bar (#42928)
Co-authored-by: Xander von Itzenplitz
Co-authored-by: Julius Marminge
---
apps/mobile/src/features/files/DelimitedFilePreview.tsx | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/apps/mobile/src/features/files/DelimitedFilePreview.tsx b/apps/mobile/src/features/files/DelimitedFilePreview.tsx
index 281f4a3a8fdaa..c07cce86bb78c 100644
--- a/apps/mobile/src/features/files/DelimitedFilePreview.tsx
+++ b/apps/mobile/src/features/files/DelimitedFilePreview.tsx
@@ -3,6 +3,7 @@ import { useGT } from "gt-react-native";
import { ScrollView, View } from "react-native";
import type { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
import { AppText as Text } from "../../components/ui/AppText";
+import { NativeScrollView } from "../../native/NativeScrollViewMarker";
import { FilePreviewNotice } from "./FilePreviewFeedback";
export function DelimitedFilePreview(props: {
@@ -10,7 +11,7 @@ export function DelimitedFilePreview(props: {
}) {
const gt = useGT();
return (
-
+
{props.table.truncated ? (
{gt("Table limited to the first 100 rows and 30 columns. Source shows the rest.")}
@@ -38,6 +39,6 @@ export function DelimitedFilePreview(props: {
))}
-
+
);
}
From 6bb4e3d9d647cc5bf8ea15751a0caab931ae064f Mon Sep 17 00:00:00 2001
From: Shadman Taqi <61359614+iamshadmantaqi@users.noreply.github.com>
Date: Wed, 25 Nov 2026 23:06:24 +0600
Subject: [PATCH 065/238] fix(web): comment timestamps follow 'Open links in'
(#42873)
Co-authored-by: Julius Marminge
---
.../issue/IssueDetailPanel.browser.test.tsx | 51 ++++++++++++++++---
.../src/components/issue/IssueDetailPanel.tsx | 4 ++
.../PullRequestSummaryTab.browser.test.tsx | 45 ++++++++++++++++
.../pullRequest/PullRequestSummaryTab.tsx | 18 +++++--
4 files changed, 107 insertions(+), 11 deletions(-)
diff --git a/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx b/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx
index 7b9755435a1e9..064add4ebeeb3 100644
--- a/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx
+++ b/apps/web/src/components/issue/IssueDetailPanel.browser.test.tsx
@@ -68,18 +68,26 @@ vi.mock(import("~/state/issues"), async (original) => {
import { IssueDetailPanel } from "./IssueDetailPanel";
+const reference = {
+ projectId: "project-1" as never,
+ tracker: "github" as never,
+ scope: "owner/repo",
+ key: "7",
+};
+
+function setComments(comments: IssueDetail["comments"]) {
+ state.openLink.mockClear();
+ (detail as { comments: unknown }).comments = comments;
+}
+
describe("IssueDetailPanel", () => {
it("opens the issue number through the link-target setting, not a popup", async () => {
+ setComments([]);
const threadRef = { environmentId: "env-1", threadId: "thread-1" } as never;
await using screen = await render(
,
);
@@ -91,4 +99,35 @@ describe("IssueDetailPanel", () => {
expect(state.openLink).toHaveBeenCalledOnce();
expect(state.openLink).toHaveBeenCalledWith(url, { event: expect.anything() });
});
+
+ it("opens a comment's timestamp through the link-target setting, not a popup", async () => {
+ const commentUrl = `${url}#issuecomment-1`;
+ setComments([
+ {
+ id: "1",
+ author: null,
+ body: "Same here",
+ createdAt: "2026-01-02T00:00:00.000Z",
+ url: commentUrl,
+ },
+ ]);
+ await using screen = await render(
+ ,
+ );
+ const link = await vi.waitFor(() => {
+ const found = screen.container.querySelector(`a[href="${commentUrl}"]`);
+ expect(found).not.toBeNull();
+ return found!;
+ });
+ const click = new MouseEvent("click", { bubbles: true, cancelable: true });
+ link.dispatchEvent(click);
+
+ expect(click.defaultPrevented).toBe(true);
+ expect(state.openLink).toHaveBeenCalledOnce();
+ expect(state.openLink).toHaveBeenCalledWith(commentUrl, { event: expect.anything() });
+ });
});
diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx
index 38d803e896779..9bdc1cd820a6a 100644
--- a/apps/web/src/components/issue/IssueDetailPanel.tsx
+++ b/apps/web/src/components/issue/IssueDetailPanel.tsx
@@ -902,6 +902,10 @@ export function IssueDetailPanel({
render={
}
+ onClick={(event) => {
+ event.preventDefault();
+ void openLink(item.comment.url!, { event }).catch(console.error);
+ }}
>
{formatRelativeTimeLabel(item.comment.createdAt, undefined, messages)}
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx
index d44830dc03c0b..a74b8f716604f 100644
--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx
@@ -11,8 +11,11 @@ const state = vi.hoisted(() => ({
update: vi.fn(),
canUpdate: true,
timestampFormat: "locale" as "locale" | "12-hour" | "24-hour",
+ openLink: vi.fn(async () => {}),
}));
+vi.mock(import("~/browser/useOpenLink"), () => ({ useOpenLink: () => state.openLink }));
+
vi.mock(import("~/state/use-atom-command"), async (original) => ({
...(await original()),
useAtomCommand: (() => state.update) as never,
@@ -51,6 +54,7 @@ function setup() {
state.update.mockResolvedValue({ _tag: "Success", value: undefined });
state.canUpdate = true;
state.timestampFormat = "locale";
+ state.openLink.mockClear();
}
import "~/index.css";
@@ -349,3 +353,44 @@ it("scrolls from the keyboard after a click inside it", async () => {
await userEvent.keyboard("{PageDown}");
await vi.waitFor(() => expect(scroller.scrollTop).toBeGreaterThan(0));
});
+
+it("opens comment timestamps through the link-target setting, not a popup", async () => {
+ setup();
+ const author = { login: "reviewer", name: null, avatarUrl: null };
+ const comment = (id: string, reviewState: string | null) => ({
+ id,
+ kind: "review" as const,
+ body: `Remark ${id}`,
+ author,
+ createdAt: `2026-09-0${id}T00:00:00Z`,
+ url: `${detail.url}#review-${id}`,
+ path: null,
+ reviewState,
+ });
+ // The dismissed review renders as a collapsed card; show it with the resolved filter on.
+ localStorage.setItem(
+ "t3code:pull-request-comment-filter:v1",
+ JSON.stringify({ bots: false, resolved: true }),
+ );
+ try {
+ await using screen = await render({
+ ...detail,
+ comments: [comment("1", null), comment("2", "DISMISSED")],
+ commentCount: 2,
+ });
+ for (const id of ["1", "2"]) {
+ const href = `${detail.url}#review-${id}`;
+ const link = screen.container.querySelector(`a[href="${href}"]`);
+ expect(link, href).not.toBeNull();
+ state.openLink.mockClear();
+ const click = new MouseEvent("click", { bubbles: true, cancelable: true });
+ link!.dispatchEvent(click);
+
+ expect(click.defaultPrevented).toBe(true);
+ expect(state.openLink).toHaveBeenCalledOnce();
+ expect(state.openLink).toHaveBeenCalledWith(href, { event: expect.anything() });
+ }
+ } finally {
+ localStorage.removeItem("t3code:pull-request-comment-filter:v1");
+ }
+});
diff --git a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
index 32a84ba235cf5..5df3b61feece4 100644
--- a/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestSummaryTab.tsx
@@ -119,11 +119,15 @@ function reviewerKey(login: string): string {
function CommentIdentity({
comment,
detail,
+ threadRef,
}: {
comment: PullRequestComment;
detail: PullRequestDetailView;
+ threadRef: ScopedThreadRef | null;
}) {
const gt = useGT();
+ const openLink = useOpenLink(threadRef);
+ const url = comment.url;
const timestampFormat = useClientSettings((settings) => settings.timestampFormat);
const actor = comment.author;
const profileUrl = actor
@@ -134,12 +138,16 @@ function CommentIdentity({
{
+ event.preventDefault();
+ void openLink(url, { event }).catch(console.error);
+ }}
/>
) : (
@@ -148,7 +156,7 @@ function CommentIdentity({
label={
<>
{formatFullTimestamp(comment.createdAt, timestampFormat)}
- {comment.url ? ` · ${gt("Open comment on host")}` : ""}
+ {url ? ` · ${gt("Open comment on host")}` : ""}
>
}
>
@@ -320,7 +328,7 @@ function CollapsedComment({
-
+
{replyCount > 0 ? (
{gt("{count, plural, one {{count} reply} other {{count} replies}}", {
@@ -826,7 +834,7 @@ export const PullRequestSummaryTab = memo(function PullRequestSummaryTab({
>
-
+
{outcome ? (
) : comment.reviewState ? (
From e36800e61babed824d055393d62fedc961e26e3b Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 11:13:34 -0600
Subject: [PATCH 066/238] fix(web): SQLite 1-byte BLOB previews show "[blob: 1
byte]" (#42950)
Co-authored-by: Julius Marminge
---
.../files/binaryPreview.worker.test.ts | 55 ++++++++++++++-----
.../components/files/binaryPreview.worker.ts | 2 +-
2 files changed, 43 insertions(+), 14 deletions(-)
diff --git a/apps/web/src/components/files/binaryPreview.worker.test.ts b/apps/web/src/components/files/binaryPreview.worker.test.ts
index caaef354c51a0..99e089ff0ce79 100644
--- a/apps/web/src/components/files/binaryPreview.worker.test.ts
+++ b/apps/web/src/components/files/binaryPreview.worker.test.ts
@@ -6,6 +6,22 @@ import {
type BinaryWorkerResult,
} from "./binaryPreviewProtocol";
+async function startWorker() {
+ const worker = new EventTarget();
+ let receive = (_result: BinaryWorkerResult) => {};
+ vi.stubGlobal(
+ "self",
+ Object.assign(worker, { postMessage: (result: BinaryWorkerResult) => receive(result) }),
+ );
+ vi.resetModules();
+ await import("./binaryPreview.worker");
+ return (input: BinaryWorkerRequest) =>
+ new Promise((resolve) => {
+ receive = resolve;
+ worker.dispatchEvent(new MessageEvent("message", { data: input }));
+ });
+}
+
it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])(
"only copies previewable TAR payloads with a %i-byte entry",
async (size) => {
@@ -47,20 +63,8 @@ it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])(
offset += 512 + Math.ceil(entry.bytes.length / 512) * 512;
}
- const worker = new EventTarget();
- let receive = (_result: BinaryWorkerResult) => {};
- vi.stubGlobal(
- "self",
- Object.assign(worker, { postMessage: (result: BinaryWorkerResult) => receive(result) }),
- );
try {
- vi.resetModules();
- await import("./binaryPreview.worker");
- const request = (input: BinaryWorkerRequest) =>
- new Promise((resolve) => {
- receive = resolve;
- worker.dispatchEvent(new MessageEvent("message", { data: input }));
- });
+ const request = await startWorker();
using copies = vi.spyOn(Uint8Array.prototype, "slice");
expect(
await request({ type: "open", kind: "archive", name: "mixed.tar", bytes: bytes.buffer }),
@@ -104,3 +108,28 @@ it.each([ARCHIVE_ENTRY_MAX_BYTES, ARCHIVE_ENTRY_MAX_BYTES + 1])(
}
},
);
+
+it("formats singular and plural byte labels for SQLite BLOB cells", async () => {
+ const { default: initSqlJs } = await import("sql.js");
+ const SQL = await initSqlJs();
+ const db = new SQL.Database();
+ db.run(
+ "CREATE TABLE blobs(empty BLOB, one BLOB, four BLOB); INSERT INTO blobs VALUES (X'', X'FF', X'DEADBEEF');",
+ );
+ const bytes = db.export().slice().buffer;
+ db.close();
+
+ try {
+ const request = await startWorker();
+ await request({ type: "open", kind: "sqlite", name: "blobs.sqlite", bytes });
+ expect(await request({ type: "rows", table: "blobs", page: 0 })).toEqual({
+ type: "rows",
+ table: "blobs",
+ page: 0,
+ columns: ["empty", "one", "four"],
+ rows: [["[blob: 0 bytes]", "[blob: 1 byte]", "[blob: 4 bytes]"]],
+ });
+ } finally {
+ vi.unstubAllGlobals();
+ }
+});
diff --git a/apps/web/src/components/files/binaryPreview.worker.ts b/apps/web/src/components/files/binaryPreview.worker.ts
index 4c67d2826976f..d661c4eade9f3 100644
--- a/apps/web/src/components/files/binaryPreview.worker.ts
+++ b/apps/web/src/components/files/binaryPreview.worker.ts
@@ -180,7 +180,7 @@ async function handle(input: BinaryWorkerRequest) {
.slice(0, 50) ?? [];
const fields = columns.map((name) => {
const field = quote(name);
- return `CASE WHEN typeof(${field}) = 'blob' THEN '[blob: ' || length(${field}) || ' bytes]' ELSE substr(CAST(${field} AS TEXT), 1, 1024) END`;
+ return `CASE WHEN typeof(${field}) = 'blob' THEN '[blob: ' || length(${field}) || CASE length(${field}) WHEN 1 THEN ' byte]' ELSE ' bytes]' END ELSE substr(CAST(${field} AS TEXT), 1, 1024) END`;
});
const result = database.exec(
`SELECT ${fields.join(",")} FROM ${quote(input.table)} LIMIT ${SQLITE_PAGE_SIZE} OFFSET ${input.page * SQLITE_PAGE_SIZE}`,
From 3b827b4fb358e820f8871daeafbaaf3f1a2d57a9 Mon Sep 17 00:00:00 2001
From: Simone
Date: Wed, 25 Nov 2026 18:23:49 +0100
Subject: [PATCH 067/238] fix(server): preserve image descriptions in EPUB
attachment text (#42925)
Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com>
Co-authored-by: Julius Marminge
---
apps/server/src/provider/documentTextWorker.ts | 13 +++++++++++++
.../src/provider/userInputAttachments.test.ts | 7 ++++++-
2 files changed, 19 insertions(+), 1 deletion(-)
diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts
index 8d0688b551373..6f5a52030aa57 100644
--- a/apps/server/src/provider/documentTextWorker.ts
+++ b/apps/server/src/provider/documentTextWorker.ts
@@ -165,6 +165,19 @@ function xml(source: string, extension: string): XmlNode {
if (extension === ".epub" && node.name === "ruby" && stack[1]?.name === "html")
separateRubyReadings(node);
if (node.name === "Fallback" && !retainCompatibilityFallback(parent, node)) return;
+ const alt = tag.attributes.alt;
+ if (
+ extension === ".epub" &&
+ node.name === "img" &&
+ stack[1]?.name === "html" &&
+ alt?.trim() &&
+ !/(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*(?:hidden|collapse))\s*(?:!important\s*)?(?:;|$)/i.test(
+ String(tag.attributes.style ?? ""),
+ )
+ ) {
+ node.children.push(alt);
+ node.hasText = true;
+ }
if (HIDDEN.has(node.name) || (!node.hasText && node.name !== "noBreakHyphen")) return;
parent.hasText = true;
if (node.name === "Choice") parent.hasTextChoice = true;
diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts
index 824a9f48422e7..0b3a55bd51fad 100644
--- a/apps/server/src/provider/userInputAttachments.test.ts
+++ b/apps/server/src/provider/userInputAttachments.test.ts
@@ -1497,7 +1497,7 @@ describe("question answer paths", () => {
"OEBPS/a.xhtml":
'Last chapter
Price 10 8 old
山路やまみち を歩く。東京( とうきょう ) に着く。川 を見る。海うみ まで。
',
"OEBPS/b.xhtml":
- 'My Novel First chapter Larkspur
Direct divDirect sectionDirect item emphasis trailing
Account: A Balance: 731 Currency: USD
Heading Total Important value 731 BeforeAfter Neighbor
Port 443 Timeout 30 seconds Draft note
Hidden block
Hidden nested
Findable note
Decorative note
Prefixed note
Before boardingCheck passportsCompare names Confirm gate Board promptly Before landing
' +
+ 'My Novel First chapter Larkspur
Map: open .
Direct divDirect sectionDirect item emphasis trailing
Account: A Balance: 731 Currency: USD
Heading Total Important value 731 BeforeAfter Neighbor
Port 443 Timeout 30 seconds Draft note
Hidden block
Hidden nested
Findable note
Decorative note
Prefixed note
Before boardingCheck passportsCompare names Confirm gate Board promptly Before landing
' +
"Indented\n ",
"OEBPS/c.xhtml": 'Root hidden
',
},
@@ -1505,6 +1505,8 @@ describe("question answer paths", () => {
"## Chapter 1",
"\n# First chapter",
"Larkspur",
+ "Map: North & south piers open.",
+ "Cover art",
"Direct div",
"Direct section",
"Direct item emphasis trailing",
@@ -1529,6 +1531,9 @@ describe("question answer paths", () => {
"Draft note",
"Hidden block",
"Hidden nested",
+ "Hidden image text",
+ "Display none image",
+ "Invisible image",
"Root hidden",
],
},
From 9df77f2125aaa3d442ee15beb43759bef3ab5f28 Mon Sep 17 00:00:00 2001
From: Soroush Baraouf
Date: Wed, 25 Nov 2026 12:25:36 -0500
Subject: [PATCH 068/238] fix(server): expired buffered signals no longer wake
workflows (#42952)
Co-authored-by: Julius Marminge
---
apps/server/src/workflows/WorkflowEngine.ts | 5 +-
.../src/workflows/WorkflowStore.test.ts | 53 ++++++++
apps/server/src/workflows/WorkflowStore.ts | 11 +-
apps/server/src/workflows/Workflows.test.ts | 127 +++++++++++-------
4 files changed, 143 insertions(+), 53 deletions(-)
diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts
index 4e87304c63b81..853b7181a2b25 100644
--- a/apps/server/src/workflows/WorkflowEngine.ts
+++ b/apps/server/src/workflows/WorkflowEngine.ts
@@ -1079,8 +1079,9 @@ const make = Effect.fn("WorkflowEngine.make")(function* (
yield* wake(late, answered);
return "delivered" as const;
}
- // The kept copy went to a wait that opened, or was dropped as already delivered.
- if (outcome === "gone") return "delivered" as const;
+ if (outcome === "claimed") continue;
+ if (yield* store.signalSeen(options.id)) return "delivered" as const;
+ return yield* new WorkflowInputError({ problem: "Buffered signal expired or was removed." });
}
});
const signal: Workflows["Service"]["signal"] = Effect.fn("Workflows.signal")(
diff --git a/apps/server/src/workflows/WorkflowStore.test.ts b/apps/server/src/workflows/WorkflowStore.test.ts
index 1f295eed968f9..abc8d2c6e74c6 100644
--- a/apps/server/src/workflows/WorkflowStore.test.ts
+++ b/apps/server/src/workflows/WorkflowStore.test.ts
@@ -452,6 +452,59 @@ it.effect("one buffered signal goes to one wait, and a claimed wait keeps what w
),
);
+it.effect.each([999, 1000])("buffered mail with a 1s TTL claimed after %i ms", (elapsed) =>
+ withStore(
+ Effect.gen(function* () {
+ const store = yield* WorkflowStore.WorkflowStore;
+ const address = { workflow: "gate", channel: "ready" };
+ yield* store.waitOpened({
+ runId: "r1",
+ name: "go",
+ workflow: address.workflow,
+ key: address.channel,
+ token: "token",
+ schemaJson: "{}",
+ requestJson: null,
+ watchJson: null,
+ deadline: null,
+ });
+ yield* store.mailPut({
+ signalId: "first",
+ address,
+ valueJson: "1",
+ expiresAt: "1970-01-01T00:00:01.000Z",
+ sender,
+ });
+ yield* store.mailPut({
+ signalId: "second",
+ address,
+ valueJson: "2",
+ expiresAt: "1970-01-01T00:00:02.000Z",
+ sender,
+ });
+ const selected = yield* store.mailNext([address]);
+ assert.equal(selected?.signalId, "first");
+ yield* TestClock.adjust(elapsed);
+ const live = elapsed < 1000;
+ assert.deepStrictEqual(
+ {
+ next: (yield* store.mailNext([address]))?.signalId,
+ claim: yield* store.mailDeliver(selected!.signalId, "r1", "go", {
+ expired: false,
+ value: 1,
+ }),
+ waitOpen: (yield* store.waitAt({ runId: "r1", wait: "go" })) !== undefined,
+ receipt: yield* store.signalSeen("first"),
+ rowPresent: (yield* store.mailSender("first")) !== undefined,
+ },
+ live
+ ? { next: "first", claim: "delivered", waitOpen: false, receipt: true, rowPresent: false }
+ : { next: "second", claim: "gone", waitOpen: true, receipt: false, rowPresent: true },
+ );
+ }),
+ ),
+);
+
it.effect("tells the milestone hub of each run and question transition once", () =>
withStore(
Effect.gen(function* () {
diff --git a/apps/server/src/workflows/WorkflowStore.ts b/apps/server/src/workflows/WorkflowStore.ts
index 5e41a16ca1670..9ec9201feff79 100644
--- a/apps/server/src/workflows/WorkflowStore.ts
+++ b/apps/server/src/workflows/WorkflowStore.ts
@@ -268,7 +268,7 @@ export class WorkflowStore extends Context.Service<
readonly waitsClaimed: (runId: string) => Effect.Effect>;
/**
* Hands one buffered signal to one wait, or to none: the claim and the removal happen
- * together. `gone` when another wait took the signal, `claimed` when the wait was already woken.
+ * together. `gone` when the signal is expired or absent, `claimed` when the wait was already woken.
*/
readonly mailDeliver: (
signalId: string,
@@ -972,10 +972,11 @@ export const make = Effect.gen(function* () {
`.pipe(Effect.orDie);
}),
mailDeliver: Effect.fn("WorkflowStore.mailDeliver")(function* (signalId, runId, name, woke) {
- const at = yield* now;
+ let at = "";
const outcome = yield* sql
.withTransaction(
Effect.gen(function* () {
+ at = yield* now;
// A kept copy of an id that already woke a wait straight is spent: it is dropped, so
// it wakes no second wait and is not offered again.
const seen = yield* sql`SELECT 1 FROM workflow_signals WHERE signal_id = ${signalId}`;
@@ -990,7 +991,8 @@ export const make = Effect.gen(function* () {
`;
if (claimed.length === 0) return "claimed" as const;
const taken = yield* sql<{ expires_at: string }>`
- DELETE FROM workflow_mail WHERE signal_id = ${signalId} RETURNING expires_at
+ DELETE FROM workflow_mail
+ WHERE signal_id = ${signalId} AND expires_at > ${at} RETURNING expires_at
`;
// Failing undoes the claim: the wait stays open for a signal that is still there.
const copy = taken[0];
@@ -1288,6 +1290,7 @@ export const make = Effect.gen(function* () {
.pipe(Effect.orDie);
}),
mailNext: Effect.fn("WorkflowStore.mailNext")(function* (addresses, passed = new Set()) {
+ const at = yield* now;
for (const address of addresses) {
const rows = yield* sql<{
signal_id: string;
@@ -1295,7 +1298,7 @@ export const make = Effect.gen(function* () {
sender_json: string | null;
}>`
SELECT signal_id, value_json, sender_json FROM workflow_mail
- WHERE address = ${mailAddress(address)} ORDER BY rowid
+ WHERE address = ${mailAddress(address)} AND expires_at > ${at} ORDER BY rowid
`.pipe(Effect.orDie);
const mail = rows.find((row) => !passed.has(row.signal_id));
if (mail !== undefined) {
diff --git a/apps/server/src/workflows/Workflows.test.ts b/apps/server/src/workflows/Workflows.test.ts
index abb8bedb7aaf9..40411db749969 100644
--- a/apps/server/src/workflows/Workflows.test.ts
+++ b/apps/server/src/workflows/Workflows.test.ts
@@ -1244,54 +1244,87 @@ it.effect("a signal sent before its wait opens is delivered when it does", () =>
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
-it.effect("a signal buffered as its wait opens is still delivered to that wait", () =>
- Effect.gen(function* () {
- const looked = yield* Deferred.make();
- const opened = yield* Deferred.make();
- const checked = yield* Deferred.make();
- // Holds the signal between finding no wait and buffering, while the wait opens and finds no mail.
- const store = Layer.effect(
- WorkflowStore.WorkflowStore,
- Effect.gen(function* () {
- const real = yield* WorkflowStore.make;
- let first = true;
- return WorkflowStore.WorkflowStore.of({
- ...real,
- waitAt: (address) =>
- Effect.tap(real.waitAt(address), () => {
- if (!("channel" in address) || address.channel !== "c9" || !first) return Effect.void;
- first = false;
- return Effect.andThen(Deferred.succeed(looked, undefined), Deferred.await(opened));
- }),
- mailNext: (addresses, passed) =>
- Effect.tap(real.mailNext(addresses, passed), (mail) =>
- mail === undefined && !first ? Deferred.succeed(checked, undefined) : Effect.void,
+it.effect.each(["stays live", "expires", "is delivered concurrently"] as const)(
+ "a signal buffered as its wait opens %s",
+ (how) =>
+ Effect.gen(function* () {
+ const looked = yield* Deferred.make();
+ const opened = yield* Deferred.make();
+ const checked = yield* Deferred.make();
+ const claiming = yield* Deferred.make();
+ const claim = yield* Deferred.make();
+ // Holds the signal between finding no wait and buffering, while the wait opens and finds no mail.
+ const store = Layer.effect(
+ WorkflowStore.WorkflowStore,
+ Effect.gen(function* () {
+ const real = yield* WorkflowStore.make;
+ let first = true;
+ return WorkflowStore.WorkflowStore.of({
+ ...real,
+ waitAt: (address) =>
+ Effect.tap(real.waitAt(address), () => {
+ if (!("channel" in address) || address.channel !== "c9" || !first)
+ return Effect.void;
+ first = false;
+ return Effect.andThen(Deferred.succeed(looked, undefined), Deferred.await(opened));
+ }),
+ mailNext: (addresses, passed) =>
+ Effect.tap(real.mailNext(addresses, passed), (mail) =>
+ mail === undefined && !first ? Deferred.succeed(checked, undefined) : Effect.void,
+ ),
+ mailDeliver: (id, runId, name, woke) =>
+ Effect.andThen(
+ Effect.andThen(Deferred.succeed(claiming, undefined), Deferred.await(claim)),
+ real.mailDeliver(id, runId, name, woke),
+ ),
+ });
+ }),
+ );
+ const { boot, clock, database } = yield* harness(store);
+ yield* boot(
+ Effect.gen(function* () {
+ const workflows = yield* Workflows.Workflows;
+ const address = { workflow: "review", channel: "c9" };
+ const send = workflows.signal(address, { merge: true }, { id: "s9", ttl: "1 millis" });
+ const sent = yield* Effect.forkChild(
+ send.pipe(
+ Effect.match({ onFailure: (error) => error._tag, onSuccess: (outcome) => outcome }),
),
- });
- }),
- );
- const { boot } = yield* harness(store);
- yield* boot(
- Effect.gen(function* () {
- const workflows = yield* Workflows.Workflows;
- const sent = yield* Effect.forkChild(
- workflows.signal({ workflow: "review", channel: "c9" }, { merge: true }, { id: "s9" }),
- );
- yield* Deferred.await(looked);
- const { runId } = yield* workflows.start(
- "review",
- { change: "c9" },
- { idempotencyKey: "c9" },
- );
- // Released once the open wait has looked for mail and found none.
- yield* Deferred.await(checked);
- yield* Deferred.succeed(opened, undefined);
- assert.equal(yield* Fiber.join(sent), "delivered");
- const done = yield* workflows.waitFor(runId, status("completed"));
- assert.equal(done.result, "2 checks, merge: true");
- }),
- );
- }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+ );
+ yield* Deferred.await(looked);
+ const { runId } = yield* workflows.start(
+ "review",
+ { change: "c9" },
+ { idempotencyKey: "c9" },
+ );
+ // Released once the open wait has looked for mail and found none.
+ yield* Deferred.await(checked);
+ yield* clock.close;
+ yield* TestClock.adjust(0);
+ yield* Deferred.succeed(opened, undefined);
+ yield* Deferred.await(claiming);
+ if (how === "expires") yield* TestClock.adjust("1 millis");
+ if (how === "is delivered concurrently") assert.equal(yield* send, "delivered");
+ yield* Deferred.succeed(claim, undefined);
+ assert.equal(
+ yield* Fiber.join(sent),
+ how === "expires" ? "WorkflowInputError" : "delivered",
+ );
+ if (how === "expires") {
+ const sql = yield* Effect.provide(SqlClient.SqlClient, database);
+ assert.lengthOf(yield* sql`SELECT 1 FROM workflow_mail WHERE signal_id = 's9'`, 1);
+ assert.lengthOf(yield* sql`SELECT 1 FROM workflow_signals WHERE signal_id = 's9'`, 0);
+ assert.equal(
+ yield* workflows.signal(address, { merge: false }, { id: "replacement" }),
+ "delivered",
+ );
+ }
+ yield* clock.open;
+ const done = yield* workflows.waitFor(runId, status("completed"));
+ assert.equal(done.result, `2 checks, merge: ${how !== "expires"}`);
+ }).pipe(Effect.ensuring(clock.open)),
+ );
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
it.effect("a wait another signal claimed first wakes with that signal's value", () =>
From b1360538c1c8a01329c2bc816a8a45a7fc325517 Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 11:27:55 -0600
Subject: [PATCH 069/238] fix(server): DOCX merged table cells no longer shift
later columns in attachment text (#42955)
Co-authored-by: Julius Marminge
---
.../server/src/provider/documentTextWorker.ts | 11 +++++++++--
.../src/provider/userInputAttachments.test.ts | 19 +++++++++++++++++++
2 files changed, 28 insertions(+), 2 deletions(-)
diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts
index 6f5a52030aa57..45b8acba01527 100644
--- a/apps/server/src/provider/documentTextWorker.ts
+++ b/apps/server/src/provider/documentTextWorker.ts
@@ -366,11 +366,18 @@ function* table(node: XmlNode): Generator {
for (let index = 0; index < repeat; index++) {
if (++rowCount > 10_000) throw new Truncation("Row limit");
let column = 0;
+ let gap = 0;
for (const cell of cells) {
const count = repeatCount(cell.attrs["number-columns-repeated"]);
+ // Word emits no cell for columns covered by w:gridSpan; pad before the next cell.
+ const tcPr = cell.name === "tc" ? children(cell).find((c) => c.name === "tcPr") : undefined;
+ const val = tcPr && children(tcPr).find((c) => c.name === "gridSpan")?.attrs.val;
+ const span = val ? Math.max(1, Number.parseInt(val, 10) || 1) : 1;
for (let i = 0; i < count; i++) {
- if (column >= 512) throw new Truncation("Column limit");
- if (column++) yield "\t";
+ column += span;
+ if (column > 512) throw new Truncation("Column limit");
+ if (gap) yield "\t".repeat(gap);
+ gap = span;
// LibreOffice hides the contents a merge covers; the cell still holds its column.
if (covered(cell)) continue;
yield CELL_START;
diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts
index 0b3a55bd51fad..49dcbb9929214 100644
--- a/apps/server/src/provider/userInputAttachments.test.ts
+++ b/apps/server/src/provider/userInputAttachments.test.ts
@@ -961,6 +961,25 @@ describe("question answer paths", () => {
"Before Inner After\tNeighbor\t\u2011\n\u2011\nDemoted\nIntro. # Box title",
],
},
+ {
+ ext: "docx",
+ bounded: true,
+ parts: {
+ "word/document.xml":
+ '' +
+ "A B C " +
+ 'Tail End ' +
+ 'Merged Total ' +
+ 'Zero Next ' +
+ 'Wide ' +
+ " ",
+ },
+ expected: [
+ "A\tB\tC\nTail\tEnd\nMerged\t\tTotal\nZero\tNext",
+ "[Extracted text truncated at document extraction limits.]",
+ ],
+ absent: ["Wide"],
+ },
{
ext: "docx",
bounded: true,
From 7d8c03fd999467843c70178fe655e05eeab2aeb5 Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 18:36:33 +0100
Subject: [PATCH 070/238] fix(terminal): keep other input out of large
bracketed pastes (#42948)
Co-authored-by: Julius Marminge
---
.../terminal/ThreadTerminalRouteScreen.tsx | 36 ++---
.../features/terminal/terminalPaste.test.ts | 47 +++++-
.../src/features/terminal/terminalPaste.ts | 64 ++++++--
apps/server/src/terminal/Manager.test.ts | 121 ++++++++++++++
apps/server/src/terminal/Manager.ts | 138 ++++++++++++++--
.../src/components/ThreadTerminalDrawer.tsx | 40 +++--
.../terminal/terminalInputWriter.test.ts | 22 ++-
.../terminal/terminalInputWriter.ts | 38 +++--
packages/contracts/src/terminal.ts | 19 ++-
...e-keeps-input-from-other-client-out.e2e.ts | 153 ++++++++++++++++++
10 files changed, 597 insertions(+), 81 deletions(-)
create mode 100644 scripts/scenarios/terminal-paste-keeps-input-from-other-client-out.e2e.ts
diff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
index 2136bb020ae5e..6068c6a60db33 100644
--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
@@ -3,7 +3,7 @@ import { m } from "../../i18n/messages";
import {
AuthTerminalReadScope,
AuthTerminalOperateScope,
- chunkTerminalWrite,
+ type TerminalWriteInput,
DEFAULT_TERMINAL_ID,
EnvironmentId,
ThreadId,
@@ -649,7 +649,10 @@ function ThreadTerminal(props: {
messages,
);
- const writeInput = async (data: string): Promise => {
+ const writeInput = async (
+ data: string,
+ plainWrite?: TerminalWriteInput["plainWrite"],
+ ): Promise => {
if (
!isRunning ||
!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
@@ -657,21 +660,16 @@ function ThreadTerminal(props: {
return false;
}
- // Android's IME delivers a system paste as one input, which can exceed one write.
- const isSameShell = pasteSession.liveness();
- for (const chunk of chunkTerminalWrite(data)) {
- if (!isSameShell()) return false;
- const result = await writeTerminal({
- environmentId: selectedThread.environmentId,
- input: {
- threadId: selectedThread.id,
- terminalId,
- data: chunk,
- },
- });
- if (result._tag !== "Success") return false;
- }
- return true;
+ const result = await writeTerminal({
+ environmentId: selectedThread.environmentId,
+ input: {
+ threadId: selectedThread.id,
+ terminalId,
+ data,
+ ...(plainWrite ? { plainWrite } : {}),
+ },
+ });
+ return result._tag === "Success";
};
const pasteText = async (readText: () => Promise) => {
@@ -686,7 +684,7 @@ function ThreadTerminal(props: {
const writeModifiedInput = (data: string) => {
if (pendingModifier === null) {
- void writeInput(data);
+ void pasteSession.write(data, writeInput);
return;
}
@@ -700,7 +698,7 @@ function ThreadTerminal(props: {
void pasteText(Clipboard.getStringAsync);
return;
}
- void writeInput(resolved.data);
+ void pasteSession.write(resolved.data, writeInput);
};
const handleInput = (data: string) => {
diff --git a/apps/mobile/src/features/terminal/terminalPaste.test.ts b/apps/mobile/src/features/terminal/terminalPaste.test.ts
index 2545085137916..c34c9c09e087a 100644
--- a/apps/mobile/src/features/terminal/terminalPaste.test.ts
+++ b/apps/mobile/src/features/terminal/terminalPaste.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
-import { TERMINAL_WRITE_MAX_LENGTH } from "@t3tools/contracts";
+import { TERMINAL_WRITE_MAX_LENGTH, type TerminalWriteInput } from "@t3tools/contracts";
import { createTerminalPasteSession } from "./terminalPaste";
function deferred() {
@@ -50,9 +50,11 @@ describe("terminal paste session", () => {
const firstWrite = deferred();
const firstWriteStarted = deferred();
const writes: string[] = [];
+ const phases: Array = [];
let activeWrites = 0;
let maximumActiveWrites = 0;
- const write = async (data: string) => {
+ const write = async (data: string, phase?: TerminalWriteInput["plainWrite"]) => {
+ phases.push(phase);
writes.push(data);
activeWrites += 1;
maximumActiveWrites = Math.max(maximumActiveWrites, activeWrites);
@@ -84,8 +86,45 @@ describe("terminal paste session", () => {
firstWrite.resolve(true);
await Promise.all([olderPaste, newerPaste]);
- expect(writes.map((chunk) => chunk.length)).toEqual([TERMINAL_WRITE_MAX_LENGTH, 5]);
- expect(writes[1]).toBe("newer");
+ expect(writes.map((chunk) => chunk.length)).toEqual([TERMINAL_WRITE_MAX_LENGTH, 0, 5]);
+ expect(writes[2]).toBe("newer");
+ expect(phases).toEqual(["start", "abort", undefined]);
expect(maximumActiveWrites).toBe(1);
});
+ it("keeps a keystroke behind a queued split write", async () => {
+ const session = createTerminalPasteSession();
+ session.reset(true);
+ const firstChunk = deferred();
+ const started = deferred();
+ const writes: string[] = [];
+ const send = async (data: string) => {
+ writes.push(data);
+ if (writes.length === 1) {
+ started.resolve();
+ return firstChunk.promise;
+ }
+ return true;
+ };
+ const a = "a".repeat(TERMINAL_WRITE_MAX_LENGTH);
+ const b = "b".repeat(TERMINAL_WRITE_MAX_LENGTH);
+ const first = session.write(a + "1", send);
+ await started.promise;
+ const second = session.write(b + "2", send);
+ const key = session.write("k", send);
+ expect(writes).toEqual([a]);
+
+ firstChunk.resolve(true);
+ await Promise.all([first, second, key]);
+ expect(writes).toEqual([a, "1", b, "2", "k"]);
+ });
+
+ it("sends a keystroke typed before the first attach snapshot", async () => {
+ const session = createTerminalPasteSession();
+ const writes: string[] = [];
+ await session.write("k", async (data) => {
+ writes.push(data);
+ return true;
+ });
+ expect(writes).toEqual(["k"]);
+ });
});
diff --git a/apps/mobile/src/features/terminal/terminalPaste.ts b/apps/mobile/src/features/terminal/terminalPaste.ts
index b09e365587d57..28c176f65cf20 100644
--- a/apps/mobile/src/features/terminal/terminalPaste.ts
+++ b/apps/mobile/src/features/terminal/terminalPaste.ts
@@ -1,10 +1,16 @@
-import { chunkTerminalWrite } from "@t3tools/contracts";
+import {
+ chunkTerminalWrite,
+ terminalWritePhase,
+ type TerminalWriteInput,
+} from "@t3tools/contracts";
import { encodeTerminalPaste } from "./terminalInput";
+type WriteChunk = (data: string, phase?: TerminalWriteInput["plainWrite"]) => Promise;
+
interface TerminalPasteInput {
readonly readText: () => Promise;
- readonly write: (data: string) => Promise;
+ readonly write: WriteChunk;
readonly onReadError: (cause: unknown) => void;
}
@@ -12,13 +18,45 @@ export interface TerminalPasteSession {
readonly reset: (active: boolean) => void;
/** True until the terminal's liveness changes (stop, start or restart) after this call. */
readonly liveness: () => () => boolean;
+ readonly write: (data: string, send: WriteChunk) => Promise;
readonly paste: (input: TerminalPasteInput) => Promise;
}
export function createTerminalPasteSession(): TerminalPasteSession {
let liveTarget: object | null = null;
let latestRequest = 0;
- let writeTail: Promise = Promise.resolve();
+ let writeTail: Promise | null = null;
+
+ const writeChunks = (
+ data: string,
+ send: WriteChunk,
+ isCurrent: () => boolean,
+ queueSingle: boolean,
+ ) => {
+ const chunks = chunkTerminalWrite(data);
+ const run = async () => {
+ let started = false;
+ try {
+ for (const [index, chunk] of chunks.entries()) {
+ if (!isCurrent()) return;
+ const phase = terminalWritePhase(index, chunks.length);
+ started ||= phase === "start";
+ if (!(await send(chunk, phase))) return;
+ }
+ started = false;
+ } finally {
+ if (started) await send("", "abort");
+ }
+ };
+ if (writeTail === null && !queueSingle && chunks.length <= 1) return run();
+ const pending = (writeTail ?? Promise.resolve()).then(run, run);
+ writeTail = pending;
+ const clear = () => {
+ if (writeTail === pending) writeTail = null;
+ };
+ void pending.then(clear, clear);
+ return pending;
+ };
return {
reset(active) {
@@ -30,6 +68,12 @@ export function createTerminalPasteSession(): TerminalPasteSession {
return () => liveTarget === target;
},
+ async write(data, send) {
+ // Input can arrive before the first attach snapshot sets liveness; the caller gates on running.
+ const target = liveTarget;
+ await writeChunks(data, send, () => liveTarget === target, false);
+ },
+
async paste({ readText, write, onReadError }) {
const target = liveTarget;
if (target === null) {
@@ -50,19 +94,7 @@ export function createTerminalPasteSession(): TerminalPasteSession {
return;
}
- const writePaste = async () => {
- for (const chunk of chunkTerminalWrite(encodeTerminalPaste(text))) {
- if (!isCurrent() || !(await write(chunk))) {
- return;
- }
- }
- };
- const queuedWrite = writeTail.then(writePaste, writePaste);
- writeTail = queuedWrite.then(
- () => undefined,
- () => undefined,
- );
- await queuedWrite;
+ await writeChunks(encodeTerminalPaste(text), write, isCurrent, true);
},
};
}
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts
index 9773e2dd19350..649eb097a654f 100644
--- a/apps/server/src/terminal/Manager.test.ts
+++ b/apps/server/src/terminal/Manager.test.ts
@@ -5,6 +5,9 @@ import { assert, it } from "@effect/vitest";
import {
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
DEFAULT_TERMINAL_ID,
+ TERMINAL_BRACKETED_PASTE_START,
+ TERMINAL_BRACKETED_PASTE_END,
+ type TerminalWriteInput,
ProjectId,
ThreadId,
TerminalCwdNotFoundError,
@@ -877,6 +880,124 @@ it.layer(
}),
);
+ it.effect.each(["complete", "abort", "timeout", "close"] as const)(
+ "releases pending terminal input after paste %s",
+ (interruption) =>
+ Effect.gen(function* () {
+ const { manager, ptyAdapter } = yield* createManager();
+ yield* manager.open(openInput());
+ const target = { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID };
+ const process = ptyAdapter.processes[0]!;
+ process.onKill = () => process.emitExit({ exitCode: 0, signal: 0 });
+ const endPrefix = TERMINAL_BRACKETED_PASTE_END.slice(0, -1);
+ const endSuffix = TERMINAL_BRACKETED_PASTE_END.slice(-1);
+ const begin = TERMINAL_BRACKETED_PASTE_START + "partial";
+ const writePaste = (data: string, bracketedPaste: TerminalWriteInput["bracketedPaste"]) =>
+ manager.write({ ...target, data, ...(bracketedPaste && { bracketedPaste }) }, "paste");
+ yield* writePaste(begin, "start");
+ const pending = yield* manager
+ .write({ ...target, data: "next" }, "typing")
+ .pipe(Effect.forkScoped({ startImmediately: true }));
+ expect(process.writes).toEqual([begin]);
+
+ if (interruption === "complete") {
+ const badEnd = yield* writePaste("incomplete end", "end").pipe(Effect.flip);
+ expect(badEnd._tag).toBe("TerminalWriteError");
+ expect(process.writes).toEqual([begin]);
+ yield* writePaste(endPrefix, "continue");
+ yield* writePaste(endSuffix, "end");
+ } else if (interruption === "abort") {
+ yield* writePaste(TERMINAL_BRACKETED_PASTE_END, "abort");
+ } else if (interruption === "timeout") {
+ yield* TestClock.adjust("15 seconds");
+ } else {
+ yield* manager.close(target);
+ yield* manager.open(openInput());
+ const reopened = ptyAdapter.processes[1]!;
+ reopened.onKill = () => reopened.emitExit({ exitCode: 0, signal: 0 });
+ expect(reopened.writes).toEqual([]);
+ }
+ if (interruption === "close") {
+ const error = yield* Fiber.join(pending).pipe(Effect.flip);
+ expect(error._tag).toBe("TerminalNotRunningError");
+ expect(process.writes).toEqual([begin]);
+ expect(ptyAdapter.processes[1]!.writes).toEqual([]);
+ } else {
+ yield* Fiber.join(pending);
+ expect(process.writes).toEqual(
+ interruption === "complete"
+ ? [begin, endPrefix, endSuffix, "next"]
+ : [begin, TERMINAL_BRACKETED_PASTE_END, "next"],
+ );
+ }
+ const lateEnd = yield* writePaste(TERMINAL_BRACKETED_PASTE_END, "end").pipe(Effect.exit);
+ expect(Exit.isFailure(lateEnd)).toBe(true);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
+ it.effect.each(["end", "abort", "timeout"] as const)(
+ "releases input after a plain split write ends by %s without adding a bracket",
+ (finish) =>
+ Effect.gen(function* () {
+ const { manager, ptyAdapter } = yield* createManager();
+ yield* manager.open(openInput());
+ const target = { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID };
+ const process = ptyAdapter.processes[0]!;
+ process.onKill = () => process.emitExit({ exitCode: 0, signal: 0 });
+ yield* manager.write({ ...target, data: "first", plainWrite: "start" }, "paste");
+ const pending = yield* manager
+ .write({ ...target, data: "typing" }, "other")
+ .pipe(Effect.forkScoped({ startImmediately: true }));
+ expect(process.writes).toEqual(["first"]);
+ if (finish === "timeout") {
+ yield* TestClock.adjust("15 seconds");
+ } else {
+ yield* manager.write(
+ { ...target, data: finish === "end" ? "last" : "", plainWrite: finish },
+ "paste",
+ );
+ }
+ yield* Fiber.join(pending);
+ expect(process.writes).toEqual(
+ finish === "end" ? ["first", "last", "typing"] : ["first", "typing"],
+ );
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
+ it.effect("does not reserve the terminal when writing a paste start fails", () =>
+ Effect.gen(function* () {
+ const { manager, ptyAdapter } = yield* createManager();
+ yield* manager.open(openInput());
+ const target = { threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID };
+ const process = ptyAdapter.processes[0]!;
+ process.onKill = () => process.emitExit({ exitCode: 0, signal: 0 });
+ process.writeFailure = new Error("write failed");
+ const error = yield* manager
+ .write(
+ {
+ ...target,
+ data: TERMINAL_BRACKETED_PASTE_START + "paste",
+ bracketedPaste: "start",
+ },
+ "paste",
+ )
+ .pipe(Effect.flip);
+ expect(error._tag).toBe("TerminalWriteError");
+
+ process.writeFailure = undefined;
+ yield* manager.write(
+ {
+ ...target,
+ data: TERMINAL_BRACKETED_PASTE_END,
+ bracketedPaste: "abort",
+ },
+ "paste",
+ );
+ yield* manager.write({ ...target, data: "next" }, "typing");
+ expect(process.writes).toEqual(["next"]);
+ }),
+ );
+
it.effect("resumed attaches after close never respawn until the terminal is reopened", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts
index d71f4e2266c9a..76b39f86372b8 100644
--- a/apps/server/src/terminal/Manager.ts
+++ b/apps/server/src/terminal/Manager.ts
@@ -7,6 +7,8 @@ import {
DEFAULT_MAX_TERMINAL_BUFFER_BYTES,
retainTerminalSnapshotHistory,
TERMINAL_SEQUENCE_GROUND,
+ TERMINAL_BRACKETED_PASTE_END,
+ TERMINAL_BRACKETED_PASTE_START,
terminalSequenceEnd,
terminalSequenceStateAfter,
TerminalCwdError,
@@ -49,6 +51,7 @@ import { SpawnExecutableResolution, mergePathEntries } from "@t3tools/shared/she
import { acpRegistryManagedBinaryDirectories } from "@t3tools/provider-acp-registry/server";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
+import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Context from "effect/Context";
@@ -2030,6 +2033,28 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const workerScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void));
+ const clock = yield* Clock.Clock;
+ const pasteIdleMillis = 15_000;
+ const pasteEndOverlap = TERMINAL_BRACKETED_PASTE_END.length - 1;
+ const activePastes = new WeakMap<
+ PtyAdapter.PtyProcess,
+ {
+ readonly owner: string;
+ readonly finished: Deferred.Deferred;
+ lastWrite: number;
+ readonly bracketed: boolean;
+ trailingData: string;
+ }
+ >();
+
+ const releasePaste = (process: PtyAdapter.PtyProcess | null) => {
+ if (process === null) return;
+ const paste = activePastes.get(process);
+ if (!paste) return;
+ activePastes.delete(process);
+ Deferred.doneUnsafe(paste.finished, Effect.void);
+ };
+
const publishEvent =
/* Provider events include streaming deltas; avoid a span for each update. */
Effect.fnUntraced(function* (event: TerminalEvent) {
@@ -2716,6 +2741,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const process = session.process;
cleanupProcessHandles(session);
session.process = null;
+ releasePaste(process);
session.pid = null;
session.hasRunningSubprocess = false;
session.childCommandLabel = null;
@@ -2788,6 +2814,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
yield* modifyManagerState((state) => {
cleanupProcessHandles(session);
session.process = null;
+ releasePaste(process);
session.pid = null;
session.hasRunningSubprocess = false;
session.childCommandLabel = null;
@@ -3880,6 +3907,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
const write: TerminalManager["Service"]["write"] = Effect.fn("terminal.write")(
function* (input, viewerId) {
const terminalId = input.terminalId;
+ const phase = input.bracketedPaste ?? input.plainWrite;
+ const bracketed = input.bracketedPaste !== undefined;
const found = yield* getSession(input.threadId, terminalId);
if (Option.isNone(found)) {
if (input.expectedPid !== undefined) return yield* new TerminalProcessChangedError();
@@ -3903,17 +3932,104 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
if (input.reply && !acceptsQueryReply(toSessionKey(input.threadId, terminalId), viewerId)) {
return;
}
- session.inputCount += 1;
- yield* Effect.try({
- try: () => process.write(PtyAdapter.ptyInput(input.data, input.binary)),
- catch: (cause) =>
- new TerminalWriteError({
- threadId: input.threadId,
- terminalId,
- terminalPid: process.pid,
- cause,
- }),
- });
+ const writeError = (cause: unknown) =>
+ new TerminalWriteError({
+ threadId: input.threadId,
+ terminalId,
+ terminalPid: process.pid,
+ cause,
+ });
+ const writeData = (data: string, binary?: boolean) =>
+ Effect.try({
+ try: () => {
+ session.inputCount += 1;
+ process.write(PtyAdapter.ptyInput(data, binary));
+ },
+ catch: writeError,
+ });
+ if (
+ phase &&
+ (viewerId === undefined || input.binary || input.reply || (bracketed && input.plainWrite))
+ ) {
+ return yield* writeError("Invalid split terminal write");
+ }
+ if (phase === "continue" || phase === "end" || phase === "abort") {
+ const paste = activePastes.get(process);
+ if (!paste || paste.owner !== viewerId || paste.bracketed !== bracketed) {
+ if (phase === "abort") return;
+ return yield* writeError("Split terminal write is no longer active");
+ }
+ if (
+ bracketed &&
+ phase === "end" &&
+ !(paste.trailingData + input.data).endsWith(TERMINAL_BRACKETED_PASTE_END)
+ ) {
+ return yield* writeError("Missing end of bracketed paste");
+ }
+ paste.lastWrite = clock.currentTimeMillisUnsafe();
+ if (phase === "continue") {
+ yield* writeData(input.data);
+ paste.trailingData = (paste.trailingData + input.data).slice(-pasteEndOverlap);
+ return;
+ }
+ if (phase !== "abort" || bracketed) {
+ yield* writeData(phase === "abort" ? TERMINAL_BRACKETED_PASTE_END : input.data);
+ }
+ return releasePaste(process);
+ }
+
+ // A write that waits for a paste belongs to the same PTY even if its session restarts.
+ let active = activePastes.get(process);
+ while (active) {
+ if (phase === "start" && active.owner === viewerId) {
+ return yield* writeError("Split terminal write already active");
+ }
+ yield* Deferred.await(active.finished);
+ if (session.process !== process || session.status !== "running") {
+ return yield* new TerminalNotRunningError({ threadId: input.threadId, terminalId });
+ }
+ active = activePastes.get(process);
+ }
+ if (phase !== "start" || viewerId === undefined) {
+ return yield* writeData(input.data, input.binary);
+ }
+ if (bracketed && !input.data.startsWith(TERMINAL_BRACKETED_PASTE_START)) {
+ return yield* writeError("Missing start of bracketed paste");
+ }
+
+ const paste = {
+ owner: viewerId,
+ bracketed,
+ finished: Deferred.makeUnsafe(),
+ lastWrite: clock.currentTimeMillisUnsafe(),
+ trailingData: input.data.slice(-pasteEndOverlap),
+ };
+ // A disconnected sender cannot close its bracket. Close it on the original PTY
+ // before releasing queued input, even when the rest of the paste never arrives.
+ yield* Effect.uninterruptible(
+ Effect.gen(function* () {
+ yield* writeData(input.data);
+ activePastes.set(process, paste);
+ yield* Effect.gen(function* () {
+ while (activePastes.get(process) === paste && session.process === process) {
+ const remaining = paste.lastWrite + pasteIdleMillis - clock.currentTimeMillisUnsafe();
+ if (remaining <= 0) {
+ if (bracketed) {
+ yield* writeData(TERMINAL_BRACKETED_PASTE_END).pipe(
+ Effect.ignoreCause({ log: true }),
+ );
+ }
+ break;
+ }
+ const finished = yield* Deferred.await(paste.finished).pipe(
+ Effect.timeoutOption(Duration.millis(remaining)),
+ );
+ if (Option.isSome(finished)) return;
+ }
+ if (activePastes.get(process) === paste) releasePaste(process);
+ }).pipe(Effect.interruptible, Effect.forkIn(workerScope));
+ }),
+ );
},
);
diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx
index 9bc43233585d7..94b8c160788d2 100644
--- a/apps/web/src/components/ThreadTerminalDrawer.tsx
+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx
@@ -30,6 +30,7 @@ import {
AuthOrchestrationOperateScope,
AuthTerminalOperateScope,
TerminalProcessChangedError,
+ type TerminalWriteInput,
type ContextMenuItem,
type ProviderInstanceId,
type ResolvedKeybindingsConfig,
@@ -966,7 +967,11 @@ function TerminalSessionViewport({
};
const canWriteInput = () => readEnvironmentScope(environmentId, AuthTerminalOperateScope);
- const writeInputChunk = (data: string, kind?: "binary" | "reply", expectedPid?: number) =>
+ const writeInputChunk = (
+ data: string,
+ kind?: "binary" | "reply",
+ options?: Pick,
+ ) =>
retainedTerminalWrite.current({
environmentId,
input: {
@@ -974,7 +979,7 @@ function TerminalSessionViewport({
terminalId,
data,
...(kind === undefined ? {} : { [kind]: true }),
- ...(expectedPid === undefined ? {} : { expectedPid }),
+ ...options,
},
});
const sendTerminalInput = (
@@ -999,7 +1004,7 @@ function TerminalSessionViewport({
};
return writeInput(
data,
- async (chunk, split) => {
+ async (chunk, framing) => {
if (terminalRef.current !== terminal) return "not-dispatched";
const currentSession = appAtomRegistry.get(terminalSessionAtom);
if (
@@ -1009,9 +1014,12 @@ function TerminalSessionViewport({
return "not-dispatched";
}
const expectedPid =
- split && session.supportsConditionalWrites ? session.pid : undefined;
+ framing && session.supportsConditionalWrites ? session.pid : undefined;
if (expectedPid === null) return "not-dispatched";
- const result = await writeInputChunk(chunk, kind, expectedPid);
+ const result = await writeInputChunk(chunk, kind, {
+ ...(kind ? {} : framing),
+ ...(expectedPid === undefined ? {} : { expectedPid }),
+ });
if (result._tag === "Success") return true;
const error = squashAtomCommandFailure(result);
if (isTerminalProcessChanged(error)) return "not-dispatched";
@@ -1021,8 +1029,17 @@ function TerminalSessionViewport({
return false;
},
// The attachment's PID stays with the paste even after the viewport detaches.
- async () => {
- if (session.pid === null) return true;
+ async (bracketed) => {
+ if (kind || session.pid === null) return true;
+ const expectedPid = session.supportsConditionalWrites ? session.pid : undefined;
+ const pidGuard = expectedPid === undefined ? {} : { expectedPid };
+ if (!bracketed) {
+ // Only releases the server's hold, which also ends when that process exits.
+ const current = appAtomRegistry.get(terminalSessionAtom);
+ if (current.lifecycleVersion !== lifecycleVersion) return true;
+ await writeInputChunk("", undefined, { plainWrite: "abort", ...pidGuard });
+ return true;
+ }
if (!canWriteInput()) return false;
if (!session.supportsConditionalWrites) {
const attached =
@@ -1047,11 +1064,10 @@ function TerminalSessionViewport({
}
if (current.status !== "running" || current.pid !== session.pid) return false;
}
- const result = await writeInputChunk(
- "\x1b[201~",
- undefined,
- session.supportsConditionalWrites ? session.pid : undefined,
- );
+ const result = await writeInputChunk("\x1b[201~", undefined, {
+ bracketedPaste: "abort",
+ ...pidGuard,
+ });
if (result._tag === "Success") return true;
const error = squashAtomCommandFailure(result);
if (isTerminalProcessChanged(error)) return true;
diff --git a/apps/web/src/components/terminal/terminalInputWriter.test.ts b/apps/web/src/components/terminal/terminalInputWriter.test.ts
index 2670add86a2f3..9d79de03e57b5 100644
--- a/apps/web/src/components/terminal/terminalInputWriter.test.ts
+++ b/apps/web/src/components/terminal/terminalInputWriter.test.ts
@@ -9,7 +9,12 @@ const fitsWrite = (data: string) => isWriteInput({ threadId: "t", terminalId: "d
/** A `send` whose calls stay pending until the test settles them. */
function heldSend() {
- const sent: Array<{ readonly chunk: string; readonly settle: (ok: boolean) => void }> = [];
+ type Framing = Pick;
+ const sent: Array<{
+ readonly chunk: string;
+ readonly framing: Framing | undefined;
+ readonly settle: (ok: boolean) => void;
+ }> = [];
const waiters: Array<{ readonly count: number; readonly resolve: () => void }> = [];
return {
sent,
@@ -20,9 +25,9 @@ function heldSend() {
if (sent.length >= count) resolve();
else waiters.push({ count, resolve });
}),
- send: (chunk: string) =>
+ send: (chunk: string, framing?: Framing) =>
new Promise((settle) => {
- sent.push({ chunk, settle });
+ sent.push({ chunk, framing, settle });
for (const waiter of waiters) if (sent.length >= waiter.count) waiter.resolve();
}),
};
@@ -162,9 +167,16 @@ describe("createTerminalInputWriter", () => {
const pasted = write("q".repeat(140_000), send);
void write("next", send);
sent[0]!.settle(false);
- await pasted;
await sends(2);
+ sent[1]!.settle(true);
+ await pasted;
+ await sends(3);
- expect(chunks()).toEqual(["q".repeat(65_536), "next"]);
+ expect(chunks()).toEqual(["q".repeat(65_536), "", "next"]);
+ expect(sent.map(({ framing }) => framing)).toEqual([
+ { plainWrite: "start" },
+ { plainWrite: "abort" },
+ undefined,
+ ]);
});
});
diff --git a/apps/web/src/components/terminal/terminalInputWriter.ts b/apps/web/src/components/terminal/terminalInputWriter.ts
index ab7e7033ee7e2..c44253da4aeaa 100644
--- a/apps/web/src/components/terminal/terminalInputWriter.ts
+++ b/apps/web/src/components/terminal/terminalInputWriter.ts
@@ -1,7 +1,14 @@
-import { chunkTerminalWrite } from "@t3tools/contracts";
+import {
+ chunkTerminalWrite,
+ terminalWritePhase,
+ type TerminalWriteInput,
+} from "@t3tools/contracts";
/** Sends one chunk of terminal input; resolves false when it failed and the rest should drop. */
-type SendTerminalChunk = (chunk: string, split: boolean) => Promise;
+type SendTerminalChunk = (
+ chunk: string,
+ framing?: Pick,
+) => Promise;
/**
* Orders one terminal's input into writes that fit `terminal.write`. A split write goes one chunk
@@ -23,7 +30,7 @@ export function createTerminalInputWriter(onIdle = () => {}) {
data: string,
chunks: ReadonlyArray,
send: SendTerminalChunk,
- recover: () => Promise,
+ recover: (bracketed: boolean) => Promise,
interrupted: () => void,
) => {
if (closeInterruptedPaste !== null && !(await closePaste())) {
@@ -34,20 +41,28 @@ export function createTerminalInputWriter(onIdle = () => {}) {
const bracketed = split && data.startsWith("\x1b[200~") && data.endsWith("\x1b[201~");
let opened = false;
try {
- for (const chunk of chunks) {
- const result = await send(chunk, split);
+ for (const [index, chunk] of chunks.entries()) {
+ const phase = terminalWritePhase(index, chunks.length);
+ const result = await send(
+ chunk,
+ phase ? (bracketed ? { bracketedPaste: phase } : { plainWrite: phase }) : undefined,
+ );
if (result !== true) {
- if (result !== "not-dispatched") opened = bracketed;
+ if (result !== "not-dispatched") opened = split;
if (split) interrupted();
return;
}
- opened = bracketed;
+ opened = split;
}
opened = false;
} finally {
if (opened) {
- closeInterruptedPaste = recover;
- await closePaste();
+ if (bracketed) {
+ closeInterruptedPaste = () => recover(true);
+ await closePaste();
+ } else {
+ await recover(false);
+ }
}
}
};
@@ -55,7 +70,10 @@ export function createTerminalInputWriter(onIdle = () => {}) {
return (
data: string,
send: SendTerminalChunk,
- recover: () => Promise = async () => (await send("\x1b[201~", true)) === true,
+ recover: (bracketed: boolean) => Promise = async (bracketed) =>
+ (await (bracketed
+ ? send("\x1b[201~", { bracketedPaste: "abort" })
+ : send("", { plainWrite: "abort" }))) === true,
interrupted = () => {},
): Promise => {
const idle = () => {
diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts
index 93d5164e9b98b..fb2f9a6a8fe93 100644
--- a/packages/contracts/src/terminal.ts
+++ b/packages/contracts/src/terminal.ts
@@ -273,11 +273,15 @@ export type TerminalAttachInput = typeof TerminalAttachInput.Type;
/** Longest `data` one `terminal.write` carries, in UTF-16 code units. */
export const TERMINAL_WRITE_MAX_LENGTH = 65_536;
+export const TERMINAL_BRACKETED_PASTE_START = "\x1b[200~";
+export const TERMINAL_BRACKETED_PASTE_END = "\x1b[201~";
+
export const TerminalWriteInput = Schema.Struct({
...TerminalSessionInput.fields,
- data: Schema.String.check(Schema.isNonEmpty()).check(
- Schema.isMaxLength(TERMINAL_WRITE_MAX_LENGTH),
- ),
+ data: Schema.String.check(Schema.isMaxLength(TERMINAL_WRITE_MAX_LENGTH)),
+ // Older servers ignore the phase and still receive the bracket markers in data.
+ bracketedPaste: Schema.optionalKey(Schema.Literals(["start", "continue", "end", "abort"])),
+ plainWrite: Schema.optionalKey(Schema.Literals(["start", "continue", "end", "abort"])),
// `data` holds one byte per UTF-16 code unit; older servers write it as UTF-8 text.
binary: Schema.optionalKey(Schema.Boolean),
// A renderer's answer to a terminal query (DA, DSR, DECRQM). Every attached renderer
@@ -285,7 +289,9 @@ export const TerminalWriteInput = Schema.Struct({
reply: Schema.optionalKey(Schema.Boolean),
// Reject the write if the process that owns the paste has gone.
expectedPid: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThan(0))),
-});
+}).check(
+ Schema.makeFilter(({ data, plainWrite }) => (plainWrite === "abort") === (data.length === 0)),
+);
export type TerminalWriteInput = Schema.Codec.Encoded;
/** Splits input into writes that fit `TerminalWriteInput`, never between a surrogate pair. */
@@ -304,6 +310,11 @@ export function chunkTerminalWrite(data: string): ReadonlyArray {
return chunks;
}
+export function terminalWritePhase(index: number, count: number) {
+ if (count <= 1) return undefined;
+ return index === 0 ? "start" : index === count - 1 ? "end" : "continue";
+}
+
export const TerminalResizeInput = Schema.Struct({
...TerminalSessionInput.fields,
cols: TerminalColsSchema,
diff --git a/scripts/scenarios/terminal-paste-keeps-input-from-other-client-out.e2e.ts b/scripts/scenarios/terminal-paste-keeps-input-from-other-client-out.e2e.ts
new file mode 100644
index 0000000000000..8a3e26008fe7f
--- /dev/null
+++ b/scripts/scenarios/terminal-paste-keeps-input-from-other-client-out.e2e.ts
@@ -0,0 +1,153 @@
+///
+import { DEFAULT_TERMINAL_ID, ThreadId } from "@t3tools/contracts";
+import { expect } from "e2e";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as FileSystem from "effect/FileSystem";
+
+import { T3_HOME } from "../e2e.config.ts";
+import { rpcClient, runPromise, test, WEB } from "./t3.ts";
+
+const TAIL = "end-of-first-paste";
+const OTHER_INPUT = "second-client-input";
+const PASTE = "p".repeat(65_536 - 6) + TAIL;
+
+const PROBE = String.raw`import { writeFileSync } from "node:fs";
+const file = (name) => new URL(name, import.meta.url);
+let received = "";
+process.stdin.setRawMode(true);
+process.stdin.on("data", (chunk) => {
+ received += chunk.toString();
+ if (!received.includes("\x1b[201~")) return;
+ const expected = "\x1b[200~" + "p".repeat(65530) + "${TAIL}\x1b[201~";
+ const interleaved = "\x1b[200~" + "p".repeat(65530) + "${OTHER_INPUT}${TAIL}\x1b[201~";
+ const result = received.startsWith(expected)
+ ? "Paste arrived intact"
+ : received.startsWith(interleaved)
+ ? "Other input landed inside the paste"
+ : "Paste arrived with unexpected bytes";
+ writeFileSync(file("result"), result);
+ process.stdout.write("\x1b[?2004l\r\n" + result + "\r\n");
+ process.exit(0);
+});
+process.stdout.write("\x1b[?2004h");
+writeFileSync(file("ready"), "ready");
+`;
+
+interface PasteGate {
+ readonly waiting: () => boolean;
+ readonly release: () => void;
+}
+
+test(
+ "A second connection cannot insert input inside a web terminal paste",
+ WEB,
+ async ({ t3, app, browser, screen }) => {
+ const cwd = await t3.project("demo", { "paste-probe.mjs": PROBE });
+ const thread = await t3.thread({
+ project: cwd,
+ title: "Shared terminal paste",
+ messages: ["hello"],
+ });
+ const threadId = ThreadId.make(thread.threadId);
+ const terminalId = DEFAULT_TERMINAL_ID;
+ const origin = app.baseUrl ?? "";
+ const read = (name: string) =>
+ runPromise(
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ return yield* fs.readFileString(`${cwd}/${name}`);
+ }).pipe(Effect.orElseSucceed(() => "")),
+ );
+ await runPromise(
+ Effect.gen(function* () {
+ const client = yield* rpcClient(T3_HOME, origin);
+ yield* client["terminal.open"]({ threadId, terminalId, cwd });
+ }).pipe(Effect.scoped),
+ );
+
+ // Hold the next outgoing chunk to reproduce a slow connection after the first was acknowledged.
+ await browser.addInitScript((tail) => {
+ let release: (() => void) | undefined;
+ const nativeSend = WebSocket.prototype.send;
+ WebSocket.prototype.send = function (data: Parameters[0]) {
+ if (typeof data === "string" && data.includes('"tag":"terminal.write"')) {
+ const request = JSON.parse(data) as { payload?: { data?: string } };
+ if (request.payload?.data?.endsWith(tail + "\x1b[201~")) {
+ release = () => nativeSend.call(this, data);
+ return;
+ }
+ }
+ nativeSend.call(this, data);
+ };
+ (window as unknown as { pasteGate: PasteGate }).pasteGate = {
+ waiting: () => release !== undefined,
+ release: () => release?.(),
+ };
+ }, TAIL);
+ await browser.emulateMedia({ colorScheme: "dark", reducedMotion: "reduce" });
+ await t3.open(thread);
+ await screen.getByRole("button", "Toggle terminal drawer").tap();
+ const terminal = screen.getByLabel("Terminal input");
+ // The terminal surface can appear before its session can accept keystrokes.
+ await expect
+ .poll(
+ async () => {
+ await terminal.focus();
+ await browser.keyboard.type(`echo ready > '${cwd}/shell-ready'`);
+ await browser.keyboard.press("Enter");
+ return read("shell-ready");
+ },
+ { timeout: 30_000 },
+ )
+ .toBe("ready\n");
+
+ await terminal.focus();
+ await browser.keyboard.type(`'${process.execPath}' '${cwd}/paste-probe.mjs'`);
+ await browser.keyboard.press("Enter");
+ await expect.poll(() => read("ready"), { timeout: 15_000 }).toBe("ready");
+
+ await browser.evaluate((text) => {
+ const input = document.querySelector('[aria-label="Terminal input"]');
+ if (!input) throw new Error("no terminal input");
+ const clipboardData = new DataTransfer();
+ clipboardData.setData("text/plain", text);
+ input.dispatchEvent(
+ new ClipboardEvent("paste", { clipboardData, bubbles: true, cancelable: true }),
+ );
+ return null;
+ }, PASTE);
+ await expect
+ .poll(async () => {
+ if (await read("result")) return true;
+ return browser.evaluate(() =>
+ (window as unknown as { pasteGate: PasteGate }).pasteGate.waiting(),
+ );
+ })
+ .toBe(true);
+
+ await runPromise(
+ Effect.gen(function* () {
+ const client = yield* rpcClient(T3_HOME, origin);
+ const write = yield* client["terminal.write"]({
+ threadId,
+ terminalId,
+ data: OTHER_INPUT,
+ }).pipe(Effect.forkScoped);
+ // A server that defers the second client's write may acknowledge it after the paste.
+ yield* Fiber.join(write).pipe(Effect.timeoutOption("3 seconds"));
+ yield* Effect.promise(() =>
+ browser.evaluate(() => {
+ (window as unknown as { pasteGate: PasteGate }).pasteGate.release();
+ return null;
+ }),
+ );
+ yield* Fiber.join(write);
+ }).pipe(Effect.scoped),
+ );
+
+ await expect.poll(async () => Boolean(await read("result"))).toBe(true);
+ await app.screenshot("paste-after-input-from-second-connection");
+ expect(await read("result")).toBe("Paste arrived intact");
+ },
+);
From 2313dfadad3398fd2a3ec9e267518af762ce0374 Mon Sep 17 00:00:00 2001
From: Thanh Hoai Anh Nguyen
Date: Wed, 25 Nov 2026 19:46:02 +0200
Subject: [PATCH 071/238] fix(server): resend a Cursor request a restart cut
off before its first checkpoint (#42938)
Co-authored-by: Julius Marminge
---
.../ProviderTurnStartService.ts | 121 ++++++++++++++-
.../ProviderSwitch.integration.test.ts | 140 +++++++++++++++++-
.../src/server/ProviderAdapter.ts | 8 +
.../src/server/adapter.test.ts | 6 +
.../provider-cursor/src/server/adapter.ts | 28 ++++
5 files changed, 294 insertions(+), 9 deletions(-)
diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
index 8051a4129095a..33d549f548938 100644
--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts
@@ -151,6 +151,46 @@ export function abandonedProviderTurns(
});
}
+const CUT_TURN_SETTLED = "cut-turn-settled";
+
+/**
+ * The previous run's cancelled turn when no adapter said whether it kept the request. A Stop
+ * settles that as the turn ends; a restart cancels the turn with no adapter left to tell.
+ */
+function unsettledCancelledProviderTurn(
+ projection: Pick,
+ run: Pick,
+ providerThread: Pick,
+) {
+ const previous = projection.runs.reduce(
+ (latest, candidate) =>
+ candidate.ordinal < run.ordinal &&
+ candidate.providerThreadId === providerThread.id &&
+ candidate.startedAt !== null &&
+ (latest === undefined || candidate.ordinal > latest.ordinal)
+ ? candidate
+ : latest,
+ undefined,
+ );
+ if (previous?.status !== "cancelled" || previous.activeAttemptId === null) return undefined;
+ const turn = projection.providerTurns.findLast(
+ (candidate) =>
+ candidate.runAttemptId === previous.activeAttemptId &&
+ candidate.providerThreadId === providerThread.id,
+ );
+ const nativeTurnId = turn?.nativeTurnRef?.nativeId;
+ if (
+ turn === undefined ||
+ nativeTurnId == null ||
+ turn.status !== "cancelled" ||
+ turn.promptDropped === true ||
+ (turn.nativeThreadRef !== undefined &&
+ turn.nativeThreadRef.nativeId !== providerThread.nativeThreadRef?.nativeId)
+ )
+ return undefined;
+ return { run: previous, turn, nativeTurnId };
+}
+
export const isProviderTurnStartError = Schema.is(ProviderTurnStartError);
const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapterProtocolError);
const isProviderAdapterTurnStartError = Schema.is(ProviderAdapter.ProviderAdapterTurnStartError);
@@ -1063,6 +1103,70 @@ export const layer: Layer.Layer<
}
const session = sessionResult.success;
if (!(yield* isCurrentAttemptInStatus("starting"))) return;
+ const cutTurn = unsettledCancelledProviderTurn(projection, run, providerThread);
+ if (
+ cutTurn !== undefined &&
+ session.nativeTurnKept !== undefined &&
+ !(yield* (
+ session
+ .nativeTurnKept({ providerThread, nativeTurnId: cutTurn.nativeTurnId })
+ // As when the turn ends: an unknown answer resends the request rather than losing it.
+ .pipe(Effect.orElseSucceed(() => false))
+ ))
+ ) {
+ // Settle it as a Stop would: mark the request dropped and take back its inline context, so
+ // this turn resends both. Starting again reads the settled state.
+ const occurredAt = yield* DateTime.now;
+ const allocateEventId = () =>
+ idAllocator.allocate.event({ threadId: projection.thread.id });
+ // Its attempt starts before it delivers anything, so later inline deliveries are its own,
+ // including handoffs carried from an earlier run that they still target.
+ const cutStartedAt =
+ projection.attempts.find((candidate) => candidate.id === cutTurn.run.activeAttemptId)
+ ?.startedAt ?? cutTurn.run.startedAt;
+ const settled = yield* eventSink.writeIfRunCurrent({
+ threadId: projection.thread.id,
+ runId: run.id,
+ activeAttemptId: attempt.id,
+ expectedStatus: "starting",
+ events: [
+ {
+ id: yield* allocateEventId(),
+ type: "provider-turn.updated" as const,
+ threadId: projection.thread.id,
+ runId: cutTurn.run.id,
+ nodeId: cutTurn.turn.nodeId,
+ providerInstanceId: cutTurn.run.providerInstanceId,
+ occurredAt,
+ payload: { ...cutTurn.turn, promptDropped: true as const },
+ },
+ ...(yield* Effect.forEach(
+ projection.contextHandoffs.filter(
+ (handoff) =>
+ handoff.delivery?.status === "inline" &&
+ handoff.delivery.nativeThreadId === providerThread.nativeThreadRef?.nativeId &&
+ (handoff.targetRunId === cutTurn.run.id ||
+ (cutStartedAt !== null &&
+ DateTime.isGreaterThanOrEqualTo(handoff.updatedAt, cutStartedAt))),
+ ),
+ ({ delivery: _delivery, ...handoff }) =>
+ Effect.map(allocateEventId(), (id) => ({
+ id,
+ type: "context-handoff.updated" as const,
+ threadId: projection.thread.id,
+ runId: cutTurn.run.id,
+ providerInstanceId: cutTurn.run.providerInstanceId,
+ occurredAt,
+ payload: { ...handoff, updatedAt: occurredAt },
+ })),
+ )),
+ ],
+ });
+ if (!settled.committed) return;
+ // The restarted start captures the same baseline; never let the two write at once.
+ yield* baseline;
+ return CUT_TURN_SETTLED;
+ }
const loadFromProvider = Effect.fn("ProviderTurnStartService.loadFromProvider")(function* (
load: Effect.Effect,
) {
@@ -2389,18 +2493,23 @@ export const layer: Layer.Layer<
(yield* projects
.getById(thread.projectId, { includeDeleted: true })
.pipe(Effect.map((project) => Option.getOrUndefined(project)?.workspaceRoot)));
+ // Settling a turn a restart cut off changes what a start reads, so it starts once more.
+ const startSettled = start(input, captureStartingRun).pipe(
+ Effect.filterOrElse(
+ (started) => started !== CUT_TURN_SETTLED,
+ () => start(input, captureStartingRun),
+ ),
+ Effect.map((started) => (started === CUT_TURN_SETTLED ? undefined : started)),
+ );
const providerTurn = yield* cwd === undefined
- ? start(input, captureStartingRun)
+ ? startSettled
: withTurnStartReservation(
fileSystem,
path,
path.resolve(cwd),
thread.worktreePath === null
- ? start(input, captureStartingRun)
- : withWorkspaceLease(
- path.resolve(thread.worktreePath),
- start(input, captureStartingRun),
- ),
+ ? startSettled
+ : withWorkspaceLease(path.resolve(thread.worktreePath), startSettled),
);
if (providerTurn !== undefined && "worktreeSetup" in providerTurn) {
yield* providerTurn.worktreeSetup;
diff --git a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
index e9fc7b8d63ff6..8ee13bf8f9878 100644
--- a/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
+++ b/apps/server/src/orchestration-v2/testkit/ProviderSwitch.integration.test.ts
@@ -120,6 +120,7 @@ function makeTestAdapter(input: {
readonly rejectedNativeThreads?: Ref.Ref>;
readonly failedRunOrdinals?: ReadonlySet;
readonly promptDroppedRunOrdinals?: ReadonlySet;
+ readonly nativeTurnKept?: (nativeTurnId: string) => boolean;
readonly brokenRunOrdinals?: ReadonlySet;
readonly interruptedRunOrdinals?: ReadonlySet;
readonly cancelledRunOrdinals?: ReadonlySet;
@@ -201,6 +202,12 @@ function makeTestAdapter(input: {
...(input.canReuseContextUsage === undefined
? {}
: { canReuseContextUsage: input.canReuseContextUsage }),
+ ...(input.nativeTurnKept === undefined
+ ? {}
+ : {
+ nativeTurnKept: ({ nativeTurnId }) =>
+ Effect.succeed(input.nativeTurnKept!(nativeTurnId)),
+ }),
...(input.backgroundWork === undefined
? {}
: {
@@ -6544,14 +6551,17 @@ describe("orchestration v2 provider switching", () => {
it.effect.each([
"same-provider-retry",
"cancelled-dropped",
+ "cancelled-by-restart",
"switch-away-and-return",
"persisted-failure",
] as const)("handles an inline context handoff after a failed returning turn (%s)", (variant) =>
Effect.gen(function* () {
const cwd = yield* checkpointWorkspace(`dropped-handoff-${variant}`);
const capturedTurns = yield* Ref.make>([]);
- const dropped = variant !== "persisted-failure";
- const cancelled = variant === "cancelled-dropped";
+ // A restart cancels the turn with no adapter left to report the drop.
+ const cutByRestart = variant === "cancelled-by-restart";
+ const dropped = variant !== "persisted-failure" && !cutByRestart;
+ const cancelled = variant === "cancelled-dropped" || cutByRestart;
const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
makeTestAdapter({
instanceId: CODEX_MODEL_SELECTION.instanceId,
@@ -6569,6 +6579,9 @@ describe("orchestration v2 provider switching", () => {
? { cancelledRunOrdinals: new Set([3]) }
: { failedRunOrdinals: new Set([3]) }),
...(dropped ? { promptDroppedRunOrdinals: new Set([3]) } : {}),
+ ...(cutByRestart
+ ? { nativeTurnKept: (nativeTurnId: string) => !nativeTurnId.endsWith(":3") }
+ : {}),
}),
makeTestAdapter({
instanceId: CLAUDE_MODEL_SELECTION.instanceId,
@@ -6650,7 +6663,7 @@ describe("orchestration v2 provider switching", () => {
assert.equal(run3Handoff?.delivery?.status, "inline");
}
- if (variant === "same-provider-retry" || variant === "cancelled-dropped") {
+ if (variant === "same-provider-retry" || variant === "cancelled-dropped" || cutByRestart) {
// Run 4: stay on Codex; must re-deliver run 2's handoff.
const afterRun4 = yield* send("Resume", CODEX_MODEL_SELECTION);
const turns = yield* Ref.get(capturedTurns);
@@ -6662,6 +6675,10 @@ describe("orchestration v2 provider switching", () => {
(handoff) => handoff.id === run3Handoff!.id,
);
assert.equal(updatedHandoff?.delivery?.status, "inline");
+ const run3Turn = afterRun4.providerTurns.find(
+ (turn) => turn.runAttemptId === run3.activeAttemptId,
+ );
+ assert.equal(run3Turn?.promptDropped, true);
} else if (variant === "switch-away-and-return") {
// Run 4: bounce back to Claude, then Run 5: return to Codex.
yield* send("Continue on Claude", CLAUDE_MODEL_SELECTION);
@@ -6702,4 +6719,121 @@ describe("orchestration v2 provider switching", () => {
);
}),
);
+
+ it.effect("restores a handoff that a turn cut by a restart carried from an earlier run", () =>
+ Effect.gen(function* () {
+ const cwd = yield* checkpointWorkspace("carried-handoff-cut-by-restart");
+ const capturedTurns = yield* Ref.make>([]);
+ const refuseStarts = yield* Ref.make(0);
+ const layerRegistry = ProviderAdapterRegistry.layerFromAdapters([
+ makeTestAdapter({
+ instanceId: CODEX_MODEL_SELECTION.instanceId,
+ driver: CODEX_DRIVER,
+ capabilities: CodexProviderCapabilitiesV2,
+ modelSelection: CODEX_MODEL_SELECTION,
+ responseByRunOrdinal: { 1: "Morning Codex summary.", 4: "", 5: "Recovered." },
+ capturedTurns,
+ refuseStarts,
+ // A restart cancels run 4 before the provider keeps its request.
+ cancelledRunOrdinals: new Set([4]),
+ nativeTurnKept: (nativeTurnId) => !nativeTurnId.endsWith(":4"),
+ }),
+ makeTestAdapter({
+ instanceId: CLAUDE_MODEL_SELECTION.instanceId,
+ driver: CLAUDE_DRIVER,
+ capabilities: ClaudeProviderCapabilitiesV2,
+ modelSelection: CLAUDE_MODEL_SELECTION,
+ responseByRunOrdinal: { 2: "Afternoon Claude shipped b63 live draft." },
+ capturedTurns,
+ }),
+ ]);
+
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const testThreadId = ThreadId.make("thread:carried-handoff-cut-by-restart");
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("command:carried-handoff-cut:create"),
+ threadId: testThreadId,
+ projectId,
+ title: "Carried handoff cut by restart",
+ modelSelection: CODEX_MODEL_SELECTION,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: cwd,
+ });
+ let step = 0;
+ const send = (text: string, modelSelection: ModelSelection) =>
+ Effect.gen(function* () {
+ step += 1;
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`command:carried-handoff-cut:msg-${step}`),
+ threadId: testThreadId,
+ messageId: MessageId.make(`message:carried-handoff-cut:${step}`),
+ text,
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: "start_immediately" },
+ });
+ yield* worker.drain();
+ yield* waitForIdle(testThreadId);
+ yield* worker.drain();
+ return yield* orchestrator.getThreadProjection(testThreadId);
+ });
+
+ yield* send("Morning task", CODEX_MODEL_SELECTION);
+ yield* send("Build live draft b63", CLAUDE_MODEL_SELECTION);
+ // Codex refuses run 3 before its prompt, so run 4 carries the handoff made for run 3.
+ yield* Ref.set(refuseStarts, 1);
+ const afterRun3 = yield* send("Resume after failure", CODEX_MODEL_SELECTION);
+ const run3 = afterRun3.runs.find((run) => run.ordinal === 3)!;
+ assert.equal(run3.status, "failed");
+ const afterRun4 = yield* send("Carry the draft forward", CODEX_MODEL_SELECTION);
+ const run4 = afterRun4.runs.find((run) => run.ordinal === 4)!;
+ assert.equal(run4.status, "cancelled");
+ const carried = afterRun4.contextHandoffs.find(
+ (handoff) => handoff.targetRunId === run3.id,
+ );
+ assert.equal(carried?.delivery?.status, "inline");
+ assert.include(
+ (yield* Ref.get(capturedTurns)).at(-1)!.text,
+ "Afternoon Claude shipped b63 live draft.",
+ );
+
+ const afterRun5 = yield* send("Resume", CODEX_MODEL_SELECTION);
+ const run5Turn = (yield* Ref.get(capturedTurns)).at(-1)!;
+ assert.include(run5Turn.text, "Afternoon Claude shipped b63 live draft.");
+ assert.include(run5Turn.text, "Carry the draft forward");
+ const run4Turn = afterRun5.providerTurns.find(
+ (turn) => turn.runAttemptId === run4.activeAttemptId,
+ );
+ assert.equal(run4Turn?.promptDropped, true);
+ }).pipe(
+ Effect.provide(
+ ProviderReplayHarness.layerWithRegistry(
+ {
+ name: "carried-handoff-cut-by-restart",
+ runtimePolicyOverride: {
+ cwd,
+ approvalPolicy: "never",
+ sandboxPolicy: {
+ type: "readOnly",
+ access: { type: "fullAccess" },
+ networkAccess: false,
+ },
+ },
+ },
+ layerRegistry,
+ ),
+ ),
+ );
+ }),
+ );
});
diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts
index 5cefa6da97fab..a3e15ef9d4e35 100644
--- a/packages/provider-core/src/server/ProviderAdapter.ts
+++ b/packages/provider-core/src/server/ProviderAdapter.ts
@@ -789,6 +789,14 @@ export interface ProviderAdapterV2SessionRuntime {
cwd?: string | null,
) => number | undefined;
readonly canReuseContextUsage?: (previous: ModelSelection, next: ModelSelection) => boolean;
+ /**
+ * False when the native session no longer holds a cancelled turn's request. Set only by
+ * providers that can drop one, so a turn a restart cut off is settled like a Stop.
+ */
+ readonly nativeTurnKept?: (input: {
+ readonly providerThread: OrchestrationV2ProviderThread;
+ readonly nativeTurnId: string;
+ }) => Effect.Effect;
/** Excludes turn-scoped options from native thread load matching. */
readonly normalizeThreadLoadModelSelection?: (selection: ModelSelection) => ModelSelection;
readonly ensureThread: (
diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts
index 1425b87b53486..3b21fcf951ec4 100644
--- a/packages/provider-cursor/src/server/adapter.test.ts
+++ b/packages/provider-cursor/src/server/adapter.test.ts
@@ -939,6 +939,12 @@ describe("CursorAdapterV2", () => {
assert.equal(checkpointed.terminal?.status, "failed");
assert.isUndefined(checkpointed.terminal?.promptDropped);
assert.isUndefined(checkpointed.turn?.promptDropped);
+
+ // After a restart no turn ends to report it, so the next turn start asks instead.
+ const kept = (nativeTurnId: string) =>
+ runtime.nativeTurnKept!({ providerThread, nativeTurnId });
+ assert.isFalse(yield* kept("native-cursor-run-1"));
+ assert.isTrue(yield* kept("native-cursor-run-2"));
}).pipe(
Effect.scoped,
Effect.provide(
diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts
index 70e7a389f0663..63f8e22aa8b89 100644
--- a/packages/provider-cursor/src/server/adapter.ts
+++ b/packages/provider-cursor/src/server/adapter.ts
@@ -3372,6 +3372,34 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* (
),
),
),
+ nativeTurnKept: Effect.fn("CursorAdapterV2.nativeTurnKept")(
+ function* (keptInput: {
+ readonly providerThread: OrchestrationV2ProviderThread;
+ readonly nativeTurnId: string;
+ }) {
+ const agent = yield* openAgent({
+ operation: "resume",
+ agentId: nativeThreadId(keptInput.providerThread),
+ storeCwd: keptInput.providerThread.nativeMetadata?.cursorStoreCwd,
+ threadId: keptInput.providerThread.appThreadId ?? input.threadId,
+ modelSelection: input.modelSelection,
+ runtimePolicy: input.runtimePolicy,
+ });
+ if (agent.session.runCheckpointed === undefined) return true;
+ return yield* agent.session.runCheckpointed(keptInput.nativeTurnId);
+ },
+ (effect, keptInput) =>
+ effect.pipe(
+ Effect.mapError(
+ (cause) =>
+ new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
+ driver: CursorAgentSdk.CURSOR_PROVIDER,
+ providerThreadId: keptInput.providerThread.id,
+ cause,
+ }),
+ ),
+ ),
+ ),
startTurn,
resumeTurn: (input) => startTurn(ProviderAdapter.resumeTurnInput(input)),
compactThread: (turnInput) =>
From f84c7168394eb8541ca928f09177bcd7b5495d1d Mon Sep 17 00:00:00 2001
From: "Paul Dupuy, Jr." <70114489+pauldupuyjr@users.noreply.github.com>
Date: Wed, 25 Nov 2026 11:47:55 -0600
Subject: [PATCH 072/238] test(scripts): WSL archive fixture works with Git
Bash tar on Windows (#42962)
Co-authored-by: Julius Marminge
---
scripts/build-desktop-artifact.test.ts | 8 +++++---
1 file changed, 5 insertions(+), 3 deletions(-)
diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts
index 43e89846bded0..e5a0cc3c6e4f4 100644
--- a/scripts/build-desktop-artifact.test.ts
+++ b/scripts/build-desktop-artifact.test.ts
@@ -104,16 +104,18 @@ const makeLinuxCliArchiveFixture = Effect.fn("test.makeLinuxCliArchiveFixture")(
yield* fs.makeDirectory(path.dirname(memberPath), { recursive: true });
yield* fs.writeFileString(memberPath, member);
}
- const archivePath = path.join(input.root, `${input.stem}.tar.gz`);
+ const archiveName = `${input.stem}.tar.gz`;
const tar = yield* spawner.spawn(
- ChildProcess.make("tar", ["-czf", archivePath, "-C", contentRoot, "."], {
+ // GNU tar reads a drive letter in an absolute archive path as a remote host.
+ ChildProcess.make("tar", ["-czf", archiveName, "-C", contentRoot, "."], {
+ cwd: input.root,
stdin: "ignore",
stdout: "ignore",
stderr: "pipe",
}),
);
assert.equal(Number(yield* tar.exitCode), 0);
- return archivePath;
+ return path.join(input.root, archiveName);
});
function mockProcess(exitCode: number, stdout = "") {
From 487a29b91659cf7d391fa61f3528e9c991e59cdc Mon Sep 17 00:00:00 2001
From: Kyros Abas
Date: Thu, 26 Nov 2026 01:59:00 +0800
Subject: [PATCH 073/238] fix(server): EPUB attachments keep their table
captions for agents (#42964)
Co-authored-by: Julius Marminge
---
apps/server/src/provider/documentTextWorker.ts | 8 +++++++-
apps/server/src/provider/userInputAttachments.test.ts | 4 +++-
2 files changed, 10 insertions(+), 2 deletions(-)
diff --git a/apps/server/src/provider/documentTextWorker.ts b/apps/server/src/provider/documentTextWorker.ts
index 45b8acba01527..75958b9719709 100644
--- a/apps/server/src/provider/documentTextWorker.ts
+++ b/apps/server/src/provider/documentTextWorker.ts
@@ -355,8 +355,14 @@ function hasCellText(cell: XmlNode): boolean {
);
}
function* table(node: XmlNode): Generator {
+ for (const caption of children(node)) {
+ if (caption.name !== "caption") continue;
+ yield LINE_START;
+ yield* paragraphs(caption);
+ yield LINE_START;
+ }
let rowCount = 0;
- for (const row of all(node, ["tr", "table-row"])) {
+ for (const row of all(node, ["tr", "table-row"], ["caption"])) {
// Word nests a cell inside w:sdt when a content control wraps the whole cell.
const cells = [...all(row, ["tc", "table-cell", "covered-table-cell", "td", "th"])];
// ODS writers pad sheets with repeated empty rows and trailing cells.
diff --git a/apps/server/src/provider/userInputAttachments.test.ts b/apps/server/src/provider/userInputAttachments.test.ts
index 49dcbb9929214..de8dd59a91400 100644
--- a/apps/server/src/provider/userInputAttachments.test.ts
+++ b/apps/server/src/provider/userInputAttachments.test.ts
@@ -1514,7 +1514,7 @@ describe("question answer paths", () => {
"OEBPS/book.opf":
' ',
"OEBPS/a.xhtml":
- 'Last chapter
Price 10 8 old
山路やまみち を歩く。東京( とうきょう ) に着く。川 を見る。海うみ まで。
',
+ 'Last chapter
Totals
Table 1: Revenue Q1 Q2 100 200
Price 10 8 old
山路やまみち を歩く。東京( とうきょう ) に着く。川 を見る。海うみ まで。
',
"OEBPS/b.xhtml":
'My Novel First chapter Larkspur
Map: open .
Direct divDirect sectionDirect item emphasis trailing
Account: A Balance: 731 Currency: USD
Heading Total Important value 731 BeforeAfter Neighbor
Port 443 Timeout 30 seconds Draft note
Hidden block
Hidden nested
Findable note
Decorative note
Prefixed note
Before boardingCheck passportsCompare names Confirm gate Board promptly Before landing
' +
"Indented\n ",
@@ -1540,6 +1540,8 @@ describe("question answer paths", () => {
"Indented\n Alpha",
"## Chapter 2",
"Last chapter",
+ "Totals\nTable 1: Revenue\nQ1\tQ2\n100\t200",
+ "Table 2: Costs\nRent",
"Price 10 8 old",
"山路(やまみち)を歩く。東京(とうきょう)に着く。川を見る。海(うみ) まで。",
"## Chapter 3",
From 93b8dc3465ef829c8aa3b375190822550387d33f Mon Sep 17 00:00:00 2001
From: Dara Adedeji <76637177+SunkenInTime@users.noreply.github.com>
Date: Wed, 25 Nov 2026 13:00:34 -0500
Subject: [PATCH 074/238] fix(web): Antigravity settings show only the fields
the chosen sign-in method uses (#40494)
Co-authored-by: shivam <91240327+shivamhwp@users.noreply.github.com>
---
.../settings/ProviderSettingsForm.test.ts | 35 ++++++++++++++
.../settings/ProviderSettingsForm.tsx | 46 +++++++++++++++++--
apps/web/src/i18n/translations/de.json | 2 +-
apps/web/src/i18n/translations/en.json | 2 +-
apps/web/src/i18n/translations/es.json | 2 +-
apps/web/src/i18n/translations/fr.json | 2 +-
apps/web/src/i18n/translations/ja.json | 2 +-
apps/web/src/i18n/translations/ko.json | 2 +-
apps/web/src/i18n/translations/pt-BR.json | 2 +-
apps/web/src/i18n/translations/ru.json | 2 +-
apps/web/src/i18n/translations/sv.json | 2 +-
apps/web/src/i18n/translations/zh.json | 2 +-
packages/contracts/src/settings.ts | 23 ++++++++--
13 files changed, 107 insertions(+), 17 deletions(-)
diff --git a/apps/web/src/components/settings/ProviderSettingsForm.test.ts b/apps/web/src/components/settings/ProviderSettingsForm.test.ts
index 49aa7c30b567d..91b0962a5c32b 100644
--- a/apps/web/src/components/settings/ProviderSettingsForm.test.ts
+++ b/apps/web/src/components/settings/ProviderSettingsForm.test.ts
@@ -52,6 +52,41 @@ describe("ProviderSettingsForm helpers", () => {
expect(next).toEqual({ forkOwned: 1 });
});
+ it("shows Antigravity credential fields only for the sign-in methods that read them, or while set", () => {
+ const antigravity = providerClients.get(ProviderDriverKind.make("antigravity"));
+ expect(antigravity).toBeDefined();
+ const keysFor = (value?: unknown) =>
+ deriveProviderSettingsFields(antigravity!, value).map((field) => field.key);
+
+ expect(keysFor({})).toEqual(["authMethod", "binaryPath"]);
+ expect(
+ keysFor({
+ authMethod: "oauth-personal",
+ apiKey: { provider: "vault", reference: "antigravity" },
+ gcpLocation: "us-central1",
+ }),
+ ).toEqual(["authMethod", "apiKey", "gcpLocation", "binaryPath"]);
+ expect(keysFor({ authMethod: "oauth-business" })).toEqual([
+ "authMethod",
+ "gcpProject",
+ "gcpLocation",
+ "binaryPath",
+ ]);
+ expect(keysFor({ authMethod: "gemini-api-key" })).toEqual([
+ "authMethod",
+ "apiKey",
+ "binaryPath",
+ ]);
+ expect(keysFor({ authMethod: "agent-platform" })).toEqual([
+ "authMethod",
+ "apiKey",
+ "gcpProject",
+ "gcpLocation",
+ "binaryPath",
+ ]);
+ expect(keysFor()).toEqual(["authMethod", "apiKey", "gcpProject", "gcpLocation", "binaryPath"]);
+ });
+
it("does not store a text value its field's schema rejects", () => {
const claude = providerClients.get(ProviderDriverKind.make("claudeAgent"));
expect(claude).toBeDefined();
diff --git a/apps/web/src/components/settings/ProviderSettingsForm.tsx b/apps/web/src/components/settings/ProviderSettingsForm.tsx
index 6848be472d816..fd185edfdb42c 100644
--- a/apps/web/src/components/settings/ProviderSettingsForm.tsx
+++ b/apps/web/src/components/settings/ProviderSettingsForm.tsx
@@ -162,8 +162,10 @@ const PACKAGE_FIELD_TEXT: ReadonlyMap = new Map([
),
],
[
- "Google accounts use your subscription; API keys and Agent Platform bill usage.",
- msg("Google accounts use your subscription; API keys and Agent Platform bill usage."),
+ "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.",
+ msg(
+ "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.",
+ ),
],
[
"Gemini or Vertex AI express key. Stored separately on the host.",
@@ -259,6 +261,25 @@ function packageFieldText(text: string, resolve: MessageResolver): string {
return entry === undefined ? text : resolve(entry);
}
+/** An unset select shows, and acts as, its first option. */
+function readSelectValue(
+ config: unknown,
+ key: string,
+ options: ReadonlyArray | undefined,
+): string {
+ return readProviderConfigString(config, key) || (options?.[0]?.value ?? "");
+}
+
+function hasConfiguredValue(config: unknown, key: string): boolean {
+ if (config === null || typeof config !== "object") return false;
+ const value = (config as Record)[key];
+ return value !== undefined && value !== "";
+}
+
+/**
+ * Without a `value`, lists every field. With one, a `visibleWhen` field is hidden only while empty:
+ * a leftover value still reaches the server, so it stays visible and clearable.
+ */
export function deriveProviderSettingsFields(
definition: SettingsFormDefinition,
value?: unknown,
@@ -285,6 +306,23 @@ export function deriveProviderSettingsFields(
const fieldSchema = definition.settingsSchema.fields[key]!;
const formAnnotation = readProviderSettingsFormAnnotation(fieldSchema);
if (formAnnotation.hidden) return [];
+ const visibleWhen = formAnnotation.visibleWhen;
+ const controller =
+ visibleWhen === undefined ? undefined : definition.settingsSchema.fields[visibleWhen.field];
+ if (
+ visibleWhen !== undefined &&
+ value !== undefined &&
+ !hasConfiguredValue(value, key) &&
+ !visibleWhen.values.includes(
+ readSelectValue(
+ value,
+ visibleWhen.field,
+ controller && readProviderSettingsFormAnnotation(controller).options,
+ ),
+ )
+ ) {
+ return [];
+ }
if (isLocalAcp && key !== "source" && key !== "commandPath") return [];
const annotatedTitle = readFieldAnnotationString(fieldSchema, "title");
@@ -592,7 +630,7 @@ function ProviderSettingsSelect({
}) {
const options = field.options ?? [];
const fallback = options[0]?.value ?? "";
- const current = readProviderConfigString(value, field.key) || fallback;
+ const current = readSelectValue(value, field.key, options);
const label = options.find((option) => option.value === current)?.label ?? current;
return (
Erweitert.",
- "484df18e29b21047": "Google-Konten nutzen dein Abonnement; API-Schlüssel und Agent Platform rechnen nach Nutzung ab.",
+ "9610fb9f4d9849ec": "Google-Konto und Gemini Enterprise nutzen deinen bestehenden Tarif. Gemini-API-Schlüssel und Agent Platform rechnen pro Nutzung über deinen Schlüssel oder dein Google-Cloud-Projekt ab.",
"931df01584748bf9": "Express-Schlüssel für Gemini oder Vertex AI. Wird separat auf dem Host gespeichert.",
"8bf0f6ed8dd4b77e": "Erforderlich für Gemini Enterprise. Agent Platform verwendet es, wenn kein API-Schlüssel gesetzt ist.",
"7c735c8fbd3fb6e3": "Region für Gemini Enterprise oder Agent Platform.",
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index 9c06b25632e08..0de8e0ffcbba7 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -9468,7 +9468,7 @@
"33fbce50a4ea67e6": "Additional CLI arguments passed on session start.",
"abdee70d90cb26a3": "Compact after 100,000 to 1,000,000 tokens. Leave empty to use Claude's default.",
"f907b2466603538e": "When to compact an idle thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Overrides the default in Providers > Advanced.",
- "484df18e29b21047": "Google accounts use your subscription; API keys and Agent Platform bill usage.",
+ "9610fb9f4d9849ec": "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.",
"931df01584748bf9": "Gemini or Vertex AI express key. Stored separately on the host.",
"8bf0f6ed8dd4b77e": "Required for Gemini Enterprise. Agent Platform uses it when no API key is set.",
"7c735c8fbd3fb6e3": "Region for Gemini Enterprise or Agent Platform.",
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index 578276a00e78d..79f4a2bc3e13f 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -9458,7 +9458,7 @@
"33fbce50a4ea67e6": "Argumentos de CLI adicionales que se pasan al iniciar la sesión.",
"abdee70d90cb26a3": "Compacta tras 100 000 a 1 000 000 de tokens. Déjalo vacío para usar el valor predeterminado de Claude.",
"f907b2466603538e": "Cuándo compactar un hilo inactivo de más de 200 000 tokens: cuando vuelvas, justo antes de que caduque su caché de prompts, o nunca. Sustituye el valor predeterminado de Proveedores > Avanzado.",
- "484df18e29b21047": "Las cuentas de Google usan tu suscripción; las claves de API y Agent Platform facturan el uso.",
+ "9610fb9f4d9849ec": "Cuenta de Google y Gemini Enterprise usan tu plan actual. Clave de API de Gemini y Agent Platform cobran por uso en tu clave o proyecto de Google Cloud.",
"931df01584748bf9": "Clave exprés de Gemini o Vertex AI. Se guarda por separado en el host.",
"8bf0f6ed8dd4b77e": "Obligatorio para Gemini Enterprise. Agent Platform lo usa cuando no hay ninguna clave de API.",
"7c735c8fbd3fb6e3": "Región de Gemini Enterprise o Agent Platform.",
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index 3a26b9305572b..6bdf8c12b6630 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -9460,7 +9460,7 @@
"33fbce50a4ea67e6": "Arguments CLI supplémentaires passés au démarrage de la session.",
"abdee70d90cb26a3": "Compacter après 100 000 à 1 000 000 de jetons. Laissez vide pour utiliser la valeur par défaut de Claude.",
"f907b2466603538e": "Quand compacter un fil inactif de plus de 200 000 jetons : à votre retour, juste avant l’expiration de son cache de prompt, ou jamais. Remplace la valeur par défaut de Fournisseurs > Avancé.",
- "484df18e29b21047": "Les comptes Google utilisent votre abonnement ; les clés d’API et Agent Platform facturent l’utilisation.",
+ "9610fb9f4d9849ec": "Compte Google et Gemini Enterprise utilisent votre forfait existant. Clé d’API Gemini et Agent Platform facturent à l’usage sur votre clé ou projet Google Cloud.",
"931df01584748bf9": "Clé express Gemini ou Vertex AI. Stockée séparément sur l’hôte.",
"8bf0f6ed8dd4b77e": "Requis pour Gemini Enterprise. Agent Platform l’utilise quand aucune clé d’API n’est définie.",
"7c735c8fbd3fb6e3": "Région pour Gemini Enterprise ou Agent Platform.",
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index 1fb5dfff0591d..f82bb265fc1d6 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -9416,7 +9416,7 @@
"33fbce50a4ea67e6": "セッション開始時に渡す追加の CLI 引数です。",
"abdee70d90cb26a3": "100,000〜1,000,000 トークンを超えたら圧縮します。空欄にすると Claude のデフォルトを使用します。",
"f907b2466603538e": "200,000 トークンを超えるアイドル状態のスレッドを圧縮するタイミングです。戻ってきた後、プロンプトキャッシュの期限切れ直前、またはしない、から選びます。プロバイダー > 詳細のデフォルトを上書きします。",
- "484df18e29b21047": "Google アカウントはサブスクリプションを使用します。API キーと Agent Platform は使用量に応じて課金されます。",
+ "9610fb9f4d9849ec": "Google アカウントと Gemini Enterprise は既存のプランを使用します。Gemini API キーと Agent Platform は、キーまたは Google Cloud プロジェクトに使用量に応じて課金されます。",
"931df01584748bf9": "Gemini または Vertex AI エクスプレスのキーです。ホストに別途保存されます。",
"8bf0f6ed8dd4b77e": "Gemini Enterprise では必須です。API キーが設定されていない場合、Agent Platform がこれを使用します。",
"7c735c8fbd3fb6e3": "Gemini Enterprise または Agent Platform のリージョンです。",
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index a0ac24a5a0c26..868ee5709c7b9 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -9417,7 +9417,7 @@
"33fbce50a4ea67e6": "세션 시작 시 전달할 추가 CLI 인수입니다.",
"abdee70d90cb26a3": "100,000~1,000,000 토큰 후 압축합니다. 비워 두면 Claude 기본값을 사용합니다.",
"f907b2466603538e": "200,000 토큰을 넘는 유휴 스레드를 압축할 시점입니다. 돌아왔을 때, 프롬프트 캐시가 만료되기 직전, 또는 안 함 중에서 고릅니다. 제공자 > 고급의 기본값을 재정의합니다.",
- "484df18e29b21047": "Google 계정은 구독을 사용하고, API 키와 Agent Platform은 사용량에 따라 요금이 청구됩니다.",
+ "9610fb9f4d9849ec": "Google 계정과 Gemini Enterprise는 기존 요금제를 사용합니다. Gemini API 키와 Agent Platform은 사용량에 따라 키 또는 Google Cloud 프로젝트로 요금이 청구됩니다.",
"931df01584748bf9": "Gemini 또는 Vertex AI 익스프레스 키입니다. 호스트에 따로 저장됩니다.",
"8bf0f6ed8dd4b77e": "Gemini Enterprise에 필요합니다. API 키가 설정되지 않으면 Agent Platform에서 사용합니다.",
"7c735c8fbd3fb6e3": "Gemini Enterprise 또는 Agent Platform의 리전입니다.",
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index 23f825cfae590..716a2901b4081 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -9460,7 +9460,7 @@
"33fbce50a4ea67e6": "Argumentos de CLI adicionais passados no início da sessão.",
"abdee70d90cb26a3": "Compactar após 100.000 a 1.000.000 tokens. Deixe vazio para usar o padrão do Claude.",
"f907b2466603538e": "Quando compactar uma thread ociosa com mais de 200.000 tokens: depois que você voltar, pouco antes de o cache do prompt expirar ou nunca. Substitui o padrão em Provedores > Avançado.",
- "484df18e29b21047": "Contas Google usam sua assinatura; chaves de API e o Agent Platform cobram pelo uso.",
+ "9610fb9f4d9849ec": "Conta Google e Gemini Enterprise usam seu plano atual. Chave de API do Gemini e Agent Platform cobram por uso na sua chave ou projeto do Google Cloud.",
"931df01584748bf9": "Chave express do Gemini ou do Vertex AI. Armazenada separadamente no host.",
"8bf0f6ed8dd4b77e": "Obrigatório para o Gemini Enterprise. O Agent Platform usa quando nenhuma chave de API está definida.",
"7c735c8fbd3fb6e3": "Região do Gemini Enterprise ou do Agent Platform.",
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index cae6ba120f711..af80a928e9382 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -9461,7 +9461,7 @@
"33fbce50a4ea67e6": "Дополнительные аргументы CLI, передаваемые при запуске сеанса.",
"abdee70d90cb26a3": "Сжимать после 100 000 – 1 000 000 токенов. Оставьте пустым, чтобы использовать значение Claude по умолчанию.",
"f907b2466603538e": "Когда сжимать простаивающий тред больше 200 000 токенов: после вашего возвращения, перед самым истечением кеша промпта или никогда. Переопределяет значение по умолчанию в разделе Провайдеры > Дополнительно.",
- "484df18e29b21047": "Аккаунты Google используют вашу подписку; за API-ключи и Agent Platform взимается плата за использование.",
+ "9610fb9f4d9849ec": "Аккаунт Google и Gemini Enterprise используют ваш текущий план. API-ключ Gemini и Agent Platform взимают оплату за использование с вашего ключа или проекта Google Cloud.",
"931df01584748bf9": "Ключ Gemini или Vertex AI express. Хранится на хосте отдельно.",
"8bf0f6ed8dd4b77e": "Требуется для Gemini Enterprise. Agent Platform использует его, если API-ключ не задан.",
"7c735c8fbd3fb6e3": "Регион для Gemini Enterprise или Agent Platform.",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index 811c6ceabd7fe..8fbbc80a44485 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -9466,7 +9466,7 @@
"33fbce50a4ea67e6": "Extra CLI-argument som skickas när sessionen startar.",
"abdee70d90cb26a3": "Komprimera efter 100 000 till 1 000 000 token. Lämna tomt för att använda Claudes standard.",
"f907b2466603538e": "När en inaktiv tråd över 200 000 token ska komprimeras: när du kommer tillbaka, precis innan dess promptcache går ut, eller aldrig. Åsidosätter standardvärdet i Leverantörer > Avancerat.",
- "484df18e29b21047": "Google-konton använder din prenumeration; API-nycklar och Agent Platform debiteras efter användning.",
+ "9610fb9f4d9849ec": "Google-konto och Gemini Enterprise använder din befintliga plan. Gemini API-nyckel och Agent Platform debiteras per användning via din nyckel eller ditt Google Cloud-projekt.",
"931df01584748bf9": "Express-nyckel för Gemini eller Vertex AI. Lagras separat på värden.",
"8bf0f6ed8dd4b77e": "Krävs för Gemini Enterprise. Agent Platform använder den när ingen API-nyckel är angiven.",
"7c735c8fbd3fb6e3": "Region för Gemini Enterprise eller Agent Platform.",
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index 5f4d8cfc31658..26db796ccfe17 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -9476,7 +9476,7 @@
"33fbce50a4ea67e6": "启动智能体会话时传入的额外 CLI 参数。",
"abdee70d90cb26a3": "达到 100,000 至 1,000,000 token 时压缩。留空则使用 Claude 的默认值。",
"f907b2466603538e": "空闲且超过 200,000 token 的会话何时压缩:在你回来后、提示缓存即将过期前,或从不压缩。覆盖“智能体提供方 > 高级”中的默认设置。",
- "484df18e29b21047": "Google 账户使用你的订阅;API 密钥和 Agent Platform 按用量计费。",
+ "9610fb9f4d9849ec": "Google 账户和 Gemini Enterprise 使用你现有的套餐。Gemini API 密钥和 Agent Platform 按用量向你的密钥或 Google Cloud 项目计费。",
"931df01584748bf9": "Gemini 或 Vertex AI express 密钥,单独存储在主机上。",
"8bf0f6ed8dd4b77e": "Gemini Enterprise 必填。未设置 API 密钥时,Agent Platform 使用此项目。",
"7c735c8fbd3fb6e3": "Gemini Enterprise 或 Agent Platform 使用的区域。",
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 4922cceeda19f..630527f75690b 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -662,6 +662,10 @@ export interface ProviderSettingsFormAnnotation {
readonly clearWhenEmpty?: "omit" | "persist" | undefined;
readonly options?: ReadonlyArray | undefined;
+ /** Shows the field only while the named select field holds one of these values. */
+ readonly visibleWhen?:
+ | { readonly field: string; readonly values: ReadonlyArray }
+ | undefined;
}
export function secretSettingsFields(schema: {
@@ -881,6 +885,10 @@ export const AntigravityAuthMethod = Schema.Literals(
ANTIGRAVITY_AUTH_METHODS.map((method) => method.value),
);
export type AntigravityAuthMethod = typeof AntigravityAuthMethod.Type;
+const antigravityGcpFieldVisibility = {
+ field: "authMethod",
+ values: ["oauth-business", "agent-platform"],
+} satisfies ProviderSettingsFormAnnotation["visibleWhen"];
export const AntigravitySettings = makeProviderSettingsSchema(
{
@@ -893,7 +901,7 @@ export const AntigravitySettings = makeProviderSettingsSchema(
Schema.annotateKey({
title: "Sign-in method",
description:
- "Google accounts use your subscription; API keys and Agent Platform bill usage.",
+ "Google account and Gemini Enterprise use your existing plan. Gemini API key and Agent Platform charge per use to your key or Google Cloud project.",
providerSettingsForm: {
control: "select",
options: ANTIGRAVITY_AUTH_METHODS,
@@ -911,6 +919,7 @@ export const AntigravitySettings = makeProviderSettingsSchema(
control: "password",
placeholder: "Optional",
clearWhenEmpty: "omit",
+ visibleWhen: { field: "authMethod", values: ["gemini-api-key", "agent-platform"] },
},
}),
),
@@ -920,7 +929,11 @@ export const AntigravitySettings = makeProviderSettingsSchema(
title: "GCP project",
description:
"Required for Gemini Enterprise. Agent Platform uses it when no API key is set.",
- providerSettingsForm: { placeholder: "my-project-id", clearWhenEmpty: "omit" },
+ providerSettingsForm: {
+ placeholder: "my-project-id",
+ clearWhenEmpty: "omit",
+ visibleWhen: antigravityGcpFieldVisibility,
+ },
}),
),
gcpLocation: TrimmedString.pipe(
@@ -928,7 +941,11 @@ export const AntigravitySettings = makeProviderSettingsSchema(
Schema.annotateKey({
title: "GCP location",
description: "Region for Gemini Enterprise or Agent Platform.",
- providerSettingsForm: { placeholder: "us-central1", clearWhenEmpty: "omit" },
+ providerSettingsForm: {
+ placeholder: "us-central1",
+ clearWhenEmpty: "omit",
+ visibleWhen: antigravityGcpFieldVisibility,
+ },
}),
),
binaryPath: TrimmedString.pipe(
From 667cb3b25571fc3a1700f29d62453ed50acd5c7c Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 10:02:19 -0800
Subject: [PATCH 075/238] fix(contracts): pull request and issue errors reach
clients behind T3 Connect (#42956)
Co-authored-by: Claude Opus 5.5
---
packages/contracts/src/issue.ts | 10 ++++++----
packages/contracts/src/pullRequest.test.ts | 21 ++++++++++++++++++++-
packages/contracts/src/pullRequest.ts | 5 +++--
3 files changed, 29 insertions(+), 7 deletions(-)
diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts
index 7aabd5e70ba21..8a39e9100fea5 100644
--- a/packages/contracts/src/issue.ts
+++ b/packages/contracts/src/issue.ts
@@ -503,10 +503,11 @@ export class IssueOperationError extends Schema.TaggedError
retryAt: Schema.optional(Schema.Number),
cause: Schema.optional(Schema.Defect()),
},
- { httpApiStatus: 502 },
+ // Not 502: Cloudflare, in front of T3 Connect, swaps an origin 502 for its own page.
+ { httpApiStatus: 503 },
) {
[HttpServerRespondable.symbol]() {
- return HttpServerResponse.schemaJson(IssueOperationError)(this, { status: 502 });
+ return HttpServerResponse.schemaJson(IssueOperationError)(this, { status: 503 });
}
override get message(): string {
@@ -692,10 +693,11 @@ export class IssueTrackerConnectionError extends Schema.TaggedError {
expect(resolvePullRequestAuthorFilter("meredith", "bilal")).toBe("meredith");
});
});
+
+describe("PullRequestOperationError", () => {
+ // Cloudflare swaps an origin 502 for its own body without CORS headers, so a
+ // client behind a T3 Connect tunnel sees a transport error instead of this error.
+ it.effect("answers with a status a Cloudflare tunnel passes through", () =>
+ Effect.gen(function* () {
+ const error = new PullRequestOperationError({
+ operation: "diff",
+ detail: "gitlab requests to gitlab.com are paused until the rate limit resets.",
+ });
+ const response = yield* error[HttpServerRespondable.symbol]();
+ expect(response.status).not.toBe(502);
+ expect(PullRequestOperationError.ast.annotations?.httpApiStatus).not.toBe(502);
+ }),
+ );
+});
diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts
index 311831de776f5..a820ba49c799b 100644
--- a/packages/contracts/src/pullRequest.ts
+++ b/packages/contracts/src/pullRequest.ts
@@ -1065,10 +1065,11 @@ export class PullRequestOperationError extends Schema.TaggedError
Date: Wed, 25 Nov 2026 12:07:07 -0600
Subject: [PATCH 076/238] fix(web): exact 1,024-column CSV and TSV files no
longer show the truncated-columns banner (#42973)
Co-authored-by: Julius Marminge
---
.../AttachmentFilePreview.browser.test.tsx | 19 +++++++++++++++++++
.../src/components/files/LargeTextViewer.tsx | 14 ++++++++++----
.../src/components/files/largeText.worker.ts | 18 ++++++++++++++----
.../src/components/files/largeTextProtocol.ts | 9 ++++++++-
4 files changed, 51 insertions(+), 9 deletions(-)
diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
index 46af0f57af84c..260583c8f2f79 100644
--- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
@@ -1149,6 +1149,25 @@ describe("large text preview recovery", () => {
expect(screen.container.querySelector('[role="alert"]')).toBeNull();
});
+ it.each([
+ [1024, false],
+ [1025, true],
+ ] as const)(
+ "shows the column truncation banner only when a CSV exceeds 1,024 columns (%i columns)",
+ async (columnCount, truncated) => {
+ const row = Array.from({ length: columnCount }, (_, i) => i).join(",");
+ await using screen = await render(
+ ,
+ );
+ const hasBanner = () =>
+ screen.container.textContent?.includes("Showing the first 1,024 columns") ?? false;
+ expect(hasBanner()).toBe(truncated);
+ const status = () => screen.container.querySelector('[role="status"]')?.textContent ?? "";
+ await vi.waitFor(() => expect(status()).toContain("1 row · 1,024 columns"), 10_000);
+ expect(hasBanner()).toBe(truncated);
+ },
+ );
+
it("reloads a partial page when the indexed row count grows", async () => {
const load = vi.fn();
const rows = [["first"]];
diff --git a/apps/web/src/components/files/LargeTextViewer.tsx b/apps/web/src/components/files/LargeTextViewer.tsx
index fc9a890dd9b3e..44edca218c00e 100644
--- a/apps/web/src/components/files/LargeTextViewer.tsx
+++ b/apps/web/src/components/files/LargeTextViewer.tsx
@@ -6,7 +6,11 @@ import { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview";
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
import { useClientSettings } from "~/hooks/useSettings";
import { FileSurfaceFailure, FileSurfaceLoading, FileSurfaceNotice } from "./fileSurfaceChrome";
-import { PREVIEW_PAGE_ROWS, type TextPreviewResult } from "./largeTextProtocol";
+import {
+ LARGE_TEXT_MAX_COLUMNS,
+ PREVIEW_PAGE_ROWS,
+ type TextPreviewResult,
+} from "./largeTextProtocol";
import { previewFailureText } from "./previewFailureMessages";
import VirtualTablePreview from "./VirtualTablePreview";
@@ -17,7 +21,7 @@ function firstScreen(text: string, delimiter: "," | "\t" | null, complete: boole
const rows = delimiter
? parseDelimitedPreview(text, delimiter, {
maxRows: PREVIEW_PAGE_ROWS * 2 + 1,
- maxColumns: 1024,
+ maxColumns: LARGE_TEXT_MAX_COLUMNS + 1,
maxCellLength: FIRST_SCREEN_BYTES,
}).rows
: text
@@ -35,6 +39,7 @@ type Meta = Extract;
function firstScreenState(text: string, delimiter: "," | "\t" | null, complete: boolean) {
const rows = firstScreen(text, delimiter, complete);
if (!rows.length) return null;
+ const widest = rows.reduce((max, row) => Math.max(max, row.length), 1);
return {
pages: new Map(
[0, PREVIEW_PAGE_ROWS]
@@ -44,7 +49,8 @@ function firstScreenState(text: string, delimiter: "," | "\t" | null, complete:
meta: {
type: "meta",
count: rows.length,
- columns: rows.reduce((max, row) => Math.max(max, row.length), 1),
+ columns: Math.min(LARGE_TEXT_MAX_COLUMNS, widest),
+ columnsTruncated: widest > LARGE_TEXT_MAX_COLUMNS,
complete: false,
} satisfies Meta as Meta,
};
@@ -280,7 +286,7 @@ export default function LargeTextViewer(props: {
) : null}
- {meta.columns === 1024 ? (
+ {meta.columnsTruncated ? (
Showing the first 1,024 columns. Source and Save retain every column.
diff --git a/apps/web/src/components/files/largeText.worker.ts b/apps/web/src/components/files/largeText.worker.ts
index 83a1ddae0a8e5..94b04a2b7ed48 100644
--- a/apps/web/src/components/files/largeText.worker.ts
+++ b/apps/web/src/components/files/largeText.worker.ts
@@ -19,6 +19,16 @@ let columns = 1;
function reply(value: TextPreviewResult) {
self.postMessage(value, { transfer: [] });
}
+function meta() {
+ reply({
+ type: "meta",
+ count: entries - 1,
+ columns: Math.min(LARGE_TEXT_MAX_COLUMNS, columns),
+ columnsTruncated: columns > LARGE_TEXT_MAX_COLUMNS,
+ complete,
+ sizeBytes: size,
+ });
+}
function at(index: number) {
return offsets[index >>> 16]![index & 65535]!;
}
@@ -163,7 +173,7 @@ async function open(input: Extract
) {
if (byte === 10 || byte === 13) {
if (entries > LARGE_TEXT_MAX_ROWS) throw new PreviewError({ code: "text-too-many-rows" });
set(entries++, pos + 1);
- columns = Math.min(LARGE_TEXT_MAX_COLUMNS, Math.max(columns, rowColumns));
+ columns = Math.max(columns, rowColumns);
rowColumns = 1;
fieldStart = true;
cr = byte === 13;
@@ -171,7 +181,7 @@ async function open(input: Extract) {
}
size += value.length;
if (!first && entries > 1) {
- reply({ type: "meta", count: entries - 1, columns, complete: false, sizeBytes: size });
+ meta();
await page(0);
first = true;
}
@@ -180,10 +190,10 @@ async function open(input: Extract) {
if (size > at(entries - 1)) {
if (entries > LARGE_TEXT_MAX_ROWS) throw new PreviewError({ code: "text-too-many-rows" });
set(entries++, size);
- columns = Math.min(LARGE_TEXT_MAX_COLUMNS, Math.max(columns, rowColumns));
+ columns = Math.max(columns, rowColumns);
}
complete = true;
- reply({ type: "meta", count: entries - 1, columns, complete, sizeBytes: size });
+ meta();
await page(0);
} finally {
await reader.cancel();
diff --git a/apps/web/src/components/files/largeTextProtocol.ts b/apps/web/src/components/files/largeTextProtocol.ts
index 661b15c8c8e7d..fbc4fcc137e5f 100644
--- a/apps/web/src/components/files/largeTextProtocol.ts
+++ b/apps/web/src/components/files/largeTextProtocol.ts
@@ -14,7 +14,14 @@ export type TextPreviewRequest =
| { type: "page"; index: number }
| { type: "copy" };
export type TextPreviewResult =
- | { type: "meta"; count: number; columns: number; complete: boolean; sizeBytes?: number }
+ | {
+ type: "meta";
+ count: number;
+ columns: number;
+ columnsTruncated: boolean;
+ complete: boolean;
+ sizeBytes?: number;
+ }
| { type: "page"; index: number; rows: string[][] }
| { type: "copy"; text: string }
| ({ type: "error"; operation: TextPreviewRequest["type"] } & PreviewFailure);
From cbc3057f590203372b2070afdc97368ccca82403 Mon Sep 17 00:00:00 2001
From: shivam <91240327+shivamhwp@users.noreply.github.com>
Date: Wed, 25 Nov 2026 23:38:07 +0530
Subject: [PATCH 077/238] fix(web,mobile): a running Read's image shows a
loading frame, not "Image unavailable" (#42921)
Co-authored-by: Julius Marminge
Co-authored-by: Claude Opus 5.5
---
.../src/features/threads/ThreadFeed.tsx | 15 +-
apps/mobile/src/lib/threadActivity.ts | 11 +-
.../src/components/chat/ChatMarkdownMedia.tsx | 38 +++--
.../chat/MessagesTimeline.browser.test.tsx | 79 +++++++++-
.../chat/MessagesTimeline.logic.test.ts | 4 +-
.../components/chat/MessagesTimeline.logic.ts | 18 ++-
.../components/chat/TimelineWorkEntryRow.tsx | 3 +-
.../src/work-log/presentation.test.ts | 67 +++++++++
.../src/work-log/presentation.ts | 33 ++++-
...ding-read-image-shows-loading-frame.e2e.ts | 139 ++++++++++++++++++
10 files changed, 367 insertions(+), 40 deletions(-)
create mode 100644 scripts/scenarios/pending-read-image-shows-loading-frame.e2e.ts
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index 9b59571c5fff4..c1522eab19131 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -2137,9 +2137,20 @@ function renderFeedEntry(
const thumbnailWidth = Math.floor((props.contentWidth - VIEWED_IMAGE_GAP) / 2);
return (
- {entry.paths.map((path) => (
+ {entry.images.map(({ path, pending }) => (
- {props.renderViewedImage({ href: path, alt: null, title: null })}
+ {pending ? (
+ // The running Read may not have written the file yet, so hold its frame unrequested.
+
+ ) : (
+ props.renderViewedImage({ href: path, alt: null, title: null })
+ )}
))}
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index 50e87752574b3..0d8e5d30b9b67 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -30,8 +30,9 @@ import {
resolveWorkEntryToolPresentation,
summarizeToolGroup,
toolGroupSummaryKind,
- workEntriesViewedImagePaths,
+ workEntriesViewedImages,
type ToolGroupSummaryKind,
+ type ViewedImage,
type WorkLogPresentationEntry,
type WorkLogToolLifecycleStatus,
workEntryHiddenByToolCallVisibility,
@@ -245,7 +246,7 @@ type ThreadFeedEntryContent =
readonly id: string;
readonly createdAt: string;
readonly runId: RunId | null;
- readonly paths: ReadonlyArray;
+ readonly images: ReadonlyArray;
}
| {
readonly type: "run-fold";
@@ -2237,14 +2238,14 @@ function appendActivityGroupRows(
activeTail && isTrailingRun,
resolve,
);
- const paths = workEntriesViewedImagePaths(groupableRun.map((activity) => activity.workEntry));
- if (paths.length > 0) {
+ const images = workEntriesViewedImages(groupableRun.map((activity) => activity.workEntry));
+ if (images.length > 0) {
result.push({
type: "viewed-images",
id: `${groupId}:viewed-images`,
createdAt: groupableRun[0]!.createdAt,
runId: groupableRun[0]!.runId,
- paths,
+ images,
});
}
groupableRun = [];
diff --git a/apps/web/src/components/chat/ChatMarkdownMedia.tsx b/apps/web/src/components/chat/ChatMarkdownMedia.tsx
index 1bf15380c1217..78093d0bc90df 100644
--- a/apps/web/src/components/chat/ChatMarkdownMedia.tsx
+++ b/apps/web/src/components/chat/ChatMarkdownMedia.tsx
@@ -85,11 +85,11 @@ export function authoredImageSizeStyle(
}
/**
- * An unavailable file has no dimensions, so its `aspect-video w-full` frame
- * would fill the row and `max-height` would squash it. Bound the width so the
- * frame stays 16:9 at the height cap.
+ * A loading or unavailable file has no dimensions, so its `aspect-video w-full`
+ * frame would fill the row and `max-height` would squash it. Bound the width so
+ * the frame stays 16:9 at the height cap.
*/
-function unavailableImageSizeStyle(maxHeightRem: number): CSSProperties | undefined {
+function unsizedImageFrameStyle(maxHeightRem: number): CSSProperties | undefined {
if (maxHeightRem === 30) return undefined;
return { maxWidth: `min(100%, 30rem, ${(maxHeightRem * 16) / 9}rem)` };
}
@@ -194,6 +194,8 @@ export function ChatMarkdownImage(props: {
readonly standalone: boolean;
readonly className?: string | undefined;
readonly style?: CSSProperties | undefined;
+ /** The loading or unavailable frame's size, when it differs from the image's. */
+ readonly frameStyle?: CSSProperties | undefined;
readonly imageProps?:
| Omit, "src" | "alt" | "className" | "style">
| undefined;
@@ -282,7 +284,7 @@ export function ChatMarkdownImage(props: {
CHAT_MARKDOWN_IMAGE_FRAME_CLASS_NAME,
"relative",
)}
- style={props.style}
+ style={props.frameStyle ?? props.style}
{...(failed
? { role: "alert" as const }
: { role: "status" as const, "aria-label": gt("Loading image") })}
@@ -366,6 +368,8 @@ export function assetMediaActionsSource(input: {
readonly workspaceRoot?: string | undefined;
readonly originalUrl?: string | undefined;
readonly downloadable?: boolean | undefined;
+ /** The file may not exist yet: keep only actions that do not read it. */
+ readonly pending?: boolean | undefined;
}): MediaActionSource {
const { environmentId, resource } = input;
const path =
@@ -384,9 +388,13 @@ export function assetMediaActionsSource(input: {
kind: input.kind,
name: input.name,
src: input.src,
- ...(input.downloadable === false ? {} : { asset: { environmentId, resource } }),
+ ...(input.downloadable === false || input.pending
+ ? {}
+ : { asset: { environmentId, resource } }),
...(reference ? { reference } : {}),
- ...(relativePath && (resource._tag === "media-file" || resource._tag === "workspace-file")
+ ...(relativePath &&
+ !input.pending &&
+ (resource._tag === "media-file" || resource._tag === "workspace-file")
? {
onOpenFile: () =>
useRightPanelStore
@@ -400,6 +408,8 @@ export function assetMediaActionsSource(input: {
export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props: {
readonly environmentId: EnvironmentId;
readonly resource: ChatMarkdownAssetResource;
+ /** Hold the loading frame without asking for the file, which may not exist yet. */
+ readonly pending?: boolean | undefined;
readonly kind?: "image" | "video";
readonly alt: string;
readonly copyMarkdown?: string;
@@ -424,7 +434,7 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
const workspaceMutationId = props.workspaceMutationId ?? threadWorkspaceMutationId;
const assetUrl = useAssetUrlState(
props.environmentId,
- resource,
+ props.pending ? null : resource,
workspaceMutationId !== undefined &&
props.kind !== "video" &&
(resource._tag === "media-file" || resource._tag === "workspace-file")
@@ -453,11 +463,11 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
props.style ??
(knownSize
? authoredImageSizeStyle(knownSize.width, knownSize.height, maxHeightRem)
- : unavailable
- ? unavailableImageSizeStyle(maxHeightRem)
- : maxHeightRem !== 30
- ? { maxHeight: `${maxHeightRem}rem` }
- : undefined);
+ : maxHeightRem !== 30
+ ? { maxHeight: `${maxHeightRem}rem` }
+ : undefined);
+ // Kept until the image decodes: an SVG's URL arrives without dimensions.
+ const frameStyle = props.style ?? (knownSize ? style : unsizedImageFrameStyle(maxHeightRem));
const actionsSource = assetMediaActionsSource({
environmentId: props.environmentId,
resource,
@@ -467,6 +477,7 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
workspaceRoot: props.workspaceRoot,
originalUrl: props.originalUrl,
downloadable: fallbackSrc === undefined,
+ pending: props.pending,
});
if (props.kind === "video") {
@@ -501,6 +512,7 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
props.className,
)}
style={style}
+ frameStyle={frameStyle}
imageProps={props.imageProps}
actionsSource={actionsSource}
originalUrl={props.originalUrl}
diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
index 4009d7159f0f0..945107293b80c 100644
--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
@@ -88,11 +88,13 @@ vi.mock(import("~/assets/assetUrls"), async (original) => {
return {
...actual,
useAssetUrlState: ((...args: Parameters) =>
- stubbedAsset.failed
- ? { _tag: "Failure" }
- : stubbedAsset.url
- ? { _tag: "Success", url: stubbedAsset.url }
- : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState,
+ args[1] === null
+ ? { _tag: "Loading" }
+ : stubbedAsset.failed
+ ? { _tag: "Failure" }
+ : stubbedAsset.url
+ ? { _tag: "Success", url: stubbedAsset.url }
+ : actual.useAssetUrlState(...args)) as typeof actual.useAssetUrlState,
useAssetUrls: ((...args: Parameters) =>
stubbedAsset.url
? args[1].map(() => stubbedAsset.url)
@@ -2039,7 +2041,10 @@ describe("MessagesTimeline attachments", () => {
kind: "viewed-images",
id: "viewed",
createdAt: CREATED_AT,
- paths: ["/repo/first.png", "/repo/second.png", "/repo/third.png"],
+ images: ["/repo/first.png", "/repo/second.png", "/repo/third.png"].map((path) => ({
+ path,
+ pending: false,
+ })),
}}
/>
,
@@ -2074,7 +2079,10 @@ describe("MessagesTimeline attachments", () => {
kind: "viewed-images",
id: "viewed",
createdAt: CREATED_AT,
- paths: ["/repo/step-1.jpg", "/repo/step-3.jpg"],
+ images: ["/repo/step-1.jpg", "/repo/step-3.jpg"].map((path) => ({
+ path,
+ pending: false,
+ })),
}}
/>
,
@@ -2096,6 +2104,63 @@ describe("MessagesTimeline attachments", () => {
expect(Math.abs(size.width / size.height - 16 / 9)).toBeLessThan(0.02);
});
+ it("holds a loading frame for an image a running Read is opening, then shows the image", async () => {
+ // The file does not exist yet, so asking for it would fail.
+ stubbedAsset.failed = true;
+ onTestFinished(() => {
+ stubbedAsset.failed = false;
+ stubbedAsset.url = "";
+ });
+ const strip = (pending: boolean) => (
+
+
+
+ );
+ await using screen = await renderElement(strip(true));
+ const frame = await vi.waitFor(() => {
+ const element = screen.container.querySelector(
+ '[data-image-gallery] [role="status"]',
+ );
+ expect(element?.getAttribute("aria-label")).toBe("Loading image");
+ return element!;
+ });
+ expect(screen.container.querySelector('[role="alert"]')).toBeNull();
+ expect(screen.text()).not.toContain("Image unavailable");
+ const size = await vi.waitFor(() => {
+ const rect = frame.getBoundingClientRect();
+ expect(rect.width).toBeGreaterThan(0);
+ return rect;
+ });
+ expect(size.height).toBeLessThanOrEqual(161);
+ expect(Math.abs(size.width / size.height - 16 / 9)).toBeLessThan(0.02);
+
+ stubbedAsset.failed = false;
+ stubbedAsset.url =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
+ await screen.rerender(strip(false));
+ await vi.waitFor(() =>
+ expect(
+ screen.container.querySelector(
+ '[data-image-gallery] img[alt="later.png"]',
+ )?.className,
+ ).not.toContain("invisible"),
+ );
+ });
+
it("opens an image from an expanded tool row as a gallery of the turn's viewed images", async () => {
stubbedAsset.url =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=";
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
index 6330bb33c22fa..fc7a5e07e3a74 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
@@ -2457,7 +2457,9 @@ describe("deriveMessagesTimelineRows", () => {
supportsConversationRollback: false,
});
return rows.flatMap((row, index) =>
- row.kind === "viewed-images" ? [{ after: rows[index - 1]?.kind, paths: row.paths }] : [],
+ row.kind === "viewed-images"
+ ? [{ after: rows[index - 1]?.kind, paths: row.images.map(({ path }) => path) }]
+ : [],
);
};
const paths = ["/repo/docs/sidebar.png", "/repo/docs/topbar.png"];
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts
index ae8ad90df43b9..90b324598ba72 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts
@@ -29,8 +29,9 @@ import {
toolGroupAction,
toolGroupSummaryKind,
contextCompactionTokenCounts,
- workEntriesViewedImagePaths,
+ workEntriesViewedImages,
type ToolGroupSummaryKind,
+ type ViewedImage,
liveThoughtLine,
workEntryHiddenByToolCallVisibility,
} from "@t3tools/client-runtime/work-log/presentation";
@@ -583,7 +584,7 @@ type MessagesTimelineRowContent =
kind: "viewed-images";
id: string;
createdAt: string;
- paths: ReadonlyArray;
+ images: ReadonlyArray;
}
| {
kind: "turn-fold";
@@ -710,10 +711,10 @@ function viewedImagesRows(
createdAt: string,
groupedEntries: ReadonlyArray,
): Array> {
- const paths = workEntriesViewedImagePaths(groupedEntries);
- return paths.length === 0
+ const images = workEntriesViewedImages(groupedEntries);
+ return images.length === 0
? []
- : [{ kind: "viewed-images", id: `${groupId}:viewed-images`, createdAt, paths }];
+ : [{ kind: "viewed-images", id: `${groupId}:viewed-images`, createdAt, images }];
}
export function resolveAssistantMessageCopyState({
@@ -2829,8 +2830,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
const bv = b as typeof a;
return (
a.createdAt === bv.createdAt &&
- a.paths.length === bv.paths.length &&
- a.paths.every((path, index) => path === bv.paths[index])
+ a.images.length === bv.images.length &&
+ a.images.every(
+ (image, index) =>
+ image.path === bv.images[index]?.path && image.pending === bv.images[index]?.pending,
+ )
);
}
diff --git a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx
index 5662814a6821e..b6cb9aa6af8df 100644
--- a/apps/web/src/components/chat/TimelineWorkEntryRow.tsx
+++ b/apps/web/src/components/chat/TimelineWorkEntryRow.tsx
@@ -265,7 +265,7 @@ export function ViewedImagesTimelineRow({
if (!threadRef) return null;
return (
- {row.paths.map((path) => {
+ {row.images.map(({ path, pending }) => {
const image = resolveViewedImageAsset(path, {
threadId: threadRef.threadId,
workspaceRoot,
@@ -275,6 +275,7 @@ export function ViewedImagesTimelineRow({
key={path}
environmentId={threadRef.environmentId}
resource={image.resource}
+ pending={pending}
alt={image.alt}
srcFragment={image.srcFragment}
workspaceRoot={workspaceRoot}
diff --git a/packages/client-runtime/src/work-log/presentation.test.ts b/packages/client-runtime/src/work-log/presentation.test.ts
index 32388d11795b8..8238834e23e30 100644
--- a/packages/client-runtime/src/work-log/presentation.test.ts
+++ b/packages/client-runtime/src/work-log/presentation.test.ts
@@ -10,6 +10,9 @@ import {
type WorkLogPresentationEntry,
workEntryIndicatesToolFailure,
workEntryDisplayIndicatesToolFailure,
+ workEntriesViewedImagePaths,
+ workEntriesViewedImages,
+ workEntryViewedImagePath,
} from "./presentation.js";
function commandItem(
@@ -225,3 +228,67 @@ describe("resolveViewedImageAsset", () => {
).toBe("/repo/my shot.png");
});
});
+
+describe("workEntryViewedImagePath", () => {
+ it("withholds a Read's image preview until the Read has finished", () => {
+ const read: WorkLogPresentationEntry = {
+ id: "read",
+ createdAt: "2026-01-01T00:00:00.000Z",
+ label: "Read",
+ tone: "tool",
+ itemType: "dynamic_tool",
+ viewedImagePath: "/repo/out/later3.png",
+ };
+
+ expect(workEntryViewedImagePath({ ...read, toolLifecycleStatus: "inProgress" })).toBeNull();
+ expect(workEntryViewedImagePath({ ...read, toolLifecycleStatus: "completed" })).toBe(
+ "/repo/out/later3.png",
+ );
+ });
+});
+
+describe("workEntriesViewedImages", () => {
+ const read = (
+ id: string,
+ path: string,
+ toolLifecycleStatus: NonNullable
,
+ ): WorkLogPresentationEntry => ({
+ id,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ label: "Read",
+ tone: "tool",
+ itemType: "dynamic_tool",
+ viewedImagePath: path,
+ toolLifecycleStatus,
+ });
+
+ it("marks an image pending until a Read of it finishes", () => {
+ expect(
+ workEntriesViewedImages([
+ read("done", "/repo/a.png", "completed"),
+ read("running", "/repo/b.png", "inProgress"),
+ read("missing", "/repo/c.png", "failed"),
+ read("again", "/repo/a.png", "inProgress"),
+ ]),
+ ).toEqual([
+ { path: "/repo/a.png", pending: false },
+ { path: "/repo/b.png", pending: true },
+ ]);
+ expect(
+ workEntriesViewedImages([
+ read("running", "/repo/b.png", "inProgress"),
+ read("done", "/repo/b.png", "completed"),
+ ]),
+ ).toEqual([{ path: "/repo/b.png", pending: false }]);
+ });
+
+ it("orders the finished images like the strip shows them", () => {
+ expect(
+ workEntriesViewedImagePaths([
+ read("first", "/repo/a.png", "inProgress"),
+ read("other", "/repo/b.png", "completed"),
+ read("again", "/repo/a.png", "completed"),
+ ]),
+ ).toEqual(["/repo/a.png", "/repo/b.png"]);
+ });
+});
diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts
index 6e5f320ebd0fa..6e3e7561c7f39 100644
--- a/packages/client-runtime/src/work-log/presentation.ts
+++ b/packages/client-runtime/src/work-log/presentation.ts
@@ -467,9 +467,13 @@ function computeToolGroupAction(entry: WorkLogPresentationEntry): ToolGroupActio
}
export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): string | null {
- if (entry.toolLifecycleStatus === "failed") {
- return null;
- }
+ // The file may not exist until the call runs, and an open row never retries a failed asset URL.
+ return entry.toolLifecycleStatus === "failed" || entry.toolLifecycleStatus === "inProgress"
+ ? null
+ : viewedImagePathOf(entry);
+}
+
+function viewedImagePathOf(entry: WorkLogPresentationEntry): string | null {
const viewedImagePath = entry.viewedImagePath?.trim();
if (
viewedImagePath !== undefined &&
@@ -491,7 +495,28 @@ export function workEntryViewedImagePath(entry: WorkLogPresentationEntry): strin
export function workEntriesViewedImagePaths(
entries: ReadonlyArray,
): string[] {
- return [...new Set(entries.flatMap((entry) => workEntryViewedImagePath(entry) ?? []))];
+ return workEntriesViewedImages(entries).flatMap(({ path, pending }) => (pending ? [] : path));
+}
+
+export interface ViewedImage {
+ readonly path: string;
+ /** Only running Reads opened it, so its file may not exist yet; show a placeholder, not a request. */
+ readonly pending: boolean;
+}
+
+/** {@link workEntriesViewedImagePaths}, plus the images a running Read is opening. */
+export function workEntriesViewedImages(
+ entries: ReadonlyArray,
+): ViewedImage[] {
+ const pendingByPath = new Map();
+ for (const entry of entries) {
+ if (entry.toolLifecycleStatus === "failed") continue;
+ const path = viewedImagePathOf(entry);
+ if (path === null) continue;
+ const pending = entry.toolLifecycleStatus === "inProgress";
+ pendingByPath.set(path, (pendingByPath.get(path) ?? true) && pending);
+ }
+ return [...pendingByPath].map(([path, pending]) => ({ path, pending }));
}
export interface ViewedImageAsset {
diff --git a/scripts/scenarios/pending-read-image-shows-loading-frame.e2e.ts b/scripts/scenarios/pending-read-image-shows-loading-frame.e2e.ts
new file mode 100644
index 0000000000000..0af219112beba
--- /dev/null
+++ b/scripts/scenarios/pending-read-image-shows-loading-frame.e2e.ts
@@ -0,0 +1,139 @@
+// @effect-diagnostics nodeBuiltinImport:off -- The scenario stages a local ACP executable.
+import * as NodeFSP from "node:fs/promises";
+import * as NodePath from "node:path";
+
+import { expect } from "e2e";
+import * as Effect from "effect/Effect";
+import * as Stream from "effect/Stream";
+
+import { T3_HOME } from "../e2e.config.ts";
+import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
+
+const REPLY = "The screenshot is a blue frame.";
+// A 320x180 blue PNG.
+const PNG =
+ "iVBORw0KGgoAAAANSUhEUgAAAUAAAAC0CAIAAABqhmJGAAABk0lEQVR42u3TAQkAAAzDsGm53fu8jusYBKKg0MweUCoSgIEBAwMGBgMDBgYMDBgYDAwYGDAwGBgwMGBgwMBgYMDAgIEBA4OBAQMDBgYDAwYGDAwYGAwMGBgwMGBgMDBgYMDAYGDAwICBAQODgQEDAwYGA6sABgYMDBgYDAwYGDAwYGAwMGBgwMBgYMDAgIEBA4OBAQMDBgYMDAYGDAwYGAwMGBgwMGBgMDBgYMDAgIHBwICBAQODgQEDAwYGDAwGBgwMGBgMDBgYMDBgYDAwYGDAwICBwcCAgQEDg4EBAwMGBgwMBgYMDBgYMDAYGDAwYGAwMGBgwMCAgcHAgIEBAwMGBgMDBgYMDAYGDAwYGDAwGBgwMGBgMDBgYMDAgIHBwICBAQMDBgYDAwYGDAwGBgwMGBgwMBgYMDBgYMDAYGDAwICBwcCAgQEDAwYGAwMGBgwMBlYBDAwYGDAwGBgwMGBgwMBgYMDAgIHBwICBAQMDBgYDAwYGDAwYGAwMGBgwMBgYMDBgYMDAYGDAwICBAQNDtwcYFke/eepCNQAAAABJRU5ErkJggg==";
+
+// Like an agent that takes a screenshot and reads it in one message: the Read starts before
+// the file exists, and the file appears while the Read is still running. The agent waits for
+// the test's go-ahead before writing the file and again before ending the turn, which folds the
+// strip away.
+const acp = (path: string, signals: string) => `
+import { existsSync, watch, writeFileSync } from "node:fs";
+import { createInterface } from "node:readline";
+
+const sessionId = "pending-read-image";
+const path = ${JSON.stringify(path)};
+const signals = ${JSON.stringify(signals)};
+const waitFor = (signal) =>
+ new Promise((resolve) => {
+ const watcher = watch(signals, (_event, name) => {
+ if (name !== signal) return;
+ watcher.close();
+ resolve();
+ });
+ if (existsSync(signals + "/" + signal)) {
+ watcher.close();
+ resolve();
+ }
+ });
+const send = (message) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\\n");
+const update = (value) => send({ method: "session/update", params: { sessionId, update: value } });
+for await (const line of createInterface({ input: process.stdin })) {
+ const { id, method } = JSON.parse(line);
+ if (id === undefined) continue;
+ if (method === "initialize") {
+ send({ id, result: { protocolVersion: 1, agentCapabilities: {}, authMethods: [] } });
+ } else if (method === "session/new") {
+ send({ id, result: { sessionId } });
+ } else if (method === "session/prompt") {
+ update({ sessionUpdate: "tool_call", toolCallId: "read", kind: "read", title: "Read", status: "in_progress", rawInput: { path } });
+ await waitFor("write-image");
+ writeFileSync(path, Buffer.from(${JSON.stringify(PNG)}, "base64"));
+ update({
+ sessionUpdate: "tool_call_update",
+ toolCallId: "read",
+ status: "completed",
+ content: [{ type: "content", content: { type: "text", text: "Read image" } }],
+ });
+ await waitFor("reply");
+ update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: ${JSON.stringify(REPLY)} } });
+ send({ id, result: { stopReason: "end_turn" } });
+ } else {
+ send({ id, error: { code: -32601, message: "Method not found" } });
+ }
+}
+`;
+
+test(
+ "An image a running Read is opening shows a loading frame, not Image unavailable, then the image",
+ WEB,
+ async ({ t3, app, screen, browser }) => {
+ const project = await t3.project("demo");
+ const script = NodePath.join(project, "pending-read-acp.mjs");
+ const settingsPath = NodePath.join(T3_HOME, "userdata/settings.json");
+ const originalSettings = await NodeFSP.readFile(settingsPath, "utf8");
+ const settings = JSON.parse(originalSettings);
+ const signals = await NodeFSP.mkdtemp(NodePath.join(T3_HOME, "pending-read-"));
+ await NodeFSP.writeFile(script, acp(NodePath.join(project, "later.png"), signals));
+ settings.providerInstances["pending-read-agent"] = {
+ driver: "acpRegistry",
+ displayName: "Pending read agent",
+ enabled: true,
+ config: { source: "local", commandPath: process.execPath, commandArgs: [script] },
+ };
+ try {
+ await NodeFSP.writeFile(settingsPath, JSON.stringify(settings));
+ // The settings watcher registers the agent asynchronously; start once the server lists it.
+ await runPromise(
+ Effect.gen(function* () {
+ const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
+ yield* client.subscribeServerConfig({}).pipe(
+ Stream.filter((event) =>
+ (event.type === "snapshot"
+ ? event.config.providers
+ : event.type === "providerStatuses"
+ ? event.payload.providers
+ : []
+ ).some((provider) => provider.instanceId === "pending-read-agent"),
+ ),
+ Stream.runHead,
+ );
+ }).pipe(Effect.scoped),
+ );
+ const { cli } = makeState(T3_HOME);
+ const started = await runPromise(
+ cli([
+ "thread",
+ "start",
+ project,
+ "Take a screenshot and look at it",
+ "--title",
+ "Pending read",
+ "--provider",
+ "pending-read-agent",
+ "--model",
+ "default",
+ "--json",
+ ]),
+ );
+ const { threadId } = JSON.parse(started.stdout) as { threadId: string };
+
+ await t3.open({ threadId });
+ await screen.getByText("Read demo/later.png", { exact: true }).waitFor({ timeout: 60_000 });
+ // The strip's frame shows either state; the bug is which one it is while the Read runs.
+ const frame = browser.locator('[data-image-gallery] :is([role="status"], [role="alert"])');
+ await frame.first().waitFor({ timeout: 10_000 });
+ await app.screenshot("while-reading");
+ await expect(frame).toHaveAttribute("aria-label", "Loading image");
+
+ await NodeFSP.writeFile(NodePath.join(signals, "write-image"), "");
+ await screen.getByRole("button", "Preview later.png").waitFor({ timeout: 30_000 });
+ await app.screenshot("after-read");
+ await NodeFSP.writeFile(NodePath.join(signals, "reply"), "");
+ await screen.getByText(REPLY, { exact: true }).waitFor({ timeout: 30_000 });
+ } finally {
+ await NodeFSP.writeFile(settingsPath, originalSettings);
+ }
+ },
+);
From 09385a33ce967cac83fbd1a3b4cba9fcfe688de3 Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 12:10:58 -0600
Subject: [PATCH 078/238] fix(shared): usage page says "record was skipped" for
one malformed record (#42974)
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 +-
apps/web/src/i18n/translations/de.json | 2 +-
apps/web/src/i18n/translations/en.json | 2 +-
apps/web/src/i18n/translations/es.json | 2 +-
apps/web/src/i18n/translations/fr.json | 2 +-
apps/web/src/i18n/translations/ja.json | 2 +-
apps/web/src/i18n/translations/ko.json | 2 +-
apps/web/src/i18n/translations/pt-BR.json | 2 +-
apps/web/src/i18n/translations/ru.json | 2 +-
apps/web/src/i18n/translations/sv.json | 2 +-
apps/web/src/i18n/translations/zh.json | 2 +-
packages/shared/src/usageFormat.test.ts | 12 ++++++++++++
packages/shared/src/usageFormatCopy.ts | 2 +-
22 files changed, 33 insertions(+), 21 deletions(-)
diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json
index 9efa66206a9cc..7cb5f2fc625ce 100644
--- a/apps/mobile/src/i18n/translations/de.json
+++ b/apps/mobile/src/i18n/translations/de.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "Datei gelesen",
"5ce648cd03020fd9": "{path} gelesen +{count} weitere",
"5d6c2898401c94e6": "{path} gelesen",
- "612170d804b03320": "{count, plural, one {{count} fehlerhafter oder inkonsistenter Nutzungseintrag wurde übersprungen; die Nutzung ist möglicherweise unvollständig.} other {{count} fehlerhafte oder inkonsistente Nutzungseinträge wurden übersprungen; die Nutzung ist möglicherweise unvollständig.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} fehlerhafter oder inkonsistenter Nutzungseintrag wurde übersprungen; die Nutzung ist möglicherweise unvollständig.} other {{count} fehlerhafte oder inkonsistente Nutzungseinträge wurden übersprungen; die Nutzung ist möglicherweise unvollständig.}}",
"ee448ceb6820ce2f": "{environment} verwendet eine ältere Serverversion und wird nicht in die Summen einbezogen.",
"732708950237004e": "Dieser Client ist älter als der Server auf {environment}; seine Nutzung wird nicht in die Summen einbezogen.",
"9758c2ede06aa19b": "heute {hour}",
diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json
index 223ace0c6dd48..04fd867277e19 100644
--- a/apps/mobile/src/i18n/translations/en.json
+++ b/apps/mobile/src/i18n/translations/en.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "Read file",
"5ce648cd03020fd9": "Read {path} +{count} more",
"5d6c2898401c94e6": "Read {path}",
- "612170d804b03320": "{count, plural, one {{count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.} other {{count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} malformed or inconsistent usage record was skipped; usage may be incomplete.} other {{count} malformed or inconsistent usage records were skipped; usage may be incomplete.}}",
"ee448ceb6820ce2f": "{environment} runs an older server version and is excluded from totals.",
"732708950237004e": "This client is older than the server on {environment}; its usage is excluded from totals.",
"9758c2ede06aa19b": "{hour} today",
diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json
index 26a58f6c58f64..6397909e086d0 100644
--- a/apps/mobile/src/i18n/translations/es.json
+++ b/apps/mobile/src/i18n/translations/es.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "Archivo leído",
"5ce648cd03020fd9": "Leyó {path} y {count} más",
"5d6c2898401c94e6": "Leyó {path}",
- "612170d804b03320": "{count, plural, one {Se omitió {count} registro de uso mal formado o incoherente; el uso puede estar incompleto.} other {Se omitieron {count} registros de uso mal formados o incoherentes; el uso puede estar incompleto.}}",
+ "69150fe436b3a0c2": "{count, plural, one {Se omitió {count} registro de uso mal formado o incoherente; el uso puede estar incompleto.} other {Se omitieron {count} registros de uso mal formados o incoherentes; el uso puede estar incompleto.}}",
"ee448ceb6820ce2f": "{environment} ejecuta una versión anterior del servidor y se excluye de los totales.",
"732708950237004e": "Este cliente es más antiguo que el servidor de {environment}; su uso se excluye de los totales.",
"9758c2ede06aa19b": "Hoy a las {hour}",
diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json
index bf46c964394e1..149061977f2ba 100644
--- a/apps/mobile/src/i18n/translations/fr.json
+++ b/apps/mobile/src/i18n/translations/fr.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "Fichier lu",
"5ce648cd03020fd9": "Lecture de {path} +{count} autres",
"5d6c2898401c94e6": "Lecture de {path}",
- "612170d804b03320": "{count, plural, one {{count} enregistrement d’utilisation mal formé ou incohérent a été ignoré ; l’utilisation peut être incomplète.} other {{count} enregistrements d’utilisation mal formés ou incohérents ont été ignorés ; l’utilisation peut être incomplète.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} enregistrement d’utilisation mal formé ou incohérent a été ignoré ; l’utilisation peut être incomplète.} other {{count} enregistrements d’utilisation mal formés ou incohérents ont été ignorés ; l’utilisation peut être incomplète.}}",
"ee448ceb6820ce2f": "{environment} utilise une ancienne version du serveur et est exclu des totaux.",
"732708950237004e": "Ce client est plus ancien que le serveur de {environment} ; son utilisation est exclue des totaux.",
"9758c2ede06aa19b": "{hour} aujourd’hui",
diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json
index 480c4e959f147..416f65e6307ef 100644
--- a/apps/mobile/src/i18n/translations/ja.json
+++ b/apps/mobile/src/i18n/translations/ja.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "ファイルを読み取りました",
"5ce648cd03020fd9": "{path} と他 {count} 件を読み取りました",
"5d6c2898401c94e6": "{path} を読み取りました",
- "612170d804b03320": "{count, plural, other {不正または不整合な使用量レコード {count} 件をスキップしました。使用量が不完全な可能性があります。}}",
+ "69150fe436b3a0c2": "{count, plural, other {不正または不整合な使用量レコード {count} 件をスキップしました。使用量が不完全な可能性があります。}}",
"ee448ceb6820ce2f": "{environment} は古いバージョンのサーバーを実行しているため、合計から除外されています。",
"732708950237004e": "このクライアントは {environment} のサーバーより古いため、その使用量は合計から除外されています。",
"9758c2ede06aa19b": "今日 {hour}",
diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json
index 34fe2af053545..4ba4ae039be88 100644
--- a/apps/mobile/src/i18n/translations/ko.json
+++ b/apps/mobile/src/i18n/translations/ko.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "파일 읽음",
"5ce648cd03020fd9": "{path} 읽음 외 {count}개",
"5d6c2898401c94e6": "{path} 읽음",
- "612170d804b03320": "{count, plural, other {형식이 잘못되었거나 일관되지 않은 사용량 기록 {count}개를 건너뛰었습니다. 사용량이 불완전할 수 있습니다.}}",
+ "69150fe436b3a0c2": "{count, plural, other {형식이 잘못되었거나 일관되지 않은 사용량 기록 {count}개를 건너뛰었습니다. 사용량이 불완전할 수 있습니다.}}",
"ee448ceb6820ce2f": "{environment}은(는) 이전 서버 버전을 실행 중이어서 합계에서 제외됩니다.",
"732708950237004e": "이 클라이언트가 {environment}의 서버보다 오래되어 해당 사용량은 합계에서 제외됩니다.",
"9758c2ede06aa19b": "오늘 {hour}",
diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json
index 72870adc6d774..cbd3a8957a2ed 100644
--- a/apps/mobile/src/i18n/translations/pt-BR.json
+++ b/apps/mobile/src/i18n/translations/pt-BR.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "Leu o arquivo",
"5ce648cd03020fd9": "Leu {path} e mais {count}",
"5d6c2898401c94e6": "Leu {path}",
- "612170d804b03320": "{count, plural, one {{count} registro de uso malformado ou inconsistente foi ignorado; o uso pode estar incompleto.} other {{count} registros de uso malformados ou inconsistentes foram ignorados; o uso pode estar incompleto.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} registro de uso malformado ou inconsistente foi ignorado; o uso pode estar incompleto.} other {{count} registros de uso malformados ou inconsistentes foram ignorados; o uso pode estar incompleto.}}",
"ee448ceb6820ce2f": "{environment} roda uma versão mais antiga do servidor e fica fora dos totais.",
"732708950237004e": "Este cliente é mais antigo que o servidor em {environment}; o uso dele fica fora dos totais.",
"9758c2ede06aa19b": "Hoje às {hour}",
diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json
index 7a48ee5eafdd1..f9f254560865a 100644
--- a/apps/mobile/src/i18n/translations/ru.json
+++ b/apps/mobile/src/i18n/translations/ru.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "Прочитан файл",
"5ce648cd03020fd9": "Прочитан {path} и ещё {count}",
"5d6c2898401c94e6": "Прочитан {path}",
- "612170d804b03320": "{count, plural, one {Пропущена {count} повреждённая или несогласованная запись об использовании; данные могут быть неполными.} few {Пропущено {count} повреждённые или несогласованные записи об использовании; данные могут быть неполными.} many {Пропущено {count} повреждённых или несогласованных записей об использовании; данные могут быть неполными.} other {Пропущено {count} повреждённой или несогласованной записи об использовании; данные могут быть неполными.}}",
+ "69150fe436b3a0c2": "{count, plural, one {Пропущена {count} повреждённая или несогласованная запись об использовании; данные могут быть неполными.} few {Пропущено {count} повреждённые или несогласованные записи об использовании; данные могут быть неполными.} many {Пропущено {count} повреждённых или несогласованных записей об использовании; данные могут быть неполными.} other {Пропущено {count} повреждённой или несогласованной записи об использовании; данные могут быть неполными.}}",
"ee448ceb6820ce2f": "{environment} использует старую версию сервера и не учитывается в итогах.",
"732708950237004e": "Этот клиент старее сервера на {environment}; его использование не учитывается в итогах.",
"9758c2ede06aa19b": "{hour} сегодня",
diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json
index a79f24906759e..f62c445602d56 100644
--- a/apps/mobile/src/i18n/translations/sv.json
+++ b/apps/mobile/src/i18n/translations/sv.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "Läste fil",
"5ce648cd03020fd9": "Läste {path} +{count} till",
"5d6c2898401c94e6": "Läste {path}",
- "612170d804b03320": "{count, plural, one {{count} felaktig eller inkonsekvent användningspost hoppades över; användningen kan vara ofullständig.} other {{count} felaktiga eller inkonsekventa användningsposter hoppades över; användningen kan vara ofullständig.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} felaktig eller inkonsekvent användningspost hoppades över; användningen kan vara ofullständig.} other {{count} felaktiga eller inkonsekventa användningsposter hoppades över; användningen kan vara ofullständig.}}",
"ee448ceb6820ce2f": "{environment} kör en äldre serverversion och räknas inte med i totalerna.",
"732708950237004e": "Den här klienten är äldre än servern på {environment}; dess användning räknas inte med i totalerna.",
"9758c2ede06aa19b": "{hour} i dag",
diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json
index 58c5f8b4e70cd..64c79639eface 100644
--- a/apps/mobile/src/i18n/translations/zh.json
+++ b/apps/mobile/src/i18n/translations/zh.json
@@ -1298,7 +1298,7 @@
"c13753167634f7aa": "已读取文件",
"5ce648cd03020fd9": "已读取 {path},另有 {count} 个",
"5d6c2898401c94e6": "已读取 {path}",
- "612170d804b03320": "{count, plural, other {已跳过 {count} 条格式错误或不一致的用量记录;用量可能不完整。}}",
+ "69150fe436b3a0c2": "{count, plural, other {已跳过 {count} 条格式错误或不一致的用量记录;用量可能不完整。}}",
"ee448ceb6820ce2f": "{environment} 上运行的服务器版本较旧,未计入总计。",
"732708950237004e": "此客户端比 {environment} 上的服务器版本旧,其用量未计入总计。",
"9758c2ede06aa19b": "今天 {hour}",
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json
index 6372943aad165..1d0ed2484b1b9 100644
--- a/apps/web/src/i18n/translations/de.json
+++ b/apps/web/src/i18n/translations/de.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "Datei gelesen",
"5ce648cd03020fd9": "{path} gelesen +{count} weitere",
"5d6c2898401c94e6": "{path} gelesen",
- "612170d804b03320": "{count, plural, one {{count} fehlerhafter oder inkonsistenter Nutzungseintrag wurde übersprungen; die Nutzung ist möglicherweise unvollständig.} other {{count} fehlerhafte oder inkonsistente Nutzungseinträge wurden übersprungen; die Nutzung ist möglicherweise unvollständig.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} fehlerhafter oder inkonsistenter Nutzungseintrag wurde übersprungen; die Nutzung ist möglicherweise unvollständig.} other {{count} fehlerhafte oder inkonsistente Nutzungseinträge wurden übersprungen; die Nutzung ist möglicherweise unvollständig.}}",
"ee448ceb6820ce2f": "{environment} verwendet eine ältere Serverversion und wird nicht in die Summen einbezogen.",
"732708950237004e": "Dieser Client ist älter als der Server auf {environment}; seine Nutzung wird nicht in die Summen einbezogen.",
"9758c2ede06aa19b": "heute {hour}",
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index 0de8e0ffcbba7..8ea2b46f82d17 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "Read file",
"5ce648cd03020fd9": "Read {path} +{count} more",
"5d6c2898401c94e6": "Read {path}",
- "612170d804b03320": "{count, plural, one {{count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.} other {{count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} malformed or inconsistent usage record was skipped; usage may be incomplete.} other {{count} malformed or inconsistent usage records were skipped; usage may be incomplete.}}",
"ee448ceb6820ce2f": "{environment} runs an older server version and is excluded from totals.",
"732708950237004e": "This client is older than the server on {environment}; its usage is excluded from totals.",
"9758c2ede06aa19b": "{hour} today",
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index 79f4a2bc3e13f..899b049a8734c 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "Archivo leído",
"5ce648cd03020fd9": "Leyó {path} y {count} más",
"5d6c2898401c94e6": "Leyó {path}",
- "612170d804b03320": "{count, plural, one {Se omitió {count} registro de uso mal formado o incoherente; el uso puede estar incompleto.} other {Se omitieron {count} registros de uso mal formados o incoherentes; el uso puede estar incompleto.}}",
+ "69150fe436b3a0c2": "{count, plural, one {Se omitió {count} registro de uso mal formado o incoherente; el uso puede estar incompleto.} other {Se omitieron {count} registros de uso mal formados o incoherentes; el uso puede estar incompleto.}}",
"ee448ceb6820ce2f": "{environment} ejecuta una versión anterior del servidor y se excluye de los totales.",
"732708950237004e": "Este cliente es más antiguo que el servidor de {environment}; su uso se excluye de los totales.",
"9758c2ede06aa19b": "Hoy a las {hour}",
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index 6bdf8c12b6630..eda27f8ff3270 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "Fichier lu",
"5ce648cd03020fd9": "Lecture de {path} +{count} autres",
"5d6c2898401c94e6": "Lecture de {path}",
- "612170d804b03320": "{count, plural, one {{count} enregistrement d’utilisation mal formé ou incohérent a été ignoré ; l’utilisation peut être incomplète.} other {{count} enregistrements d’utilisation mal formés ou incohérents ont été ignorés ; l’utilisation peut être incomplète.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} enregistrement d’utilisation mal formé ou incohérent a été ignoré ; l’utilisation peut être incomplète.} other {{count} enregistrements d’utilisation mal formés ou incohérents ont été ignorés ; l’utilisation peut être incomplète.}}",
"ee448ceb6820ce2f": "{environment} utilise une ancienne version du serveur et est exclu des totaux.",
"732708950237004e": "Ce client est plus ancien que le serveur de {environment} ; son utilisation est exclue des totaux.",
"9758c2ede06aa19b": "{hour} aujourd’hui",
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index f82bb265fc1d6..994329ba6a5be 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "ファイルを読み取りました",
"5ce648cd03020fd9": "{path} と他 {count} 件を読み取りました",
"5d6c2898401c94e6": "{path} を読み取りました",
- "612170d804b03320": "{count, plural, other {不正または不整合な使用量レコード {count} 件をスキップしました。使用量が不完全な可能性があります。}}",
+ "69150fe436b3a0c2": "{count, plural, other {不正または不整合な使用量レコード {count} 件をスキップしました。使用量が不完全な可能性があります。}}",
"ee448ceb6820ce2f": "{environment} は古いバージョンのサーバーを実行しているため、合計から除外されています。",
"732708950237004e": "このクライアントは {environment} のサーバーより古いため、その使用量は合計から除外されています。",
"9758c2ede06aa19b": "今日 {hour}",
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index 868ee5709c7b9..38c24fd5de248 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "파일 읽음",
"5ce648cd03020fd9": "{path} 읽음 외 {count}개",
"5d6c2898401c94e6": "{path} 읽음",
- "612170d804b03320": "{count, plural, other {형식이 잘못되었거나 일관되지 않은 사용량 기록 {count}개를 건너뛰었습니다. 사용량이 불완전할 수 있습니다.}}",
+ "69150fe436b3a0c2": "{count, plural, other {형식이 잘못되었거나 일관되지 않은 사용량 기록 {count}개를 건너뛰었습니다. 사용량이 불완전할 수 있습니다.}}",
"ee448ceb6820ce2f": "{environment}은(는) 이전 서버 버전을 실행 중이어서 합계에서 제외됩니다.",
"732708950237004e": "이 클라이언트가 {environment}의 서버보다 오래되어 해당 사용량은 합계에서 제외됩니다.",
"9758c2ede06aa19b": "오늘 {hour}",
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index 716a2901b4081..4eb5563c27e76 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "Leu o arquivo",
"5ce648cd03020fd9": "Leu {path} e mais {count}",
"5d6c2898401c94e6": "Leu {path}",
- "612170d804b03320": "{count, plural, one {{count} registro de uso malformado ou inconsistente foi ignorado; o uso pode estar incompleto.} other {{count} registros de uso malformados ou inconsistentes foram ignorados; o uso pode estar incompleto.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} registro de uso malformado ou inconsistente foi ignorado; o uso pode estar incompleto.} other {{count} registros de uso malformados ou inconsistentes foram ignorados; o uso pode estar incompleto.}}",
"ee448ceb6820ce2f": "{environment} roda uma versão mais antiga do servidor e fica fora dos totais.",
"732708950237004e": "Este cliente é mais antigo que o servidor em {environment}; o uso dele fica fora dos totais.",
"9758c2ede06aa19b": "Hoje às {hour}",
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index af80a928e9382..d05fa22ef00a0 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "Прочитан файл",
"5ce648cd03020fd9": "Прочитан {path} и ещё {count}",
"5d6c2898401c94e6": "Прочитан {path}",
- "612170d804b03320": "{count, plural, one {Пропущена {count} повреждённая или несогласованная запись об использовании; данные могут быть неполными.} few {Пропущено {count} повреждённые или несогласованные записи об использовании; данные могут быть неполными.} many {Пропущено {count} повреждённых или несогласованных записей об использовании; данные могут быть неполными.} other {Пропущено {count} повреждённой или несогласованной записи об использовании; данные могут быть неполными.}}",
+ "69150fe436b3a0c2": "{count, plural, one {Пропущена {count} повреждённая или несогласованная запись об использовании; данные могут быть неполными.} few {Пропущено {count} повреждённые или несогласованные записи об использовании; данные могут быть неполными.} many {Пропущено {count} повреждённых или несогласованных записей об использовании; данные могут быть неполными.} other {Пропущено {count} повреждённой или несогласованной записи об использовании; данные могут быть неполными.}}",
"ee448ceb6820ce2f": "{environment} использует старую версию сервера и не учитывается в итогах.",
"732708950237004e": "Этот клиент старее сервера на {environment}; его использование не учитывается в итогах.",
"9758c2ede06aa19b": "{hour} сегодня",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index 8fbbc80a44485..b75c3b8d950c8 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "Läste fil",
"5ce648cd03020fd9": "Läste {path} +{count} till",
"5d6c2898401c94e6": "Läste {path}",
- "612170d804b03320": "{count, plural, one {{count} felaktig eller inkonsekvent användningspost hoppades över; användningen kan vara ofullständig.} other {{count} felaktiga eller inkonsekventa användningsposter hoppades över; användningen kan vara ofullständig.}}",
+ "69150fe436b3a0c2": "{count, plural, one {{count} felaktig eller inkonsekvent användningspost hoppades över; användningen kan vara ofullständig.} other {{count} felaktiga eller inkonsekventa användningsposter hoppades över; användningen kan vara ofullständig.}}",
"ee448ceb6820ce2f": "{environment} kör en äldre serverversion och räknas inte med i totalerna.",
"732708950237004e": "Den här klienten är äldre än servern på {environment}; dess användning räknas inte med i totalerna.",
"9758c2ede06aa19b": "{hour} i dag",
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index 26db796ccfe17..2872d36584f71 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -1297,7 +1297,7 @@
"c13753167634f7aa": "已读取文件",
"5ce648cd03020fd9": "已读取 {path},另有 {count} 个",
"5d6c2898401c94e6": "已读取 {path}",
- "612170d804b03320": "{count, plural, other {已跳过 {count} 条格式错误或不一致的用量记录;用量可能不完整。}}",
+ "69150fe436b3a0c2": "{count, plural, other {已跳过 {count} 条格式错误或不一致的用量记录;用量可能不完整。}}",
"ee448ceb6820ce2f": "{environment} 上运行的服务器版本较旧,未计入总计。",
"732708950237004e": "此客户端比 {environment} 上的服务器版本旧,其用量未计入总计。",
"9758c2ede06aa19b": "今天 {hour}",
diff --git a/packages/shared/src/usageFormat.test.ts b/packages/shared/src/usageFormat.test.ts
index a40190312e510..7b90f48f3d697 100644
--- a/packages/shared/src/usageFormat.test.ts
+++ b/packages/shared/src/usageFormat.test.ts
@@ -9,6 +9,7 @@ import {
makeWindow,
usageSourceMessages,
} from "./usageFormat.ts";
+import { usageSourceMessages as localizedUsageSourceMessages } from "./usageFormatCopy.ts";
function malformedSource(count: number, overrides: Partial = {}): UsageSource {
return {
@@ -199,3 +200,14 @@ describe("token formatting", () => {
expect(formatTokens(-999_999)).toBe("-1M");
});
});
+
+describe("localized usage source messages", () => {
+ it("uses singular and plural copy for skipped malformed records", () => {
+ expect(localizedUsageSourceMessages([malformedSource(1)])).toEqual([
+ "1 malformed or inconsistent usage record was skipped; usage may be incomplete.",
+ ]);
+ expect(localizedUsageSourceMessages([malformedSource(2)])).toEqual([
+ "2 malformed or inconsistent usage records were skipped; usage may be incomplete.",
+ ]);
+ });
+});
diff --git a/packages/shared/src/usageFormatCopy.ts b/packages/shared/src/usageFormatCopy.ts
index 1a1a041aabe25..7a1508cc61ae4 100644
--- a/packages/shared/src/usageFormatCopy.ts
+++ b/packages/shared/src/usageFormatCopy.ts
@@ -16,7 +16,7 @@ export function usageSourceMessages(
return usageSourceMessagesWith(sources, (count) =>
resolve(
msg(
- "{count, plural, one {{count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.} other {{count} malformed or inconsistent usage record(s) were skipped; usage may be incomplete.}}",
+ "{count, plural, one {{count} malformed or inconsistent usage record was skipped; usage may be incomplete.} other {{count} malformed or inconsistent usage records were skipped; usage may be incomplete.}}",
{ count },
),
),
From 03c0b313156192c1cc239fce1a2cd4c20bcea28b Mon Sep 17 00:00:00 2001
From: Simone
Date: Wed, 25 Nov 2026 19:11:13 +0100
Subject: [PATCH 079/238] fix(antigravity): keep child skills visible under a
root SKILL.md (#42971)
Co-authored-by: Simone <185146821+Lucenx9@users.noreply.github.com>
Co-authored-by: Julius Marminge
---
.../Drivers/AntigravitySkills.test.ts | 24 ++++++++++++-------
.../src/provider/Drivers/AntigravitySkills.ts | 3 ++-
2 files changed, 17 insertions(+), 10 deletions(-)
diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts
index 908d66beae4b6..3e93dc601efd1 100644
--- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts
+++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts
@@ -152,21 +152,27 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => {
}),
);
- it.effect("loads a root skill without scanning its children", () =>
+ it.effect("keeps child skills visible under a project root SKILL.md", () =>
Effect.gen(function* () {
- const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const input = yield* makeWorkspace();
- const root = path.join(input.cwd, ".agents", "skills");
- const skillPath = yield* writeSkill(root, "---\nname: root-skill\n---\n");
- yield* writeSkill(path.join(root, "child"), "---\nname: child-skill\n---\n");
+ const agentsRoot = path.join(input.cwd, ".agents", "skills");
+ const legacyRoot = path.join(input.cwd, ".agent", "skills");
+ yield* writeSkill(agentsRoot, "---\nname: root-skill\n---\n");
+ yield* writeSkill(legacyRoot, "---\nname: legacy-root-skill\n---\n");
+ const child = yield* writeSkill(
+ path.join(agentsRoot, "child"),
+ "---\nname: child-skill\n---\n",
+ );
+ const legacyChild = yield* writeSkill(
+ path.join(legacyRoot, "child"),
+ "---\nname: legacy-child-skill\n---\n",
+ );
assert.deepEqual(yield* discoverAntigravitySkills(input), [
- { name: "root-skill", path: skillPath, scope: "project", enabled: true },
+ { name: "child-skill", path: child, scope: "project", enabled: true },
+ { name: "legacy-child-skill", path: legacyChild, scope: "project", enabled: true },
]);
-
- yield* fileSystem.writeFileString(skillPath, "---\nname: [invalid\n---\n");
- assert.deepEqual(yield* discoverAntigravitySkills(input), []);
}),
);
diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts
index 84332d95f2278..a281cd691de67 100644
--- a/apps/server/src/provider/Drivers/AntigravitySkills.ts
+++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts
@@ -310,7 +310,8 @@ export const discoverAntigravitySkills = Effect.fn("discoverAntigravitySkills")(
const sortedEntries = entries.toSorted();
const skillFileName = sortedEntries.find((entry) => entry.toLowerCase() === "skill.md");
- if (skillFileName !== undefined && (mode !== "agent-root" || skillFileName.endsWith(".md"))) {
+ // agy treats the automatic .agent(s)/skills roots as collections.
+ if (skillFileName !== undefined && mode !== "agent-root") {
if (matchesSkillFilter(path.basename(directory), filter)) {
yield* addSkillFile(path.join(directory, skillFileName), scope, pluginName);
}
From 60eed627d03da74a4cdbcca6798cc0b44d8575f7 Mon Sep 17 00:00:00 2001
From: AymanKhan9
Date: Wed, 25 Nov 2026 23:42:33 +0530
Subject: [PATCH 080/238] fix(web): PR timeline "Open activity on host" buttons
honor 'Open links in' (#42914)
Co-authored-by: Julius Marminge
---
.../PullRequestTimelineTab.browser.test.tsx | 75 +++++++++++++++++++
.../pullRequest/PullRequestTimelineTab.tsx | 24 +++---
2 files changed, 90 insertions(+), 9 deletions(-)
diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.browser.test.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.browser.test.tsx
index 531e3bc86f4eb..858d89453fec6 100644
--- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.browser.test.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.browser.test.tsx
@@ -2,11 +2,23 @@ import {
EnvironmentId,
ProjectId,
SourceControlProviderKind,
+ ThreadId,
type PullRequestDetailView,
} from "@t3tools/contracts";
import { expect, it, vi } from "vite-plus/test";
import { userEvent } from "vite-plus/test/browser";
+const linkState = vi.hoisted(() => ({
+ openLink: vi.fn(async () => {}),
+ useOpenLink: vi.fn(),
+}));
+vi.mock(import("~/browser/useOpenLink"), () => ({
+ useOpenLink: (threadRef: unknown) => {
+ linkState.useOpenLink(threadRef);
+ return linkState.openLink;
+ },
+}));
+
import { render } from "../../../test/render";
import "../../index.css";
import { PullRequestTimelineTab } from "./PullRequestTimelineTab";
@@ -221,3 +233,66 @@ it("gives each comment and review a heading for screen reader navigation", async
await expect.element(screen.getByText("One question", { exact: true })).toBeVisible();
await expect.element(screen.getByRole("heading", { name: /alice commented/ })).toBeVisible();
});
+
+it("opens activity host links through the link-target setting", async () => {
+ linkState.openLink.mockClear();
+ linkState.useOpenLink.mockClear();
+ const reviewUrl = `${detail.url}#pullrequestreview-1`;
+ const commentUrl = `${detail.url}#issuecomment-2`;
+ const threadRef = {
+ environmentId: EnvironmentId.make("environment"),
+ threadId: ThreadId.make("thread-1"),
+ };
+ const commented: PullRequestDetailView = {
+ ...detail,
+ commits: [],
+ comments: [
+ {
+ id: "review",
+ kind: "review",
+ author: { login: "bob", name: null, avatarUrl: null },
+ body: "Looks good",
+ createdAt: "2026-10-01T00:00:00Z",
+ url: reviewUrl,
+ path: null,
+ reviewState: "APPROVED",
+ },
+ {
+ id: "comment",
+ kind: "issue-comment",
+ author: { login: "alice", name: null, avatarUrl: null },
+ body: "One question",
+ createdAt: "2026-10-01T00:01:00Z",
+ url: commentUrl,
+ path: null,
+ reviewState: null,
+ },
+ ],
+ };
+ await using screen = await render(
+
+
{}}
+ detail={commented}
+ environmentId={threadRef.environmentId}
+ threadRef={threadRef}
+ reference={detail}
+ order="oldest"
+ onOpenCommit={() => {}}
+ onRefresh={() => {}}
+ />
+ ,
+ );
+ await userEvent.click(screen.getByRole("button", { name: "Open activity on host" }));
+ expect(linkState.useOpenLink).toHaveBeenCalledWith(threadRef);
+ expect(linkState.openLink).toHaveBeenLastCalledWith(reviewUrl, {
+ event: expect.objectContaining({ metaKey: false, ctrlKey: false }),
+ });
+
+ await userEvent.click(screen.getByRole("button", { name: /1 comment/ }));
+ const buttons = screen.getByRole("button", { name: "Open activity on host" }).all();
+ await userEvent.click(buttons[1]!);
+ expect(linkState.openLink).toHaveBeenLastCalledWith(commentUrl, {
+ event: expect.objectContaining({ metaKey: false, ctrlKey: false }),
+ });
+});
diff --git a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
index 1853489d1d7bb..e282676792a9b 100644
--- a/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
+++ b/apps/web/src/components/pullRequest/PullRequestTimelineTab.tsx
@@ -28,8 +28,8 @@ import { msg, T, useGT, useMessages, Var } from "gt-react";
import { m } from "~/i18n/messages";
import { useEffect, useEffectEvent, useRef, useState, type ReactNode } from "react";
+import { useOpenLink } from "~/browser/useOpenLink";
import { cn } from "~/lib/utils";
-import { readLocalApi } from "~/localApi";
import { pullRequestEnvironment } from "~/state/pullRequests";
import { RelativeTime } from "~/components/RelativeTime";
@@ -219,7 +219,12 @@ function AddToChatButton({
);
}
-function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: (url: string) => void }) {
+type OpenOnHost = (
+ url: string,
+ event: { readonly metaKey: boolean; readonly ctrlKey: boolean; readonly button?: number },
+) => void;
+
+function OpenOnHostButton({ url, onOpen }: { url: string | null; onOpen: OpenOnHost }) {
const gt = useGT();
return url === null ? null : (
onOpen(url)}
+ onClick={(event) => onOpen(url, event)}
>
@@ -247,7 +252,7 @@ function ConversationCard({
event: PullRequestTimelineEvent;
editable: PullRequestComment | null;
cwd: string;
- onOpen: (url: string) => void;
+ onOpen: OpenOnHost;
reactions: ReactionSurface;
showPath?: boolean;
/** A reply goes with its conversation, from the card that heads it. */
@@ -402,7 +407,7 @@ function ConversationGroup({
events: ReadonlyArray;
editable: ReadonlyMap;
cwd: string;
- onOpen: (url: string) => void;
+ onOpen: OpenOnHost;
reactions: ReactionSurface;
}) {
const [open, setOpen] = useState(
@@ -493,7 +498,7 @@ function ReviewThreadEvent({
detail: PullRequestDetailView;
editable: ReadonlyMap;
cwd: string;
- onOpen: (url: string) => void;
+ onOpen: OpenOnHost;
reactions: ReactionSurface;
}) {
const gt = useGT();
@@ -734,7 +739,7 @@ function ReviewVerdictEvent({
outcome: PullRequestReviewOutcome;
stale: boolean;
cwd: string;
- onOpen: (url: string) => void;
+ onOpen: OpenOnHost;
reactions: ReactionSurface;
}) {
const gt = useGT();
@@ -911,8 +916,9 @@ export function PullRequestTimelineTab({
}, [revealUrl, targetIndex]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the hold observes DOM outside React and must end with the tab
useEffect(() => () => stopHolding.current?.(), []);
- const openOnHost = (url: string) => {
- void readLocalApi()?.shell.openExternal(url);
+ const openLink = useOpenLink(threadRef);
+ const openOnHost: OpenOnHost = (url, event) => {
+ void openLink(url, { event }).catch(console.error);
};
const rowKey = (row: PullRequestTimelineRow) => {
From 9ea5044aef27b0b710857d8d1dc13240392cafc6 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 10:32:55 -0800
Subject: [PATCH 081/238] fix(server): images on drives Windows' native
realpath cannot resolve preview again (#42981)
---
apps/server/src/assets/AssetAccess.test.ts | 36 ++++++++++++++++++++++
apps/server/src/assets/AssetAccess.ts | 14 ++++++---
apps/server/src/assets/MediaFile.ts | 4 +++
3 files changed, 50 insertions(+), 4 deletions(-)
diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts
index e70be7cb9f1fc..8e92ff0fd427b 100644
--- a/apps/server/src/assets/AssetAccess.test.ts
+++ b/apps/server/src/assets/AssetAccess.test.ts
@@ -710,6 +710,42 @@ describe("AssetAccess", () => {
}).pipe(Effect.provide(layerTest)),
);
+ // Windows' native realpath fails with ENOENT on some removable drives (an exFAT USB
+ // drive) whose files Node can still stat, open and resolve with the JS realpath.
+ it.effect("previews a readable media file when the native realpath cannot resolve it", () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const directory = yield* fs.realPath(
+ yield* fs.makeTempDirectoryScoped({ prefix: "t3-media-no-native-realpath-" }),
+ );
+ const filePath = path.join(directory, "preview-test.jpg");
+ yield* fs.writeFileString(filePath, "media");
+ const nativeRealPathFails = FileSystem.FileSystem.of({
+ ...fs,
+ realPath: (requestedPath) =>
+ Effect.fail(
+ PlatformError.systemError({
+ _tag: "NotFound",
+ module: "FileSystem",
+ method: "realPath",
+ pathOrDescriptor: requestedPath,
+ }),
+ ),
+ });
+ const result = yield* issueAssetUrl({
+ resource: { _tag: "media-file", threadId: ThreadId.make("thread-1"), path: filePath },
+ }).pipe(Effect.provideService(FileSystem.FileSystem, nativeRealPathFails));
+ const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
+ const separator = suffix.indexOf("/");
+ expect(
+ yield* resolveAsset(suffix.slice(0, separator), suffix.slice(separator + 1)).pipe(
+ Effect.provideService(FileSystem.FileSystem, nativeRealPathFails),
+ ),
+ ).toMatchObject({ kind: "file", path: filePath });
+ }).pipe(Effect.provide(layerTest)),
+ );
+
it.effect.skipIf(!symlinksSupported)(
"rejects non-previewable files, disguised targets, and directories",
() =>
diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts
index d91975114e6eb..5ea5b3bd770b4 100644
--- a/apps/server/src/assets/AssetAccess.ts
+++ b/apps/server/src/assets/AssetAccess.ts
@@ -67,6 +67,7 @@ import {
mediaFileRevision,
openMediaFile,
readMediaFileHeader,
+ realPathWithoutNativeResolver,
type OpenMediaFile,
} from "./MediaFile.ts";
import * as WorkspacePreviewRevisions from "./WorkspacePreviewRevisions.ts";
@@ -309,15 +310,20 @@ const resolveCanonicalFile = Effect.fn("AssetAccess.resolveCanonicalFile")(funct
filePath: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
- const canonicalFile = yield* ProjectFaviconResolver.optionOnNotFound(
+ const nativeCanonicalFile = yield* ProjectFaviconResolver.optionOnNotFound(
fileSystem.realPath(filePath),
);
- if (Option.isNone(canonicalFile)) return null;
+ // Windows' native realpath returns ENOENT on drives without a mount-manager name
+ // (some USB and RAM-disk drivers) although the file is readable.
+ const canonicalFile = Option.isSome(nativeCanonicalFile)
+ ? nativeCanonicalFile.value
+ : yield* realPathWithoutNativeResolver(filePath);
+ if (canonicalFile === null) return null;
- const info = yield* ProjectFaviconResolver.optionOnNotFound(fileSystem.stat(canonicalFile.value));
+ const info = yield* ProjectFaviconResolver.optionOnNotFound(fileSystem.stat(canonicalFile));
if (Option.isNone(info) || info.value.type !== "File") return null;
const isServerInternalPath = yield* makeIsServerInternalPath;
- return (yield* isServerInternalPath(canonicalFile.value)) ? null : canonicalFile.value;
+ return (yield* isServerInternalPath(canonicalFile)) ? null : canonicalFile;
});
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
diff --git a/apps/server/src/assets/MediaFile.ts b/apps/server/src/assets/MediaFile.ts
index 6cd83a797fb71..2451535b14c95 100644
--- a/apps/server/src/assets/MediaFile.ts
+++ b/apps/server/src/assets/MediaFile.ts
@@ -44,6 +44,10 @@ const realpathLikeFileSystem = (filePath: string) =>
NodeFS.realpath(filePath, (error, resolved) => (error ? reject(error) : resolve(resolved)));
});
+/** Null when the path cannot be resolved. */
+export const realPathWithoutNativeResolver = (filePath: string) =>
+ Effect.promise(() => realpathLikeFileSystem(filePath).catch(() => null));
+
export const openMediaFile = Effect.fn("openMediaFile")(function* (
filePath: string,
identity?: { readonly device: string; readonly inode: string },
From 0180628cf75eb9cd8ed371f7200d84c6f18f574a Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 10:44:09 -0800
Subject: [PATCH 082/238] fix(server): login-shell re-reads no longer pile up
fnm multishell folders in PATH (#42996)
---
apps/server/src/os-jank.test.ts | 52 ++++++++++++++++++++++++++++++++-
apps/server/src/os-jank.ts | 28 ++++++++++++++++--
2 files changed, 77 insertions(+), 3 deletions(-)
diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts
index 46b3b6b1e9936..bfae12674f2e1 100644
--- a/apps/server/src/os-jank.test.ts
+++ b/apps/server/src/os-jank.test.ts
@@ -5,10 +5,19 @@ import { CommandAvailability, WindowsShellEnvironment } from "@t3tools/shared/sh
import * as Effect from "effect/Effect";
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Observe the existing synchronous shell probe without launching the user's login shell.
import * as NodeChildProcess from "node:child_process";
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fake login shell is a script the real probe spawns.
+import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fake login shell is a script the real probe spawns.
+import * as NodePath from "node:path";
import { assert, it, vi } from "vite-plus/test";
-import { fixPath, hydratePosixHome, refreshWindowsPath } from "./os-jank.ts";
+import {
+ fixPath,
+ hydratePosixHome,
+ refreshPathFromLoginShell,
+ refreshWindowsPath,
+} from "./os-jank.ts";
vi.mock("node:child_process", { spy: true });
@@ -197,6 +206,47 @@ effectIt.effect(
),
);
+// Like a profile running `eval "$(fnm env)"`: each login shell gets a new multishell folder.
+const fnmLoginShell = (dir: string) => {
+ const shell = NodePath.join(dir, "bash");
+ NodeFS.writeFileSync(
+ shell,
+ [
+ "#!/bin/sh",
+ `n=$(cat "${dir}/count" 2>/dev/null || echo 0); n=$((n + 1)); echo "$n" > "${dir}/count"`,
+ `multishell="/run/user/1000/fnm_multishells/$((1000 + n))_17956/bin"`,
+ // `fnm env` prepends to the server's PATH the shell inherited (handed over in `path`).
+ `path="$multishell:/home/me/.local/share/fnm:$(cat "${dir}/path")"`,
+ 'printf "__T3CODE_ENV_PATH_START__\\n%s\\n__T3CODE_ENV_PATH_END__\\n" "$path"',
+ 'printf "__T3CODE_ENV_FNM_MULTISHELL_PATH_START__\\n%s\\n__T3CODE_ENV_FNM_MULTISHELL_PATH_END__\\n" "${multishell%/bin}"',
+ ].join("\n"),
+ { mode: 0o755 },
+ );
+ return shell;
+};
+
+effectIt.effect("re-reading an fnm login shell does not pile up its multishell folders", () =>
+ Effect.gen(function* () {
+ const dir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-fnm-"));
+ const env: NodeJS.ProcessEnv = { SHELL: fnmLoginShell(dir), PATH: "/usr/bin" };
+
+ for (let read = 0; read < 3; read++) {
+ NodeFS.writeFileSync(NodePath.join(dir, "path"), env.PATH ?? "");
+ yield* refreshPathFromLoginShell().pipe(
+ Effect.provideService(HostProcess.Platform, "linux"),
+ Effect.provideService(HostProcess.Environment, env),
+ Effect.provide(NodeServices.layer),
+ );
+ }
+ NodeFS.rmSync(dir, { recursive: true, force: true });
+
+ const multishells = (env.PATH ?? "")
+ .split(":")
+ .filter((entry) => entry.includes("fnm_multishells"));
+ assert.isAtMost(multishells.length, 1, env.PATH);
+ }),
+);
+
effectIt.effect("replaces a Path-spelled Windows PATH instead of adding a second key", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = { Path: "C:\\Windows" };
diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts
index dc0c90a787123..7f8a684ae6be6 100644
--- a/apps/server/src/os-jank.ts
+++ b/apps/server/src/os-jank.ts
@@ -32,7 +32,13 @@ function logPathHydrationWarning(message: string, error?: unknown): void {
// __MISE_DIFF is mise's record of the PATH entries it added. It must travel
// with the shell's PATH, or `mise x` can rebuild PATH behind a same-named
// wrapper (`exec mise x claude -- claude`) that then re-runs itself forever.
-const LOGIN_SHELL_ENV_NAMES = ["PATH", "__MISE_DIFF", "JAVA_HOME", "T3CODE_FEATURE_FLAGS"] as const;
+const LOGIN_SHELL_ENV_NAMES = [
+ "PATH",
+ "__MISE_DIFF",
+ "FNM_MULTISHELL_PATH",
+ "JAVA_HOME",
+ "T3CODE_FEATURE_FLAGS",
+] as const;
const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
const SLOW_LOGIN_SHELL_TIMEOUT_MS = 20_000;
@@ -52,13 +58,31 @@ function applyLoginShellEnvironment(
fallbackPath?: string,
): void {
const shellPath = shellEnvironment.PATH;
- const mergedPath = mergePathEntries(shellPath ?? fallbackPath, env.PATH, platform);
+ // fnm gives every probe shell its own multishell folder; drop the last probe's on a re-read.
+ const multishell = shellPath ? shellEnvironment.FNM_MULTISHELL_PATH : undefined;
+ const staleMultishell = multishell ? env.FNM_MULTISHELL_PATH : undefined;
+ // The probe inherits our PATH, so the stale folder is in the shell's PATH too.
+ const withoutStale = (path: string | undefined) =>
+ staleMultishell && staleMultishell !== multishell
+ ? path
+ ?.split(":")
+ .filter((entry) => entry !== staleMultishell && !entry.startsWith(`${staleMultishell}/`))
+ .join(":")
+ : path;
+ const mergedPath = mergePathEntries(
+ withoutStale(shellPath ?? fallbackPath),
+ withoutStale(env.PATH),
+ platform,
+ );
if (mergedPath) {
env.PATH = mergedPath;
}
if (shellPath && shellEnvironment.__MISE_DIFF) {
env.__MISE_DIFF = shellEnvironment.__MISE_DIFF;
}
+ if (multishell) {
+ env.FNM_MULTISHELL_PATH = multishell;
+ }
// Android SDK tools are Java programs. A keg-only JDK (Homebrew's openjdk)
// is only reachable through the JAVA_HOME the shell profile sets.
if (!env.JAVA_HOME && shellEnvironment.JAVA_HOME) {
From 82e6b029800fd83cd16f9be47c282de48d423439 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 10:48:49 -0800
Subject: [PATCH 083/238] fix(mobile): an Issues list with nothing more to load
no longer spins forever (#42992)
---
apps/mobile/src/features/issues/IssuesScreen.tsx | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/apps/mobile/src/features/issues/IssuesScreen.tsx b/apps/mobile/src/features/issues/IssuesScreen.tsx
index 361d17ac79b05..4936603a0c2cc 100644
--- a/apps/mobile/src/features/issues/IssuesScreen.tsx
+++ b/apps/mobile/src/features/issues/IssuesScreen.tsx
@@ -165,7 +165,8 @@ export function IssuesScreen(
const continuable = [...held].filter(([, page]) => Object.keys(page.nextCursors).length > 0);
const moreFailure = [...held.values()].find((page) => page.moreFailure)?.moreFailure ?? null;
const loadMore = async (retry = false) => {
- if (loading.current || (moreFailure !== null && !retry)) return;
+ // With nothing to continue, the spinner and new pages would only re-fire onEndReached forever.
+ if (loading.current || continuable.length === 0 || (moreFailure !== null && !retry)) return;
loading.current = true;
setLoadingMore(true);
const loaded = await Promise.all(
From 73c48a4341a966c29e6c2ad0663e64299d652656 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 10:55:37 -0800
Subject: [PATCH 084/238] fix(server): Antigravity sessions no longer mark an
unscanned folder's skills as scanned (#43002)
---
.../src/provider/AntigravityProvider.test.ts | 60 +++++++++++++++++++
.../src/provider/AntigravityProvider.ts | 39 +++++++-----
2 files changed, 85 insertions(+), 14 deletions(-)
diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts
index 9a2e5b1443060..1fe8c38a728d3 100644
--- a/apps/server/src/provider/AntigravityProvider.test.ts
+++ b/apps/server/src/provider/AntigravityProvider.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from "@effect/vitest";
import {
ANTIGRAVITY_DEFAULT_MODEL,
AntigravitySettings,
+ isProviderWorkspaceSnapshotPending,
ProviderDriverKind,
ProviderInstanceId,
ProviderSetupError,
@@ -958,6 +959,65 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {
}),
);
+ it.effect("a session in an unscanned folder does not publish its skills as scanned", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness();
+ yield* harness.initialize;
+ const unscanned = () =>
+ Effect.map(harness.provider.snapshot.getSnapshot, (snapshot) => {
+ const entry = snapshot.workspaceSnapshots?.find((item) => item.cwd === "/workspace");
+ // ProviderRegistry skips the skill scan for a current entry that is not pending.
+ return entry === undefined || isProviderWorkspaceSnapshotPending(entry);
+ });
+
+ yield* harness.provider.onSessionStarted(started, "/workspace");
+ expect(yield* unscanned()).toBe(true);
+ yield* harness.provider.onAvailableCommands(commands, "/workspace");
+ expect(yield* unscanned()).toBe(true);
+ }),
+ );
+
+ it.effect("a skill scan leaves the folder entry it scanned from unchanged", () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness();
+ yield* harness.initialize;
+ yield* harness.provider.onSessionStarted(started, "/workspace");
+ const published = yield* harness.provider.snapshot.getSnapshot;
+ const entryOf = (provider: ServerProvider) =>
+ provider.workspaceSnapshots?.find((entry) => entry.cwd === "/workspace");
+ const skills = [{ name: "deploy", path: "/workspace/.agent/skills/deploy", enabled: true }];
+
+ yield* harness.provider.snapshotForCwd("/workspace", skills);
+ // ProviderRegistry saves the scan only if the entry it scanned from is still published.
+ const republished = mergeProviderSnapshot(
+ published,
+ yield* harness.provider.snapshot.getSnapshot,
+ );
+ expect(entryOf(republished)).toEqual(entryOf(published));
+ }),
+ );
+
+ it.effect(
+ "keeps a scanned folder's own commands when another folder reports different ones",
+ () =>
+ Effect.gen(function* () {
+ const harness = yield* makeHarness();
+ yield* harness.initialize;
+ yield* harness.provider.onAvailableCommands(commands, "/a");
+ yield* harness.provider.snapshotForCwd("/a", []);
+ yield* harness.provider.onAvailableCommands(commands.slice(1), "/b");
+ expect((yield* harness.provider.snapshotForCwd("/a", [])).slashCommands).toEqual(
+ expectedCommands,
+ );
+ yield* harness.provider.onSessionStarted(started, "/a");
+ expect(
+ (yield* harness.provider.snapshot.getSnapshot).workspaceSnapshots?.find(
+ (entry) => entry.cwd === "/a",
+ )?.slashCommands,
+ ).toEqual(expectedCommands);
+ }),
+ );
+
it.effect("bounds workspace metadata without starting sessions for workspace lookup", () =>
Effect.gen(function* () {
const harness = yield* makeHarness();
diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts
index 2c23ea821f54a..f5d609fa38280 100644
--- a/apps/server/src/provider/AntigravityProvider.ts
+++ b/apps/server/src/provider/AntigravityProvider.ts
@@ -273,8 +273,10 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
draft: initialDraft,
authRevision: 0,
});
- // Preserve disk-discovered skills when callbacks replace workspace commands; the registry will not rescan them.
+ // Skills from the registry's last scan of each folder. A folder without them stays pending so it is scanned.
const discoveredSkills = new Map();
+ // Commands of folders whose draft entry a skill scan dropped, so later scans still report them.
+ const workspaceCommands = new Map();
const thinkingLevels = new Map();
let defaultModelSlug: string | undefined;
const observeThinkingLevels = (
@@ -474,6 +476,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
const { message: _previousMessage, ...draft } = state.draft;
const workspaces = draft.workspaceSnapshots ?? [];
const workspace = cwd ? workspaces.find((entry) => entry.cwd === cwd) : undefined;
+ const skills = cwd ? discoveredSkills.get(cwd) : undefined;
const next = {
authRevision: state.authRevision + 1,
draft: {
@@ -500,8 +503,10 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
{
cwd,
checkedAt: updatedAt,
- slashCommands: workspace?.slashCommands ?? draft.slashCommands,
- skills: workspace?.skills ?? discoveredSkills.get(cwd) ?? [],
+ slashCommands:
+ workspace?.slashCommands ?? workspaceCommands.get(cwd) ?? draft.slashCommands,
+ skills: skills ?? workspace?.skills ?? [],
+ ...(skills ? {} : { slashCommandsPending: true }),
},
].slice(-MAX_WORKSPACE_SNAPSHOTS),
}
@@ -540,6 +545,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
if (!settings.enabled) return;
const slashCommands = nativeCommands(commands);
const updatedAt = DateTime.formatIso(yield* DateTime.now);
+ const skills = cwd ? discoveredSkills.get(cwd) : undefined;
yield* SubscriptionRef.update(metadata, (state) => {
if (state.draft.auth.status === "unauthenticated") return state;
return {
@@ -556,9 +562,10 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
checkedAt: updatedAt,
slashCommands,
skills:
+ skills ??
state.draft.workspaceSnapshots?.find((entry) => entry.cwd === cwd)?.skills ??
- discoveredSkills.get(cwd) ??
[],
+ ...(skills ? {} : { slashCommandsPending: true }),
},
].slice(-MAX_WORKSPACE_SNAPSHOTS),
}
@@ -597,6 +604,7 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
]);
yield* rememberRuntimeModes(previousModes, RUNTIME_MODES_WITHOUT_AUTO);
discoveredSkills.clear();
+ workspaceCommands.clear();
thinkingLevels.clear();
defaultModelSlug = undefined;
});
@@ -605,27 +613,30 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
cwd: string,
skills?: ServerProvider["skills"],
) {
+ const snapshot = yield* getSnapshot;
+ const workspace = snapshot.workspaceSnapshots?.find((entry) => entry.cwd === cwd);
if (skills) {
discoveredSkills.set(cwd, skills);
- yield* SubscriptionRef.update(metadata, (state) =>
+ if (workspace) workspaceCommands.set(cwd, workspace.slashCommands);
+ // The registry keeps the folder it scans. Changing the entry mid-scan would discard the scan.
+ yield* SubscriptionRef.updateSome(metadata, (state) =>
state.draft.workspaceSnapshots?.some((entry) => entry.cwd === cwd)
- ? {
+ ? Option.some({
...state,
draft: {
...state.draft,
- workspaceSnapshots: state.draft.workspaceSnapshots.map((entry) =>
- entry.cwd === cwd ? { ...entry, skills } : entry,
+ workspaceSnapshots: state.draft.workspaceSnapshots.filter(
+ (entry) => entry.cwd !== cwd,
),
},
- }
- : state,
+ })
+ : Option.none(),
);
}
- const snapshot = yield* getSnapshot;
- const workspace = snapshot.workspaceSnapshots?.find((entry) => entry.cwd === cwd);
const resolvedSkills = skills ?? workspace?.skills ?? discoveredSkills.get(cwd) ?? [];
- return workspace
- ? { ...snapshot, slashCommands: workspace.slashCommands, skills: resolvedSkills }
+ const slashCommands = workspace?.slashCommands ?? workspaceCommands.get(cwd);
+ return slashCommands
+ ? { ...snapshot, slashCommands, skills: resolvedSkills }
: { ...snapshot, skills: resolvedSkills };
});
From dc5ae5ce632b47ece3faee01b46bd226911bd2e6 Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 12:56:20 -0600
Subject: [PATCH 085/238] fix(web): empty ODS sheets show 0 columns instead of
1 (#42991)
Co-authored-by: Julius Marminge
---
.../components/files/FilePreviewPanel.test.ts | 16 ++++++++++++++++
.../components/files/extendedDocumentPreview.ts | 2 +-
2 files changed, 17 insertions(+), 1 deletion(-)
diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts
index 8b584e7acf833..e1c524368c119 100644
--- a/apps/web/src/components/files/FilePreviewPanel.test.ts
+++ b/apps/web/src/components/files/FilePreviewPanel.test.ts
@@ -557,6 +557,22 @@ Third}`;
expect(result.sheets[0]!.rows).toEqual([["PT03H30M00S"]]);
});
+ it("reports zero columns for an empty ODS sheet", async () => {
+ const archive = new JSZip().file(
+ "content.xml",
+ '' +
+ ' ' +
+ 'A B C ' +
+ 'Z ' +
+ " ",
+ );
+ const result = await openDocument(archive, "ods");
+ if (result.type !== "ods") throw new Error("Expected workbook");
+ expect(result.sheets[0]).toMatchObject({ rowCount: 0, columns: 0 });
+ expect(result.sheets[1]).toMatchObject({ rowCount: 1, columns: 3 });
+ expect(result.sheets[2]).toMatchObject({ rowCount: 500, columns: 1, truncated: true });
+ });
+
it.each([1, 500])("ignores styled ODS filler after %s populated rows", async (count) => {
const archive = new JSZip().file(
"content.xml",
diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts
index 75d8c01b4e3f0..64a6589f05595 100644
--- a/apps/web/src/components/files/extendedDocumentPreview.ts
+++ b/apps/web/src/components/files/extendedDocumentPreview.ts
@@ -430,7 +430,7 @@ export async function openDocument(
name: table.attrs["table:name"] || undefined,
rows,
rowCount: rows.length,
- columns: rows.reduce((columns, row) => Math.max(columns, row.length), 1),
+ columns: rows.length && rows.reduce((columns, row) => Math.max(columns, row.length), 1),
truncated,
};
}),
From cecbe8a89a18b429765bb63109ab848a72a45c7d Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 13:24:47 -0600
Subject: [PATCH 086/238] fix(shared): new thread titles no longer end with a
space before "..." (#43014)
Co-authored-by: Julius Marminge
---
packages/shared/src/String.test.ts | 4 ++++
packages/shared/src/String.ts | 2 +-
2 files changed, 5 insertions(+), 1 deletion(-)
diff --git a/packages/shared/src/String.test.ts b/packages/shared/src/String.test.ts
index d6892beb24610..6918565849961 100644
--- a/packages/shared/src/String.test.ts
+++ b/packages/shared/src/String.test.ts
@@ -11,4 +11,8 @@ describe("truncate", () => {
it("trims before measuring", () => {
expect(truncate(" hello ", 5)).toBe("hello");
});
+
+ it("drops whitespace at the cut before the ellipsis", () => {
+ expect(truncate("hello world", 6)).toBe("hello...");
+ });
});
diff --git a/packages/shared/src/String.ts b/packages/shared/src/String.ts
index f06282c030c47..7fbae4b2c49ac 100644
--- a/packages/shared/src/String.ts
+++ b/packages/shared/src/String.ts
@@ -5,5 +5,5 @@ export function truncate(text: string, maxLength = 50): string {
return trimmed;
}
- return `${characters.slice(0, maxLength).join("")}...`;
+ return `${characters.slice(0, maxLength).join("").trimEnd()}...`;
}
From 96423cb5e2614eeb7a033cc7b755795d88a9158a Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 11:25:42 -0800
Subject: [PATCH 087/238] fix(server): stop reading Antigravity usage limits
from Google's internal APIs (#43026)
---
apps/server/package.json | 1 -
.../src/provider/AntigravityProvider.test.ts | 148 ----
.../src/provider/AntigravityProvider.ts | 75 --
.../Drivers/AntigravityDriver.test.ts | 7 -
.../src/provider/Drivers/AntigravityDriver.ts | 21 +-
.../provider/antigravityUsageLimits.test.ts | 786 ------------------
.../src/provider/antigravityUsageLimits.ts | 505 -----------
apps/server/src/testUtils/shardWeights.json | 1 -
.../src/usage/UsageLimitSources.test.ts | 42 -
apps/server/src/usage/UsageLimitSources.ts | 7 +-
apps/server/src/usage/cliproxyApi.test.ts | 131 +--
apps/server/src/usage/cliproxyApi.ts | 67 +-
.../chat/ThreadDetailsUsage.logic.ts | 15 +-
docs/user/usage.md | 4 +-
knip.jsonc | 1 -
packages/shared/src/usageLimits.test.ts | 3 -
packages/shared/src/usageLimits.ts | 40 -
pnpm-lock.yaml | 3 -
18 files changed, 15 insertions(+), 1842 deletions(-)
delete mode 100644 apps/server/src/provider/antigravityUsageLimits.test.ts
delete mode 100644 apps/server/src/provider/antigravityUsageLimits.ts
diff --git a/apps/server/package.json b/apps/server/package.json
index b8371c0ac8c9a..033a4e5dd726a 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -41,7 +41,6 @@
"@effect/platform-node-shared": "catalog:",
"@ff-labs/fff-node": "0.11.0",
"@muse-code/sdk": "1.4.6",
- "@napi-rs/keyring": "^1.3.0",
"@t3tools/issue-tracker-linear": "workspace:*",
"@t3tools/provider-acp": "workspace:*",
"@t3tools/provider-acp-registry": "workspace:*",
diff --git a/apps/server/src/provider/AntigravityProvider.test.ts b/apps/server/src/provider/AntigravityProvider.test.ts
index 1fe8c38a728d3..72e00bfb75d99 100644
--- a/apps/server/src/provider/AntigravityProvider.test.ts
+++ b/apps/server/src/provider/AntigravityProvider.test.ts
@@ -9,7 +9,6 @@ import {
ProviderInstanceId,
ProviderSetupError,
type RuntimeMode,
- type ServerProviderUsageLimits,
} from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -140,7 +139,6 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* (
readonly auth?: { readonly type: string; readonly label: string };
readonly enabled?: boolean;
readonly safe?: boolean;
- readonly probeUsage?: Effect.Effect;
readonly rememberedRuntimeModes?: ReadonlyArray;
} = {},
) {
@@ -157,7 +155,6 @@ const makeHarness = Effect.fn("makeAntigravityProviderHarness")(function* (
{
stampIdentity: (snapshot) => Effect.succeed({ ...snapshot, instanceId, driver }),
...(options.auth ? { auth: options.auth } : {}),
- ...(options.probeUsage ? { probeUsage: options.probeUsage } : {}),
...(options.rememberedRuntimeModes
? { rememberedRuntimeModes: options.rememberedRuntimeModes }
: {}),
@@ -1033,151 +1030,6 @@ it.layer(layerTest)("Antigravity provider snapshots", (it) => {
expect(yield* Ref.get(harness.probeCalls)).toBe(1);
}),
);
-
- it.effect(
- "publishes limits, retains a successful read on failure, and clears them on sign-out",
- () =>
- Effect.gen(function* () {
- const limits: ServerProviderUsageLimits = {
- checkedAt: "2026-10-09T12:00:00.000Z",
- windows: [
- {
- id: "3p-weekly",
- kind: "weekly",
- label: "Claude & GPT (shared) · Weekly",
- usedPercent: 75,
- },
- ],
- };
- const usage = yield* Ref.make(limits);
- const harness = yield* makeHarness({ probeUsage: Ref.get(usage) });
- const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
- yield* harness.initialize;
- expect((yield* published)?.usageLimits).toEqual(limits);
- // The second health check is the one the failed background read triggers.
- const checks = yield* Ref.make(0);
- const failedReadApplied = yield* Deferred.make();
- yield* Ref.set(
- harness.probe,
- Ref.updateAndGet(checks, (count) => count + 1).pipe(
- Effect.tap((count) =>
- count === 2 ? Deferred.succeed(failedReadApplied, undefined) : Effect.void,
- ),
- Effect.as(initializeResult),
- ),
- );
- yield* Ref.set(usage, {
- checkedAt: "2026-10-09T12:01:00.000Z",
- windows: [],
- unavailable: { reason: "probeFailed" },
- });
- yield* harness.provider.snapshot.refresh;
- yield* Deferred.await(failedReadApplied);
- expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toEqual(limits);
- yield* harness.provider.onSignedOut;
- expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
- yield* Ref.set(usage, {
- checkedAt: "2026-10-09T12:02:00.000Z",
- windows: [],
- unavailable: { reason: "unsupported" },
- });
- const unsupported = yield* harness.nextPublish(
- (snapshot) => snapshot.usageLimits?.unavailable?.reason === "unsupported",
- );
- yield* harness.provider.snapshot.refresh;
- expect((yield* unsupported)?.usageLimits?.windows).toEqual([]);
- }),
- );
-
- it.effect("a quota read finishing after sign-out cannot restore account limits", () =>
- Effect.gen(function* () {
- const readStarted = yield* Deferred.make();
- const readResult = yield* Deferred.make();
- const usage = yield* Ref.make>(
- Effect.succeed({ checkedAt: "2026-10-09T12:00:00.000Z", windows: [] }),
- );
- const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });
- yield* harness.initialize;
- yield* Ref.set(harness.probe, Effect.succeed(initializeResult));
- yield* Ref.set(
- usage,
- Deferred.succeed(readStarted, undefined).pipe(Effect.andThen(Deferred.await(readResult))),
- );
- const refresh = yield* harness.provider.snapshot.refresh.pipe(Effect.forkChild);
- yield* Deferred.await(readStarted);
- yield* harness.provider.onSignedOut;
- yield* Deferred.succeed(readResult, {
- checkedAt: "2026-10-09T12:01:00.000Z",
- windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }],
- });
- yield* Fiber.join(refresh);
- expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
- }),
- );
-
- it.effect("reports ready and starts sessions while one shared quota read is pending", () =>
- Effect.gen(function* () {
- const reads = yield* Ref.make(0);
- const readStarted = yield* Deferred.make();
- const readResult = yield* Deferred.make();
- const harness = yield* makeHarness({
- probeUsage: Ref.update(reads, (count) => count + 1).pipe(
- Effect.andThen(Deferred.succeed(readStarted, undefined)),
- Effect.andThen(Deferred.await(readResult)),
- ),
- });
- const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
- yield* harness.initialize;
- yield* Deferred.await(readStarted);
- yield* harness.provider.onSessionStarted(started, "/workspace");
- yield* harness.provider.onSessionStarted(started, "/other");
- const ready = yield* harness.provider.snapshot.getSnapshot;
- expect(ready).toMatchObject({ status: "ready", auth: { status: "authenticated" } });
- expect(ready.usageLimits).toBeUndefined();
- expect(yield* Ref.get(reads)).toBe(1);
- const limits = {
- checkedAt: "2026-10-09T12:00:00.000Z",
- windows: [{ id: "gemini-5h", kind: "session", label: "Gemini · 5-hour", usedPercent: 10 }],
- } satisfies ServerProviderUsageLimits;
- yield* Deferred.succeed(readResult, limits);
- expect((yield* published)?.usageLimits).toEqual(limits);
- }),
- );
-
- it.effect("a quota read for the previous account is dropped after a new sign-in", () =>
- Effect.gen(function* () {
- const oldReadStarted = yield* Deferred.make();
- const newLimits = {
- checkedAt: "2026-10-09T12:01:00.000Z",
- windows: [{ id: "3p-weekly", kind: "weekly", label: "Weekly", usedPercent: 40 }],
- } satisfies ServerProviderUsageLimits;
- const usage = yield* Ref.make>(
- Deferred.succeed(oldReadStarted, undefined).pipe(Effect.andThen(Effect.never)),
- );
- const harness = yield* makeHarness({ probeUsage: Ref.get(usage).pipe(Effect.flatten) });
- const published = yield* harness.nextPublish((snapshot) => !!snapshot.usageLimits);
- yield* harness.initialize;
- yield* Deferred.await(oldReadStarted);
- yield* Ref.set(usage, Effect.succeed(newLimits));
- yield* harness.provider.onSignedIn;
- yield* harness.provider.onSessionStarted(started);
- expect((yield* published)?.usageLimits).toEqual(newLimits);
- // Switching again must not republish the previous account's limits, even if the read fails.
- const failed = {
- checkedAt: "2026-10-09T12:02:00.000Z",
- windows: [],
- unavailable: { reason: "probeFailed" },
- } satisfies ServerProviderUsageLimits;
- yield* Ref.set(usage, Effect.succeed(failed));
- const republished = yield* harness.nextPublish(
- (snapshot) => snapshot.usageLimits?.unavailable?.reason === "probeFailed",
- );
- yield* harness.provider.onSignedIn;
- expect((yield* harness.provider.snapshot.getSnapshot).usageLimits).toBeUndefined();
- yield* harness.provider.onSessionStarted(started);
- expect((yield* republished)?.usageLimits).toEqual(failed);
- }),
- );
});
it.layer(makeLayerTest(true))("Antigravity periodic health checks", (it) => {
diff --git a/apps/server/src/provider/AntigravityProvider.ts b/apps/server/src/provider/AntigravityProvider.ts
index f5d609fa38280..fccf11d663af5 100644
--- a/apps/server/src/provider/AntigravityProvider.ts
+++ b/apps/server/src/provider/AntigravityProvider.ts
@@ -8,15 +8,11 @@ import {
type ServerProvider,
type ServerProviderModel,
type ServerProviderSlashCommand,
- type ServerProviderUsageLimits,
} from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
-import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
-import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Equal from "effect/Equal";
-import * as FiberHandle from "effect/FiberHandle";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import * as Result from "effect/Result";
@@ -41,7 +37,6 @@ import {
isCommandMissingCause,
type ServerProviderDraft,
} from "@t3tools/provider-core/server/snapshotProbe";
-import { resolveUsageLimitsAfterProbe } from "@t3tools/provider-core/server/usageLimits";
import { antigravityThinkingConfig } from "./acp/AntigravityAcpSupport.ts";
@@ -51,10 +46,6 @@ const HEALTH_CHECK_TIMEOUT_MS = 90_000;
const SIGN_IN_MESSAGE = "Sign in with Google to use Antigravity.";
const AUTH_UNCHECKED_MESSAGE =
"Antigravity is installed. Google account access is not checked yet.";
-// Set while a finished quota read republishes, so that health check does not read again.
-const PublishingUsage = Context.Reference("t3/provider/AntigravityPublishingUsage", {
- defaultValue: () => false,
-});
type SessionSetupResult = Pick<
AcpSessionRuntime.AcpSessionRuntimeStartResult["sessionSetupResult"],
@@ -205,8 +196,6 @@ interface AntigravityProviderOptions {
EffectAcpErrors.AcpError | ProviderSetupError
>;
readonly supportsTextGeneration: Effect.Effect;
- readonly probeUsage?: Effect.Effect;
- readonly clearUsage?: Effect.Effect;
readonly maintenanceCapabilities?: ProviderMaintenanceCapabilities;
readonly auth?: { readonly type: string; readonly label: string };
/** Modes the last session advertised, saved because initialize alone does not report them. */
@@ -309,47 +298,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
Effect.flatMap((state) => options.stampIdentity(state.draft)),
);
- // The quota read can take 30 seconds, so it never blocks readiness or a session start.
- // One read runs at a time; sign-in and sign-out interrupt it so a stale account never lands.
- const usageRead = yield* FiberHandle.make();
- const republish = yield* Deferred.make>();
- const scope = yield* Effect.scope;
- const refreshUsage = Effect.fn("AntigravityProvider.refreshUsage")(function* () {
- if (!options.probeUsage || (yield* PublishingUsage)) return;
- yield* FiberHandle.run(
- usageRead,
- options.probeUsage.pipe(
- Effect.flatMap((probed) =>
- SubscriptionRef.update(metadata, (state) => ({
- ...state,
- draft: {
- ...state.draft,
- usageLimits: resolveUsageLimitsAfterProbe({
- published: state.draft.usageLimits,
- probed,
- }),
- },
- })),
- ),
- // Enrichment cannot change published limits; a health check publishes them.
- Effect.andThen(
- Deferred.await(republish).pipe(
- Effect.flatten,
- Effect.provideService(PublishingUsage, true),
- Effect.ignoreCause({ log: true }),
- Effect.forkIn(scope),
- ),
- ),
- ),
- // Store the fiber before it runs, so a sign-out during the read can interrupt it.
- { onlyIfMissing: true, startImmediately: false },
- );
- });
- const resetUsage = Effect.gen(function* () {
- yield* FiberHandle.clear(usageRead);
- if (options.clearUsage) yield* options.clearUsage;
- });
-
const checkProvider = Effect.fn("checkAntigravityProvider")(function* () {
if (!settings.enabled) return yield* getSnapshot;
const before = yield* SubscriptionRef.get(metadata);
@@ -397,7 +345,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
version: version === "unknown" ? draft.version : version || draft.version,
status: errorMessage ? "error" : authenticated ? "ready" : "warning",
checkedAt: updatedAt,
- usageLimits: missingInstallation ? undefined : draft.usageLimits,
...(missingInstallation
? {
models: [],
@@ -424,7 +371,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
const stored = deferFailure && state.draft.status === "ready" ? state : checked;
return [checked, stored === state ? Option.none() : Option.some(stored)];
});
- if (initialized !== undefined) yield* refreshUsage();
return yield* options.stampIdentity(next.draft);
});
@@ -448,7 +394,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
),
),
});
- yield* Deferred.succeed(republish, managed.refresh);
const onSessionStarted = Effect.fn("AntigravityProvider.onSessionStarted")(function* (
started: AcpSessionRuntime.AcpSessionRuntimeStartResult,
@@ -516,7 +461,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
return [draft.supportedRuntimeModes, next] as const;
});
yield* rememberRuntimeModes(previousModes, supportedRuntimeModes);
- if (!before.draft.usageLimits || before.draft.usageLimits.unavailable) yield* refreshUsage();
});
const onConfigOptionsUpdated = Effect.fn("AntigravityProvider.onConfigOptionsUpdated")(function* (
@@ -576,7 +520,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
});
const clearAccountMetadata = Effect.fn("AntigravityProvider.clearAccountMetadata")(function* () {
- yield* resetUsage;
if (!settings.enabled) return;
const updatedAt = DateTime.formatIso(yield* DateTime.now);
const previousModes = yield* SubscriptionRef.modify(metadata, (state) => [
@@ -598,7 +541,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
workspaceSnapshots: [],
supportedRuntimeModes: RUNTIME_MODES_WITHOUT_AUTO,
supportsTextGeneration: false,
- usageLimits: undefined,
},
} satisfies AntigravityProviderState,
]);
@@ -645,23 +587,6 @@ export const makeAntigravityProvider = Effect.fn("makeAntigravityProvider")(func
onSessionStarted,
onConfigOptionsUpdated,
onAvailableCommands,
- // The new sign-in may be another account. Clear and republish its limits so a failed read
- // cannot fall back to them; the session start then reads the new account's limits.
- onSignedIn: resetUsage.pipe(
- Effect.andThen(
- SubscriptionRef.update(metadata, (state) => {
- const { usageLimits: _previousAccount, ...draft } = state.draft;
- return { ...state, draft };
- }),
- ),
- Effect.andThen(
- Deferred.await(republish).pipe(
- Effect.flatten,
- Effect.provideService(PublishingUsage, true),
- ),
- ),
- Effect.asVoid,
- ),
onSignedOut: clearAccountMetadata(),
onAuthRequired: clearAccountMetadata(),
snapshotForCwd,
diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts
index 19451dd10ce16..c4b7cf3f994a6 100644
--- a/apps/server/src/provider/Drivers/AntigravityDriver.test.ts
+++ b/apps/server/src/provider/Drivers/AntigravityDriver.test.ts
@@ -26,7 +26,6 @@ import * as Redacted from "effect/Redacted";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
-import { HttpClient } from "effect/http";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import * as ServerConfig from "../../config.ts";
@@ -292,12 +291,6 @@ const layerDeps = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-antigravity-driver-config-",
}).pipe(
Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
- Layer.provideMerge(
- Layer.succeed(
- HttpClient.HttpClient,
- HttpClient.make(() => Effect.die("Unexpected quota request")),
- ),
- ),
Layer.provideMerge(ServerSettings.layerTest()),
Layer.provideMerge(
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts
index 36c8e68123c08..4d0af3d9900df 100644
--- a/apps/server/src/provider/Drivers/AntigravityDriver.ts
+++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts
@@ -27,7 +27,6 @@ import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
-import { HttpClient } from "effect/http";
import * as AcpErrors from "effect-acp/errors";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
@@ -71,7 +70,6 @@ import {
import { makeAcpNativeLoggerFactory } from "@t3tools/provider-acp/server/nativeLogging";
import { ProviderDriverError } from "../Errors.ts";
import { makeAntigravityProvider } from "../AntigravityProvider.ts";
-import { makeAntigravityUsageProbe } from "../antigravityUsageLimits.ts";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as ModelCatalog from "@t3tools/provider-core/server/ModelCatalog";
import {
@@ -115,7 +113,6 @@ export type AntigravityDriverEnv =
| Digest.Digest
| SecureRandom.SecureRandom
| FileSystem.FileSystem
- | HttpClient.HttpClient
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ModelCatalog.ModelCatalog
@@ -143,7 +140,6 @@ export const AntigravityDriver: ProviderDriver<
const digest = yield* Digest.Digest;
const random = yield* SecureRandom.SecureRandom;
const fileSystem = yield* FileSystem.FileSystem;
- const httpClient = yield* HttpClient.HttpClient;
const path = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const host = yield* ProviderHost.ProviderHost;
@@ -527,11 +523,7 @@ export const AntigravityDriver: ProviderDriver<
const authFlow: AntigravityAuth = yield* makeAntigravityAuth({
instanceId,
makeRuntime: makeDisposableRuntime,
- // A new sign-in may be another account; drop any in-flight quota read first.
- onAuthenticated: (started, runtime) =>
- Effect.suspend(() => provider.onSignedIn).pipe(
- Effect.andThen(publishCatalog(started, runtime)),
- ),
+ onAuthenticated: publishCatalog,
onSignedOut: Effect.suspend(() => provider.onSignedOut),
usesBrowser: antigravityAuthUsesBrowser(auth.authMethod),
codeLogin,
@@ -576,21 +568,10 @@ export const AntigravityDriver: ProviderDriver<
};
});
- const usage = yield* makeAntigravityUsageProbe({
- profileDirectory,
- authMethod: auth.authMethod,
- }).pipe(
- Effect.provideService(FileSystem.FileSystem, fileSystem),
- Effect.provideService(Path.Path, path),
- Effect.provideService(Digest.Digest, digest),
- Effect.provideService(HttpClient.HttpClient, httpClient),
- );
const provider = yield* makeAntigravityProvider(settings, {
environment: processEnvironment,
stampIdentity: classifyModels,
probe,
- probeUsage: usage.probe,
- clearUsage: usage.clear,
auth: { type: auth.authMethod, label: antigravityAuthLabel(auth.authMethod) },
...(rememberedRuntimeModes ? { rememberedRuntimeModes } : {}),
rememberRuntimeModes: (modes) =>
diff --git a/apps/server/src/provider/antigravityUsageLimits.test.ts b/apps/server/src/provider/antigravityUsageLimits.test.ts
deleted file mode 100644
index eec70e2e44fce..0000000000000
--- a/apps/server/src/provider/antigravityUsageLimits.test.ts
+++ /dev/null
@@ -1,786 +0,0 @@
-import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
-import * as NodeServices from "@effect/platform-node/NodeServices";
-import * as HostProcess from "@t3tools/shared/HostProcess";
-import * as Layer from "effect/Layer";
-import { describe, expect, it } from "@effect/vitest";
-import * as Context from "effect/Context";
-import * as DateTime from "effect/DateTime";
-import * as Effect from "effect/Effect";
-import * as FileSystem from "effect/FileSystem";
-import * as Path from "effect/Path";
-import * as TestClock from "effect/testing/TestClock";
-import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
-
-import {
- decodeGoKeyringSecret,
- makeAntigravityUsageProbe,
- readWindowsCliCredential,
-} from "./antigravityUsageLimits.ts";
-
-const summary = {
- groups: [
- {
- displayName: "Gemini Models",
- buckets: [
- {
- bucketId: "gemini-weekly",
- window: "weekly",
- remainingFraction: 0.96,
- resetTime: "2026-10-12T19:41:43Z",
- },
- {
- bucketId: "gemini-5h",
- window: "5h",
- remainingFraction: 0.91,
- resetTime: "2026-10-09T16:06:01Z",
- },
- ],
- },
- {
- displayName: "Claude and GPT models",
- buckets: [
- {
- bucketId: "3p-weekly",
- window: "weekly",
- remainingFraction: 0,
- resetTime: "2026-10-10T15:28:22Z",
- },
- {
- bucketId: "3p-5h",
- window: "5h",
- remainingFraction: 0.44,
- resetTime: "2026-10-09T16:06:30Z",
- },
- ],
- },
- ],
-};
-
-const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* (
- options: {
- summary?: unknown;
- /** Per-host quota summaries; hosts not listed fall back to `summary`. */
- summaryByHost?: Record;
- models?: unknown;
- summaryStatus?: number;
- /** Per-host summary statuses; hosts not listed fall back to `summaryStatus`. */
- summaryStatusByHost?: Record;
- tokenStatus?: number;
- refreshToken?: string;
- userId?: string;
- userInfoAt?: number;
- missingToken?: boolean;
- authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key";
- keyringSecret?: string;
- /** Reads the OS keyring instead of `keyringSecret`. */
- nativeKeyring?: boolean;
- } = {},
-) {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const profileDirectory = yield* fs.makeTempDirectoryScoped();
- yield* fs.makeDirectory(path.join(profileDirectory, "antigravity-acp"));
- const tokenPath = path.join(profileDirectory, "antigravity-acp", "acp_token.json");
- const writeToken = (refreshToken: string) =>
- fs.writeFileString(
- tokenPath,
- JSON.stringify({
- client_id: "client-id",
- client_secret: "client-secret",
- refresh_token: refreshToken,
- project_id: "project-id",
- }),
- );
- if (!options.missingToken) yield* writeToken(options.refreshToken ?? "refresh-a");
- const requests: Array<{ url: string; body: string }> = [];
- const http = HttpClient.make((request, url, _signal, fiber) =>
- Effect.sync(() => {
- const init = Context.getOrUndefined(fiber.context, FetchHttpClient.RequestInit);
- expect(init?.redirect).toBe("manual");
- const body =
- request.body._tag === "Uint8Array" ? new TextDecoder().decode(request.body.body) : "";
- requests.push({ url: request.url, body });
- if (request.url.endsWith("/token")) {
- expect(new URLSearchParams(body).get("grant_type")).toBe("refresh_token");
- return HttpClientResponse.fromWeb(
- request,
- Response.json(
- { access_token: "access-token", expires_in: 3600 },
- { status: options.tokenStatus ?? 200 },
- ),
- );
- }
- expect(request.headers.authorization).toBe("Bearer access-token");
- if (request.url.endsWith("/userinfo")) {
- return HttpClientResponse.fromWeb(
- request,
- options.userId
- ? Response.json({ id: options.userId, email: "someone@example.com" })
- : Response.json({}, { status: 403 }),
- );
- }
- expect(JSON.parse(body)).toEqual(options.missingToken ? {} : { project: "project-id" });
- expect(request.headers["user-agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /);
- return HttpClientResponse.fromWeb(
- request,
- request.url.endsWith(":retrieveUserQuotaSummary")
- ? Response.json(options.summaryByHost?.[url.host] ?? options.summary ?? summary, {
- status: options.summaryStatusByHost?.[url.host] ?? options.summaryStatus ?? 200,
- })
- : Response.json(options.models ?? { models: {} }),
- );
- }).pipe(
- Effect.tap(() =>
- request.url.endsWith("/userinfo") && options.userInfoAt !== undefined
- ? TestClock.setTime(options.userInfoAt)
- : Effect.void,
- ),
- ),
- );
- const usage = yield* makeAntigravityUsageProbe({
- profileDirectory,
- authMethod: options.authMethod ?? "oauth-personal",
- ...(options.nativeKeyring ? {} : { readKeyringSecret: Effect.succeed(options.keyringSecret) }),
- }).pipe(Effect.provideService(HttpClient.HttpClient, http));
- return { ...usage, requests, writeToken, tokenPath };
-});
-
-describe("Antigravity subscription limits", () => {
- // Oracle: the 10:16 UTC payload and its narrow Workaround rule.
- it.effect("omits rolling resets for untouched summary buckets and keeps used Gemini resets", () =>
- Effect.gen(function* () {
- yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
- const { probe } = yield* fixture({
- summary: {
- groups: [
- {
- buckets: [
- {
- bucketId: "3p-5h",
- window: "5h",
- remainingFraction: 1,
- resetTime: "2026-10-21T15:16:05Z",
- },
- {
- bucketId: "3p-weekly",
- window: "weekly",
- remainingFraction: 1,
- resetTime: "2026-10-28T10:16:05Z",
- },
- {
- bucketId: "gemini-5h",
- window: "5h",
- remainingFraction: 0.848104,
- resetTime: "2026-10-21T13:29:53Z",
- description:
- "You have used some of your 5-hour limit, it will fully refresh in 3 hours, 13 minutes.",
- },
- {
- bucketId: "gemini-weekly",
- window: "weekly",
- remainingFraction: 0.9620177,
- resetTime: "2026-10-28T08:29:53Z",
- description:
- "You have used some of your weekly limit, it will fully refresh in 6 days, 22 hours.",
- },
- ],
- },
- ],
- },
- });
- const limits = yield* probe;
- const byId = new Map(limits.windows.map((window) => [window.id, window]));
- expect(byId.get("3p-5h")).toEqual({
- id: "3p-5h",
- label: "Claude & GPT (shared) · 5-hour",
- kind: "session",
- usedPercent: 0,
- windowDurationMins: 300,
- });
- expect(byId.get("3p-weekly")).toEqual({
- id: "3p-weekly",
- label: "Claude & GPT (shared) · Weekly",
- kind: "weekly",
- usedPercent: 0,
- windowDurationMins: 10080,
- });
- expect(byId.get("gemini-5h")?.resetsAt).toBe("2026-10-21T13:29:53.000Z");
- expect(byId.get("gemini-weekly")?.resetsAt).toBe("2026-10-28T08:29:53.000Z");
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- // Oracle: measure the tolerance from the summary request, after auth.
- it.effect("uses summary request time after authentication for the reset tolerance", () =>
- Effect.gen(function* () {
- yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:02Z")));
- const { probe } = yield* fixture({
- userInfoAt: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")),
- summary: {
- buckets: [
- {
- bucketId: "3p-5h",
- window: "5h",
- remainingFraction: 1,
- resetTime: "2026-10-21T15:17:03Z",
- },
- ],
- },
- });
- expect((yield* probe).windows[0]?.resetsAt).toBeUndefined();
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- // Oracle: keep descriptions, measured resets, and spent buckets.
- it.effect("keeps summary resets with a description, a distant reset, or no quota left", () =>
- Effect.gen(function* () {
- yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
- const { probe } = yield* fixture({
- summary: {
- buckets: [
- {
- bucketId: "described",
- window: "5h",
- remainingFraction: 1,
- description: "Reported reset",
- resetTime: "2026-10-21T15:16:04Z",
- },
- {
- bucketId: "distant",
- window: "weekly",
- remainingFraction: 1,
- resetTime: "2026-10-28T12:16:04Z",
- },
- {
- bucketId: "spent",
- window: "5h",
- remainingFraction: 0,
- resetTime: "2026-10-21T15:16:04Z",
- },
- {
- bucketId: "overfull",
- window: "5h",
- remainingFraction: 1.01,
- resetTime: "2026-10-21T15:16:04Z",
- },
- {
- bucketId: "empty-description",
- window: "5h",
- remainingFraction: 1,
- description: "",
- resetTime: "2026-10-21T15:16:04Z",
- },
- ],
- },
- });
- expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([
- { id: "described", resetsAt: "2026-10-21T15:16:04.000Z" },
- { id: "empty-description", resetsAt: "2026-10-21T15:16:04.000Z" },
- { id: "overfull", resetsAt: "2026-10-21T15:16:04.000Z" },
- { id: "spent", resetsAt: "2026-10-21T15:16:04.000Z" },
- { id: "distant", resetsAt: "2026-10-28T12:16:04.000Z" },
- ]);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- // Oracle: the 60-second tolerance applies to both known window lengths.
- it.effect("omits summary resets 59 seconds away but keeps resets 61 seconds away", () =>
- Effect.gen(function* () {
- yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
- const { probe } = yield* fixture({
- summary: {
- buckets: [
- {
- bucketId: "5h-before",
- window: "5h",
- remainingFraction: 1,
- resetTime: "2026-10-21T15:15:05Z",
- },
- {
- bucketId: "5h-after",
- window: "5h",
- remainingFraction: 1,
- resetTime: "2026-10-21T15:17:05Z",
- },
- {
- bucketId: "5h-edge",
- window: "5h",
- remainingFraction: 1,
- resetTime: "2026-10-21T15:17:04Z",
- },
- {
- bucketId: "weekly-after",
- window: "weekly",
- remainingFraction: 1,
- resetTime: "2026-10-28T10:17:03Z",
- },
- {
- bucketId: "weekly-before",
- window: "weekly",
- remainingFraction: 1,
- resetTime: "2026-10-28T10:15:03Z",
- },
- {
- bucketId: "weekly-edge",
- window: "weekly",
- remainingFraction: 1,
- resetTime: "2026-10-28T10:15:04Z",
- },
- ],
- },
- });
- expect((yield* probe).windows.map(({ id, resetsAt }) => ({ id, resetsAt }))).toEqual([
- { id: "5h-after", resetsAt: "2026-10-21T15:17:05.000Z" },
- { id: "5h-before", resetsAt: undefined },
- { id: "5h-edge", resetsAt: undefined },
- { id: "weekly-after", resetsAt: undefined },
- { id: "weekly-before", resetsAt: "2026-10-28T10:15:03.000Z" },
- { id: "weekly-edge", resetsAt: undefined },
- ]);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- // Oracle: workspace sign-ins are metered on cloudcode-pa, so its reading wins even when less used.
- it.effect("reports a business account's quota from the endpoint it is metered on", () =>
- Effect.gen(function* () {
- yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
- const { probe } = yield* fixture({
- authMethod: "oauth-business",
- summaryByHost: {
- "daily-cloudcode-pa.googleapis.com": {
- buckets: [
- {
- bucketId: "3p-5h",
- window: "5h",
- remainingFraction: 1,
- resetTime: "2026-10-21T15:16:04Z",
- },
- {
- bucketId: "3p-weekly",
- window: "weekly",
- remainingFraction: 0.5,
- resetTime: "2026-10-27T10:16:04Z",
- },
- ],
- },
- "cloudcode-pa.googleapis.com": {
- buckets: [
- {
- bucketId: "3p-5h",
- window: "5h",
- remainingFraction: 0.5,
- resetTime: "2026-10-21T13:16:04Z",
- },
- {
- bucketId: "3p-weekly",
- window: "weekly",
- remainingFraction: 1,
- resetTime: "2026-10-28T10:16:04Z",
- },
- ],
- },
- },
- });
- expect((yield* probe).windows).toEqual([
- {
- id: "3p-5h",
- label: "Claude & GPT (shared) · 5-hour",
- kind: "session",
- usedPercent: 50,
- windowDurationMins: 300,
- resetsAt: "2026-10-21T13:16:04.000Z",
- },
- {
- id: "3p-weekly",
- label: "Claude & GPT (shared) · Weekly",
- kind: "weekly",
- usedPercent: 0,
- windowDurationMins: 10080,
- },
- ]);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- // Oracle: model quotas have no evidence for the summary-only rule.
- it.effect("keeps full model fallback resets even at a full window from the request", () =>
- Effect.gen(function* () {
- yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z")));
- const { probe } = yield* fixture({
- summaryStatus: 404,
- models: {
- models: {
- "gemini-a": {
- quotaInfo: { remainingFraction: 1, resetTime: "2026-10-21T15:16:04Z" },
- weeklyQuotaInfo: { remainingFraction: 1, resetTime: "2026-10-28T10:16:04Z" },
- },
- },
- },
- });
- expect(
- (yield* probe).windows.map(({ id, resetsAt, windowDurationMins }) => ({
- id,
- resetsAt,
- windowDurationMins,
- })),
- ).toEqual([
- { id: "gemini-weekly", resetsAt: "2026-10-28T10:16:04.000Z", windowDurationMins: 10080 },
- { id: "gemini-quota", resetsAt: "2026-10-21T15:16:04.000Z", windowDurationMins: undefined },
- ]);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("reports separate Gemini and shared Claude/GPT five-hour and weekly limits", () =>
- Effect.gen(function* () {
- const { probe, requests } = yield* fixture();
- const limits = yield* probe;
- expect(limits.windows).toHaveLength(4);
- expect(limits.unavailable).toBeUndefined();
- expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
- const byId = new Map(limits.windows.map((window) => [window.id, window]));
- expect(byId.get("gemini-weekly")?.usedPercent).toBeCloseTo(4);
- expect(byId.get("gemini-5h")?.usedPercent).toBeCloseTo(9);
- expect(byId.get("3p-weekly")).toMatchObject({
- label: "Claude & GPT (shared) · Weekly",
- kind: "weekly",
- usedPercent: 100,
- windowDurationMins: 10080,
- resetsAt: "2026-10-10T15:28:22.000Z",
- });
- expect(byId.get("3p-5h")).toMatchObject({ kind: "session", windowDurationMins: 300 });
- expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(56);
- yield* probe;
- expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(1);
- expect(
- requests.filter((request) => request.url.endsWith(":retrieveUserQuotaSummary")),
- ).toHaveLength(4);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("merges quota groups that only one endpoint reports", () =>
- Effect.gen(function* () {
- const { probe } = yield* fixture({
- summaryByHost: {
- // The daily endpoint can omit Gemini while the other endpoint returns all groups.
- "daily-cloudcode-pa.googleapis.com": {
- groups: [
- {
- displayName: "Claude and GPT models",
- buckets: [
- { bucketId: "3p-weekly", window: "weekly", remainingFraction: 0.5 },
- { bucketId: "3p-5h", window: "5h", remainingFraction: 0.3 },
- ],
- },
- ],
- },
- },
- });
- const limits = yield* probe;
- expect(limits.windows.map((window) => window.id).toSorted()).toEqual([
- "3p-5h",
- "3p-weekly",
- "gemini-5h",
- "gemini-weekly",
- ]);
- const byId = new Map(limits.windows.map((window) => [window.id, window]));
- expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly");
- expect(byId.get("3p-5h")?.usedPercent).toBeCloseTo(70);
- expect(byId.get("3p-weekly")?.usedPercent).toBe(50);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- // Oracle: reported payloads for a personal sign-in, whose runtime meters on the daily endpoint.
- it.effect("reports a personal account's quota from the daily endpoint it is metered on", () =>
- Effect.gen(function* () {
- yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-07T12:00:00Z")));
- const argon = (remainingFraction: number, resetTime: string) => ({
- groups: [
- {
- displayName: "Gemini 4 Argon",
- buckets: [
- {
- bucketId: "gemini-argon-wtu-weekly",
- window: "weekly",
- remainingFraction,
- resetTime,
- },
- ],
- },
- ],
- });
- const { probe } = yield* fixture({
- authMethod: "oauth-personal",
- summaryByHost: {
- "daily-cloudcode-pa.googleapis.com": argon(0.8623059, "2026-11-14T08:41:35Z"),
- "cloudcode-pa.googleapis.com": argon(0, "2026-11-08T18:27:14Z"),
- },
- });
- expect((yield* probe).windows).toEqual([
- expect.objectContaining({
- id: "gemini-argon-wtu-weekly",
- usedPercent: expect.closeTo(13.77, 2),
- resetsAt: "2026-11-14T08:41:35.000Z",
- }),
- ]);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("labels Argon and Carbon quotas apart from the default Gemini quota", () =>
- Effect.gen(function* () {
- const { probe } = yield* fixture({
- summary: {
- groups: [
- ...summary.groups,
- {
- displayName: "Gemini 4 Argon",
- buckets: [
- { bucketId: "gemini-argon-wtu-weekly", window: "weekly", remainingFraction: 0.6 },
- ],
- },
- {
- displayName: "Gemini 4 Carbon",
- buckets: [
- { bucketId: "gemini-carbon-wtu-weekly", window: "weekly", remainingFraction: 0.4 },
- ],
- },
- {
- displayName: " ",
- buckets: [{ bucketId: "gemini-carbon-5h", window: "5h", remainingFraction: 0.8 }],
- },
- ],
- },
- });
- const limits = yield* probe;
- const byId = new Map(limits.windows.map((window) => [window.id, window]));
- expect(byId.get("gemini-weekly")?.label).toBe("Gemini · Weekly");
- expect(byId.get("gemini-argon-wtu-weekly")?.label).toBe("Gemini 4 Argon · Weekly");
- expect(byId.get("gemini-carbon-wtu-weekly")?.label).toBe("Gemini 4 Carbon · Weekly");
- expect(byId.get("gemini-carbon-5h")?.label).toBe("Gemini Carbon · 5-hour");
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("keeps one endpoint's quotas when the other fails", () =>
- Effect.gen(function* () {
- const { probe } = yield* fixture({
- summaryStatusByHost: { "daily-cloudcode-pa.googleapis.com": 503 },
- });
- const limits = yield* probe;
- expect(limits.unavailable).toBeUndefined();
- expect(limits.windows).toHaveLength(4);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("re-reads changed credentials and clears cached access after sign-out", () =>
- Effect.gen(function* () {
- const { probe, clear, requests, writeToken, tokenPath } = yield* fixture();
- const first = yield* probe;
- yield* writeToken("refresh-b");
- const second = yield* probe;
- expect(second.credentialFingerprint).not.toBe(first.credentialFingerprint);
- expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(2);
- yield* (yield* FileSystem.FileSystem).remove(tokenPath);
- expect((yield* probe).unavailable?.reason).toBe("unsupported");
- yield* writeToken("refresh-b");
- yield* probe;
- expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(3);
- yield* clear;
- yield* probe;
- expect(requests.filter((request) => request.url.endsWith("/token"))).toHaveLength(4);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("names one Google account the same way from every sign-in", () =>
- Effect.gen(function* () {
- const read = (refreshToken: string, userId: string) =>
- fixture({ refreshToken, userId }).pipe(Effect.flatMap((usage) => usage.probe));
- const machineA = yield* read("refresh-a", "google-user-1");
- const machineB = yield* read("refresh-b", "google-user-1");
- const otherAccount = yield* read("refresh-c", "google-user-2");
- expect(machineA.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/);
- expect(machineB.credentialFingerprint).toBe(machineA.credentialFingerprint);
- expect(otherAccount.credentialFingerprint).not.toBe(machineA.credentialFingerprint);
- expect(JSON.stringify(machineA)).not.toMatch(/google-user-1|someone@example.com/);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("falls back to model quotas without inventing a window duration", () =>
- Effect.gen(function* () {
- const { probe } = yield* fixture({
- summaryStatus: 404,
- models: {
- models: {
- "gemini-a": {
- modelProvider: "MODEL_PROVIDER_GOOGLE",
- quotaInfo: { remainingFraction: 0.8, resetTime: "2026-10-10T12:00:00Z" },
- },
- "gemini-b": {
- modelProvider: "MODEL_PROVIDER_GOOGLE",
- quotaInfo: { remainingFraction: 0.6, resetTime: "2026-10-10T12:00:00Z" },
- },
- "claude-a": { quotaInfo: { remainingFraction: 0.2 } },
- },
- },
- });
- const limits = yield* probe;
- expect(limits.windows).toHaveLength(2);
- expect(limits.windows.find((window) => window.id === "gemini-quota")?.usedPercent).toBe(40);
- expect(
- limits.windows.every(
- (window) => window.kind === "other" && window.windowDurationMins === undefined,
- ),
- ).toBe(true);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("skips disabled and missing fractions and clamps valid percentages", () =>
- Effect.gen(function* () {
- const { probe } = yield* fixture({
- summary: {
- buckets: [
- { bucketId: "disabled", remainingFraction: 0, disabled: true },
- { bucketId: "missing", resetTime: "2026-10-10T12:00:00Z" },
- { bucketId: "gemini-5h", window: "5h", remainingFraction: 2, resetTime: "invalid" },
- ],
- },
- });
- expect((yield* probe).windows).toEqual([
- {
- id: "gemini-5h",
- kind: "session",
- label: "Gemini · 5-hour",
- usedPercent: 0,
- windowDurationMins: 300,
- },
- ]);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("returns a safe failure when OAuth refresh fails", () =>
- Effect.gen(function* () {
- const { probe } = yield* fixture({ tokenStatus: 401 });
- const limits = yield* probe;
- expect(limits.windows).toEqual([]);
- expect(limits.unavailable?.reason).toBe("probeFailed");
- expect(JSON.stringify(limits)).not.toMatch(/client-secret|refresh-a|access-token/);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("reads the native CLI's stored sign-in when acp_token.json is absent", () =>
- Effect.gen(function* () {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const { probe, tokenPath } = yield* fixture({ missingToken: true });
- // The 1.5.x CLI never writes acp_token.json; without a keyring it stores this file instead.
- yield* fs.writeFileString(
- path.join(path.dirname(tokenPath), "antigravity-oauth-token"),
- JSON.stringify({
- token: {
- access_token: "access-token",
- token_type: "Bearer",
- refresh_token: "refresh-a",
- expiry: "2099-01-01T00:00:00Z",
- expires_in: 3600,
- },
- auth_method: "consumer",
- id_token_email: "someone@example.com",
- }),
- );
- const limits = yield* probe;
- expect(limits.unavailable?.message).not.toBe(
- "Sign in with Google to see Antigravity limits.",
- );
- expect(limits.unavailable?.reason).not.toBe("unsupported");
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect("reads a Gemini Enterprise keyring sign-in and reports when it has expired", () =>
- Effect.gen(function* () {
- yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z")));
- const keyringSecret = (expiry: string) =>
- JSON.stringify({ token: { access_token: "access-token", refresh_token: "r", expiry } });
- // Google account instances keep their own sign-in; the shared entry belongs to another app.
- const personal = yield* fixture({
- missingToken: true,
- keyringSecret: keyringSecret("2026-10-09T14:00:00Z"),
- });
- expect((yield* personal.probe).unavailable?.message).toBe(
- "Sign in with Google to see Antigravity limits.",
- );
- expect(personal.requests).toEqual([]);
-
- const signedIn = yield* fixture({
- authMethod: "oauth-business",
- missingToken: true,
- userId: "google-user-1",
- keyringSecret: keyringSecret("2026-10-09T14:00:00.123456789+01:00"),
- });
- const limits = yield* signedIn.probe;
- expect(limits.unavailable).toBeUndefined();
- expect(limits.windows).toHaveLength(4);
- expect(signedIn.requests.some((request) => request.url.endsWith("/token"))).toBe(false);
-
- const expired = yield* fixture({
- authMethod: "oauth-business",
- missingToken: true,
- keyringSecret: keyringSecret("2026-10-09T12:00:30Z"),
- });
- expect((yield* expired.probe).unavailable?.reason).toBe("probeFailed");
- expect(expired.requests).toEqual([]);
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it.effect.runIf(HostProcess.Platform.defaultValue() === "win32")(
- "reads go-keyring's Windows credential target without changing it",
- (ctx) =>
- Effect.gen(function* () {
- // Never overwrite a real sign-in on a developer's machine.
- if (readWindowsCliCredential(HostProcess.Architecture.defaultValue())) return ctx.skip();
- yield* TestClock.setTime(
- DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-09T12:00:00Z")),
- );
- const { AsyncEntry } = yield* Effect.promise(() => import("@napi-rs/keyring"));
- // go-keyring writes the UTF-8 JSON at `:`.
- const target = AsyncEntry.withTarget("gemini:antigravity", "gemini", "antigravity");
- const stored = new TextEncoder().encode(
- JSON.stringify({
- token: { access_token: "access-token", expiry: "2026-10-09T14:00:00Z" },
- }),
- );
- yield* Effect.acquireRelease(
- Effect.promise(() => target.setSecret(stored)),
- () => Effect.promise(() => target.deleteCredential()),
- );
- const { probe } = yield* fixture({
- authMethod: "oauth-business",
- missingToken: true,
- nativeKeyring: true,
- });
- const limits = yield* probe;
- expect(limits.unavailable).toBeUndefined();
- expect(limits.windows).toHaveLength(4);
- expect(readWindowsCliCredential(HostProcess.Architecture.defaultValue())).toEqual(
- Buffer.from(stored),
- );
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-
- it("decodes go-keyring's macOS encodings", () => {
- const value = '{"token":{}}';
- const bytes = (text: string) => new TextEncoder().encode(text);
- expect(decodeGoKeyringSecret(bytes(value))).toBe(value);
- expect(
- decodeGoKeyringSecret(bytes(`go-keyring-base64:${Buffer.from(value).toString("base64")}`)),
- ).toBe(value);
- expect(
- decodeGoKeyringSecret(bytes(`go-keyring-encoded:${Buffer.from(value).toString("hex")}`)),
- ).toBe(value);
- });
-
- it.effect("does not make network requests for API keys or missing sign-ins", () =>
- Effect.gen(function* () {
- for (const options of [{ authMethod: "gemini-api-key" as const }, { missingToken: true }]) {
- const { probe, requests } = yield* fixture(options);
- expect((yield* probe).unavailable?.reason).toBe("unsupported");
- expect(requests).toEqual([]);
- }
- }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
- );
-});
diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts
deleted file mode 100644
index fadf2207c31f2..0000000000000
--- a/apps/server/src/provider/antigravityUsageLimits.ts
+++ /dev/null
@@ -1,505 +0,0 @@
-import * as NodeModule from "node:module";
-
-import type { AntigravitySettings, ServerProviderUsageWindow } from "@t3tools/contracts";
-import * as HostProcess from "@t3tools/shared/HostProcess";
-import * as Clock from "effect/Clock";
-import * as Digest from "effect/crypto/Digest";
-import * as DateTime from "effect/DateTime";
-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 Schema from "effect/Schema";
-import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
-
-import {
- makeUnavailableUsageLimits,
- makeUsageLimits,
-} from "@t3tools/provider-core/server/usageLimits";
-
-export function antigravityUserAgent(platform: NodeJS.Platform, architecture: NodeJS.Architecture) {
- return `antigravity/hub/2.24.0 (aidev_client; os_type=${platform}; arch=${architecture}; cl=963137146)`;
-}
-
-const DAILY_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
-const PROD_ENDPOINT = "https://cloudcode-pa.googleapis.com";
-// The ACP runtime meters consumer tiers on the daily host and GCP-terms tiers on prod.
-// The sign-in method stands in for the tier.
-const ENDPOINTS = {
- "oauth-personal": [DAILY_ENDPOINT, PROD_ENDPOINT],
- "oauth-business": [PROD_ENDPOINT, DAILY_ENDPOINT],
-};
-const SUMMARY_WINDOW_MINS = new Map([
- ["5h", 5 * 60],
- ["weekly", 7 * 24 * 60],
-]);
-const MANUAL_REDIRECT: RequestInit = { redirect: "manual" };
-const TokenFile = Schema.Struct({
- client_id: Schema.NonEmptyString,
- client_secret: Schema.NonEmptyString,
- refresh_token: Schema.NonEmptyString,
- project_id: Schema.optional(Schema.String),
-});
-// The 1.5.x CLI never writes acp_token.json: it keeps its sign-in in the OS keyring, or in
-// antigravity-oauth-token without one or when T3 bypasses the keyring. It stores no OAuth client, so T3 cannot refresh it.
-const CliToken = Schema.Struct({
- token: Schema.Struct({
- access_token: Schema.NonEmptyString,
- refresh_token: Schema.optional(Schema.String),
- expiry: Schema.optional(Schema.String),
- }),
-});
-const TokenResponse = Schema.Struct({
- access_token: Schema.NonEmptyString,
- expires_in: Schema.Number.check(Schema.isGreaterThan(0)),
-});
-const UserInfo = Schema.Struct({ id: Schema.NonEmptyString });
-const Quota = Schema.Struct({
- remainingFraction: Schema.optional(Schema.Number),
- resetTime: Schema.optional(Schema.String),
-});
-const Bucket = Schema.Struct({
- ...Quota.fields,
- bucketId: Schema.NonEmptyString,
- window: Schema.optional(Schema.String),
- displayName: Schema.optional(Schema.String),
- description: Schema.optional(Schema.String),
- disabled: Schema.optional(Schema.Boolean),
-});
-const Summary = Schema.Struct({
- groups: Schema.optional(
- Schema.Array(
- Schema.Struct({
- displayName: Schema.optional(Schema.String),
- buckets: Schema.optional(Schema.Array(Bucket)),
- }),
- ),
- ),
- buckets: Schema.optional(Schema.Array(Bucket)),
-});
-const Models = Schema.Struct({
- models: Schema.Record(
- Schema.String,
- Schema.Struct({
- modelProvider: Schema.optional(Schema.String),
- quotaInfo: Schema.optional(Quota),
- weeklyQuotaInfo: Schema.optional(Quota),
- }),
- ),
-});
-
-const decodeTokenFile = Schema.decodeEffect(Schema.fromJsonString(TokenFile));
-const decodeCliToken = Schema.decodeEffect(Schema.fromJsonString(CliToken));
-const decodeTokenResponse = Schema.decodeUnknownEffect(TokenResponse);
-const decodeUserInfo = Schema.decodeUnknownEffect(UserInfo);
-const decodeSummary = Schema.decodeUnknownEffect(Summary);
-const decodeModels = Schema.decodeUnknownEffect(Models);
-
-function iso(value: string | undefined): string | undefined {
- const parsed = value ? DateTime.make(value) : Option.none();
- return Option.isSome(parsed) ? DateTime.formatIso(parsed.value) : undefined;
-}
-
-function quotaWindow(
- id: string,
- label: string,
- quota: typeof Quota.Type,
- kind: ServerProviderUsageWindow["kind"] = "other",
- windowDurationMins?: number,
-): ServerProviderUsageWindow | undefined {
- if (quota.remainingFraction === undefined || !Number.isFinite(quota.remainingFraction)) {
- return undefined;
- }
- const resetsAt = iso(quota.resetTime);
- return {
- id,
- label,
- kind,
- usedPercent: (1 - Math.max(0, Math.min(1, quota.remainingFraction))) * 100,
- ...(resetsAt ? { resetsAt } : {}),
- ...(windowDurationMins === undefined ? {} : { windowDurationMins }),
- };
-}
-
-function summaryResetTime(
- bucket: typeof Bucket.Type,
- windowDurationMins: number | undefined,
- requestedAt: number,
-): string | undefined {
- // Untouched summary buckets report a rolling full-window reset.
- const untouched =
- bucket.remainingFraction === 1 &&
- bucket.description === undefined &&
- windowDurationMins !== undefined &&
- Math.abs(Date.parse(bucket.resetTime ?? "") - requestedAt - windowDurationMins * 60_000) <=
- 60_000;
- return untouched ? undefined : bucket.resetTime;
-}
-
-const sha256 = Effect.fnUntraced(function* (text: string) {
- const digest = yield* (yield* Digest.Digest).digest(
- Digest.sha256,
- new TextEncoder().encode(text),
- );
- return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
-});
-
-/** go-keyring stores UTF-8, which it prefixes and encodes on macOS. */
-export function decodeGoKeyringSecret(secret: ArrayLike): string {
- // The binding resolves a plain number array at runtime despite its Uint8Array type.
- const text = new TextDecoder().decode(Uint8Array.from(secret));
- if (text.startsWith("go-keyring-base64:")) {
- return Buffer.from(text.slice("go-keyring-base64:".length), "base64").toString("utf8");
- }
- if (text.startsWith("go-keyring-encoded:")) {
- return Buffer.from(text.slice("go-keyring-encoded:".length), "hex").toString("utf8");
- }
- return text;
-}
-
-class AntigravityKeyringError extends Schema.TaggedError()(
- "AntigravityKeyringError",
- { cause: Schema.Defect() },
-) {
- override get message(): string {
- return "Could not read the Antigravity sign-in from the system keyring.";
- }
-}
-
-// A single-executable server resolves packages on disk only through `require`.
-const requireExternal = NodeModule.createRequire(import.meta.url);
-
-/**
- * go-keyring's Windows target is `gemini:antigravity`; @napi-rs/keyring reads `antigravity.gemini`,
- * and its `withTarget` overwrites the target with an empty secret before reading.
- */
-export function readWindowsCliCredential(
- architecture: NodeJS.Architecture,
-): Uint8Array | undefined {
- // CREDENTIALW offsets and the pointers below are 64-bit.
- if (architecture !== "x64" && architecture !== "arm64") {
- throw new Error(`no credential access on ${architecture}`);
- }
- const { DataType, load, open } = requireExternal("ffi-rs") as typeof import("ffi-rs");
- open({ library: "t3-advapi32", path: "advapi32.dll" });
- open({ library: "t3-kernel32", path: "kernel32.dll" });
- const copy = (into: Buffer, from: bigint) =>
- load({
- library: "t3-kernel32",
- funcName: "RtlMoveMemory",
- retType: DataType.Void,
- paramsType: [DataType.U8Array, DataType.BigInt, DataType.BigInt],
- paramsValue: [into, from, BigInt(into.length)],
- });
- const out = Buffer.alloc(8);
- const read = load({
- library: "t3-advapi32",
- funcName: "CredReadW",
- retType: DataType.I32,
- // CRED_TYPE_GENERIC
- paramsType: [DataType.WString, DataType.U32, DataType.U32, DataType.U8Array],
- paramsValue: ["gemini:antigravity", 1, 0, out],
- errno: true as const,
- });
- if (read.value === 0) {
- // ERROR_NOT_FOUND
- if (read.errnoCode === 1168) return undefined;
- throw new Error(`CredReadW failed with Windows error ${read.errnoCode}`);
- }
- const credential = out.readBigUInt64LE();
- try {
- // CredentialBlobSize is a DWORD at 32 and CredentialBlob a pointer at 40.
- const header = Buffer.alloc(48);
- copy(header, credential);
- const size = header.readUInt32LE(32);
- if (size === 0) return undefined;
- const blob = Buffer.alloc(size);
- copy(blob, header.readBigUInt64LE(40));
- return blob;
- } finally {
- load({
- library: "t3-advapi32",
- funcName: "CredFree",
- retType: DataType.Void,
- paramsType: [DataType.BigInt],
- paramsValue: [credential],
- });
- }
-}
-
-// Loaded lazily: a native binding that fails to load must not take the provider down.
-const readCliKeyringSecret = (platform: NodeJS.Platform, architecture: NodeJS.Architecture) =>
- Effect.tryPromise({
- try: async () => {
- const secret =
- platform === "win32"
- ? readWindowsCliCredential(architecture)
- : await new (
- requireExternal("@napi-rs/keyring") as typeof import("@napi-rs/keyring")
- ).AsyncEntry("gemini", "antigravity").getSecret();
- return secret ? decodeGoKeyringSecret(secret) : undefined;
- },
- catch: (cause) => new AntigravityKeyringError({ cause }),
- });
-
-/** Keys an account by its Google ID, which matches across machines and hubs; refresh tokens do not. */
-export const antigravityAccountFingerprint = (userInfo: unknown) =>
- decodeUserInfo(userInfo).pipe(Effect.flatMap((info) => sha256(`google-account\0${info.id}`)));
-
-/** Windows from a `retrieveUserQuotaSummary` answer requested at `requestedAt`. */
-export const antigravitySummaryWindows = (response: unknown, requestedAt: number) =>
- decodeSummary(response).pipe(Effect.map((summary) => summaryWindows(summary, requestedAt)));
-
-function summaryWindows(summary: typeof Summary.Type, requestedAt: number) {
- const windows = new Map();
- const groups = summary.groups?.some((group) => group.buckets?.length)
- ? summary.groups
- : [{ buckets: summary.buckets }];
- for (const group of groups ?? []) {
- for (const bucket of group.buckets ?? []) {
- if (bucket.disabled) continue;
- // Argon and Carbon are metered separately from the default Gemini buckets.
- const family = bucket.bucketId.startsWith("gemini-argon-")
- ? group.displayName?.trim() || "Gemini Argon"
- : bucket.bucketId.startsWith("gemini-carbon-")
- ? group.displayName?.trim() || "Gemini Carbon"
- : bucket.bucketId.startsWith("gemini-")
- ? "Gemini"
- : bucket.bucketId.startsWith("3p-")
- ? "Claude & GPT (shared)"
- : group.displayName?.trim() || bucket.bucketId;
- const weekly = bucket.window === "weekly";
- const session = bucket.window === "5h";
- const windowDurationMins = SUMMARY_WINDOW_MINS.get(bucket.window ?? "");
- const window = quotaWindow(
- bucket.bucketId,
- `${family} · ${weekly ? "Weekly" : session ? "5-hour" : bucket.displayName?.trim() || "Quota"}`,
- { ...bucket, resetTime: summaryResetTime(bucket, windowDurationMins, requestedAt) },
- weekly ? "weekly" : session ? "session" : "other",
- windowDurationMins,
- );
- if (window) windows.set(window.id, window);
- }
- }
- return [...windows.values()];
-}
-
-/** Older accounts expose model quotas without a window length. Do not invent a reset cadence. */
-function modelWindows(models: typeof Models.Type) {
- const windows = new Map();
- for (const [modelId, model] of Object.entries(models.models)) {
- const family =
- model.modelProvider === "MODEL_PROVIDER_GOOGLE" || modelId.startsWith("gemini-")
- ? "Gemini"
- : model.modelProvider === "MODEL_PROVIDER_ANTHROPIC" || modelId.startsWith("claude-")
- ? "Claude"
- : model.modelProvider === "MODEL_PROVIDER_OPENAI" || modelId.startsWith("gpt-")
- ? "GPT"
- : undefined;
- if (!family) continue;
- for (const [suffix, quota] of [
- ["quota", model.quotaInfo],
- ["weekly", model.weeklyQuotaInfo],
- ] as const) {
- if (!quota) continue;
- const window = quotaWindow(
- `${family.toLowerCase()}-${suffix}`,
- `${family} · ${suffix === "weekly" ? "Weekly" : "Reported quota"}`,
- quota,
- suffix === "weekly" ? "weekly" : "other",
- suffix === "weekly" ? 7 * 24 * 60 : undefined,
- );
- if (!window) continue;
- const previous = windows.get(window.id);
- if (!previous || window.usedPercent > previous.usedPercent) windows.set(window.id, window);
- }
- }
- return [...windows.values()];
-}
-
-export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: {
- readonly profileDirectory: string;
- readonly authMethod: AntigravitySettings["authMethod"];
- readonly readKeyringSecret?: Effect.Effect;
-}) {
- const fs = yield* FileSystem.FileSystem;
- const path = yield* Path.Path;
- const client = (yield* HttpClient.HttpClient).pipe(HttpClient.filterStatusOk);
- const crypto = yield* Digest.Digest;
- const platform = yield* HostProcess.Platform;
- const architecture = yield* HostProcess.Architecture;
- const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json");
- const cliTokenPath = path.join(
- input.profileDirectory,
- "antigravity-acp",
- "antigravity-oauth-token",
- );
- const readKeyringSecret = input.readKeyringSecret ?? readCliKeyringSecret(platform, architecture);
- let cached:
- | { fingerprint: string; account: string; accessToken: string; expiresAt: number }
- | undefined;
- let generation = 0;
-
- const request = (request: HttpClientRequest.HttpClientRequest) =>
- client.execute(request).pipe(
- Effect.provideService(FetchHttpClient.RequestInit, MANUAL_REDIRECT),
- Effect.flatMap(HttpClientResponse.filterStatusOk),
- Effect.flatMap((response) => response.json),
- Effect.timeout("10 seconds"),
- );
- const read = Effect.gen(function* () {
- const startedGeneration = generation;
- const checkedAt = DateTime.formatIso(yield* DateTime.now);
- if (input.authMethod !== "oauth-personal" && input.authMethod !== "oauth-business") {
- return makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" });
- }
- const now = yield* Clock.currentTimeMillis;
- let accessToken: string;
- let account: string;
- let projectId: string | undefined;
- if (!(yield* fs.exists(tokenPath))) {
- cached = undefined;
- // Google account instances bypass the keyring, whose one entry every profile shares.
- const stored = (yield* fs.exists(cliTokenPath))
- ? yield* fs.readFileString(cliTokenPath)
- : input.authMethod === "oauth-business"
- ? yield* readKeyringSecret
- : undefined;
- if (stored === undefined) {
- return makeUnavailableUsageLimits({
- checkedAt,
- reason: "unsupported",
- message: "Sign in with Google to see Antigravity limits.",
- });
- }
- const { token } = yield* decodeCliToken(stored);
- if (!(Date.parse(token.expiry ?? "") > now + 60_000)) {
- return makeUnavailableUsageLimits({
- checkedAt,
- reason: "probeFailed",
- message:
- "Antigravity's saved sign-in has expired. Start an Antigravity turn to renew it, then refresh limits.",
- });
- }
- accessToken = token.access_token;
- account = yield* request(
- HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
- HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
- ),
- ).pipe(
- Effect.flatMap(antigravityAccountFingerprint),
- Effect.catch(() => sha256(`antigravity-cli\0${token.refresh_token || accessToken}`)),
- );
- } else {
- const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile));
- projectId = token.project_id;
- const fingerprint = yield* sha256(
- `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`,
- );
- if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) {
- cached = undefined;
- const refreshed = yield* request(
- HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe(
- HttpClientRequest.bodyUrlParams({
- client_id: token.client_id,
- client_secret: token.client_secret,
- refresh_token: token.refresh_token,
- grant_type: "refresh_token",
- }),
- ),
- ).pipe(Effect.flatMap(decodeTokenResponse));
- accessToken = refreshed.access_token;
- // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine.
- account = yield* request(
- HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
- HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }),
- ),
- ).pipe(
- Effect.flatMap(antigravityAccountFingerprint),
- Effect.orElseSucceed(() => fingerprint),
- );
- if (generation === startedGeneration) {
- cached = {
- fingerprint,
- account,
- accessToken,
- expiresAt: now + refreshed.expires_in * 1000,
- };
- }
- } else {
- accessToken = cached.accessToken;
- account = cached.account;
- }
- }
- const endpoints = ENDPOINTS[input.authMethod];
- // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins.
- const fetchWindows = Effect.fn("AntigravityUsageProbe.fetchWindows")(function* (
- operation: string,
- parse: (
- response: unknown,
- requestedAt: number,
- ) => Effect.Effect,
- ) {
- const responses = yield* Effect.forEach(
- endpoints,
- (endpoint) =>
- Effect.gen(function* () {
- // Capture each request after auth, so refresh latency does not widen the tolerance.
- const requestedAt = yield* Clock.currentTimeMillis;
- return yield* request(
- HttpClientRequest.post(`${endpoint}/v1internal:${operation}`).pipe(
- HttpClientRequest.setHeaders({
- Authorization: `Bearer ${accessToken}`,
- "User-Agent": antigravityUserAgent(platform, architecture),
- }),
- HttpClientRequest.bodyJsonUnsafe(projectId ? { project: projectId } : {}),
- ),
- ).pipe(
- Effect.flatMap((response) => parse(response, requestedAt)),
- Effect.orElseSucceed(() => []),
- );
- }),
- { concurrency: "unbounded" },
- );
- const windows = new Map();
- for (const window of responses.flat()) {
- if (!windows.has(window.id)) windows.set(window.id, window);
- }
- return [...windows.values()];
- });
- const summary = yield* fetchWindows("retrieveUserQuotaSummary", antigravitySummaryWindows);
- const windows = summary.length
- ? summary
- : yield* fetchWindows("fetchAvailableModels", (response) =>
- decodeModels(response).pipe(Effect.map(modelWindows)),
- );
- if (windows.length === 0) {
- return makeUnavailableUsageLimits({
- checkedAt,
- reason: "probeFailed",
- message: "Antigravity did not return usable quota information.",
- });
- }
- return { ...makeUsageLimits({ checkedAt, windows }), credentialFingerprint: account };
- });
- const probe = read.pipe(
- Effect.provideService(Digest.Digest, crypto),
- Effect.timeout("30 seconds"),
- Effect.catch(() =>
- Effect.gen(function* () {
- return makeUnavailableUsageLimits({
- checkedAt: DateTime.formatIso(yield* DateTime.now),
- reason: "probeFailed",
- message: "Could not read Antigravity limits. Refresh provider status to retry.",
- });
- }),
- ),
- );
- return {
- probe,
- clear: Effect.sync(() => {
- cached = undefined;
- generation++;
- }),
- };
-});
diff --git a/apps/server/src/testUtils/shardWeights.json b/apps/server/src/testUtils/shardWeights.json
index 86df1db6d7399..fbcfc63612d94 100644
--- a/apps/server/src/testUtils/shardWeights.json
+++ b/apps/server/src/testUtils/shardWeights.json
@@ -170,7 +170,6 @@
"src/provider/ProviderRegistry.test.ts": 0.7,
"src/provider/acp/AcpJsonRpcConnection.test.ts": 6.1,
"src/provider/acp/AcpSessionRuntime.processTree.test.ts": 1,
- "src/provider/antigravityUsageLimits.test.ts": 0.6,
"src/provider/providerCompatibility.test.ts": 1.6,
"src/provider/providerInstallation.test.ts": 1.1,
"src/provider/providerMaintenanceRunner.test.ts": 0.5,
diff --git a/apps/server/src/usage/UsageLimitSources.test.ts b/apps/server/src/usage/UsageLimitSources.test.ts
index 22321d4ad909f..26416247d6cc6 100644
--- a/apps/server/src/usage/UsageLimitSources.test.ts
+++ b/apps/server/src/usage/UsageLimitSources.test.ts
@@ -448,18 +448,6 @@ it.each([
model: "opus",
expected: at(1),
},
- {
- name: "a spent Gemini quota does not hold back Claude on Antigravity",
- accounts: [
- {
- driver: "antigravity",
- models: ["claude-opus-4-6-thinking"],
- windows: [spent("3p-5h", 1), spent("gemini-5h", 24)],
- },
- ],
- model: "claude-opus-4-6-thinking",
- expected: at(1),
- },
{
name: "a hub thinking suffix routes by its base model",
accounts: [
@@ -469,24 +457,6 @@ it.each([
model: "gpt-5.2(high)",
expected: at(3),
},
- {
- name: "a prefixed Gemini model is held back by the Gemini quota",
- accounts: [
- {
- driver: "antigravity",
- models: ["ag/gemini-3.1-pro-high"],
- windows: [spent("3p-5h", 1), spent("gemini-5h", 24)],
- },
- ],
- model: "ag/gemini-3.1-pro-high",
- expected: at(24),
- },
- {
- name: "an alias of unknown family is held back by every Antigravity quota",
- accounts: [{ driver: "antigravity", models: ["fast"], windows: [spent("gemini-5h", 24)] }],
- model: "fast",
- expected: at(24),
- },
{
name: "an own-driver account whose model list was unread still counts",
accounts: [
@@ -500,18 +470,6 @@ it.each([
model: "claude-sonnet-4-6",
expected: at(1),
},
- {
- name: "an Argon model waits only for the Argon quota",
- accounts: [
- {
- driver: "antigravity",
- models: ["gemini-4-argon-high"],
- windows: [spent("gemini-argon-5h", 2), spent("gemini-carbon-weekly", 96)],
- },
- ],
- model: "gemini-4-argon-high",
- expected: at(2),
- },
])("hub pool reset: $name", ({ accounts, model, expected }) => {
expect(
UsageLimitSources.hubPoolResetAt(
diff --git a/apps/server/src/usage/UsageLimitSources.ts b/apps/server/src/usage/UsageLimitSources.ts
index 21ca1fd39064f..e5d0d7f20bce1 100644
--- a/apps/server/src/usage/UsageLimitSources.ts
+++ b/apps/server/src/usage/UsageLimitSources.ts
@@ -12,7 +12,7 @@ import {
type UsageLimitSourceSnapshot,
} from "@t3tools/contracts";
import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
-import { antigravityWindowLimitsModel, hubRoutes } from "@t3tools/shared/usageLimits";
+import { hubRoutes } from "@t3tools/shared/usageLimits";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
@@ -324,10 +324,7 @@ export function hubPoolResetAt(
// An unread account may be the one still blocked, so its refill is unknown.
if (account.usageLimits.unavailable) return null;
const spent = account.usageLimits.windows.filter(
- (window) =>
- window.usedPercent >= 100 &&
- windowLimitsModel(window, model) &&
- (account.driver !== "antigravity" || antigravityWindowLimitsModel(window, model)),
+ (window) => window.usedPercent >= 100 && windowLimitsModel(window, model),
);
if (spent.length === 0) return null;
const resets = spent.map((window) => Date.parse(window.resetsAt ?? ""));
diff --git a/apps/server/src/usage/cliproxyApi.test.ts b/apps/server/src/usage/cliproxyApi.test.ts
index 56983c0684685..e25fd54e8b32d 100644
--- a/apps/server/src/usage/cliproxyApi.test.ts
+++ b/apps/server/src/usage/cliproxyApi.test.ts
@@ -1,5 +1,4 @@
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
-import * as HostProcess from "@t3tools/shared/HostProcess";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
@@ -485,17 +484,6 @@ describe("CLIProxyAPI built-in management API", () => {
}),
);
- const antigravitySummary = {
- buckets: [
- {
- bucketId: "gemini-weekly",
- window: "weekly",
- remainingFraction: 0.75,
- resetTime: "2099-01-01T00:00:00Z",
- },
- ],
- };
-
it.effect("reads an xAI account as Grok with Grok CLI headers", () =>
Effect.gen(function* () {
const test = fixture({
@@ -526,105 +514,13 @@ describe("CLIProxyAPI built-in management API", () => {
}),
);
- it.effect("reads an Antigravity summary and keys the account by its Google ID", () =>
- Effect.gen(function* () {
- const test = fixture({
- accounts: [
- {
- id: "antigravity-g@example.com.json",
- auth_index: "g",
- provider: "antigravity",
- email: "g@example.com",
- project_id: "project-7",
- },
- ],
- upstream: (request) => ({
- status: 200,
- body: request.url?.endsWith("/userinfo") ? { id: "google-42" } : antigravitySummary,
- }),
- });
- const [account] = yield* (yield* test.api).readAccounts(config);
- expect(account?.driver).toBe("antigravity");
- expect(account?.email).toBeUndefined();
- expect(account?.usageLimits.credentialFingerprint).toBe(
- // sha256("google-account\0google-42"), as a local Antigravity probe reports it.
- "136d4952771fd67a3600053f37492cbd05828712e0b1c89ebab03d4c22ab6554",
- );
- expect(account?.usageLimits.windows).toMatchObject([
- { id: "gemini-weekly", kind: "weekly", usedPercent: 25 },
- ]);
- const summary = test.requests.find((request) => request.body?.method === "POST")?.body;
- expect(summary?.url).toBe(
- "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary",
- );
- expect(summary?.data).toBe(encodeJson({ project: "project-7" }));
- expect(summary).toMatchObject({
- auth_index: "g",
- method: "POST",
- header: {
- Authorization: "Bearer $TOKEN$",
- "Content-Type": "application/json",
- "User-Agent":
- "antigravity/hub/2.24.0 (aidev_client; os_type=linux; arch=x64; cl=963137146)",
- },
- });
- const identityCalls = test.requests.filter((request) =>
- request.body?.url?.endsWith("/userinfo"),
- );
- expect(identityCalls).toHaveLength(1);
- expect(identityCalls[0]?.body).toMatchObject({
- method: "GET",
- url: "https://www.googleapis.com/oauth2/v2/userinfo",
- header: { Authorization: "Bearer $TOKEN$" },
- });
- }).pipe(
- Effect.provideService(HostProcess.Platform, "linux"),
- Effect.provideService(HostProcess.Architecture, "x64"),
- ),
- );
-
- it.effect("keeps Antigravity limits and listing email when its identity read fails", () =>
- Effect.gen(function* () {
- const test = fixture({
- accounts: [
- {
- id: "antigravity.json",
- auth_index: "g",
- provider: "antigravity",
- email: "g@example.com",
- project_id: "project-7",
- },
- ],
- upstream: (request) =>
- request.url?.endsWith("/userinfo")
- ? { status: 403, body: { error: "denied" } }
- : {
- status: 200,
- body: antigravitySummary,
- },
- });
- const result = yield* (yield* test.api).readAccounts(config);
- expect(result).toHaveLength(1);
- const [account] = result;
- expect(account).toMatchObject({ driver: "antigravity", email: "g@example.com" });
- expect(account?.usageLimits.credentialFingerprint).toBeUndefined();
- expect(account?.usageLimits.unavailable).toBeUndefined();
- expect(account?.usageLimits.windows).toMatchObject([
- { id: "gemini-weekly", kind: "weekly", usedPercent: 25 },
- ]);
- }),
- );
-
it.effect.each([
{ name: "a refused xAI call", provider: "xai", status: 403, body: { error: "denied" } },
{ name: "a malformed xAI answer", provider: "xai", status: 200, body: { config: "x" } },
- { name: "a refused Antigravity call", provider: "antigravity", status: 401, body: {} },
- { name: "a malformed Antigravity answer", provider: "antigravity", status: 200, body: [] },
- { name: "an empty Antigravity summary", provider: "antigravity", status: 200, body: {} },
])("reports $name as unreadable", ({ provider, status, body }) =>
Effect.gen(function* () {
const test = fixture({
- accounts: [{ id: `${provider}.json`, auth_index: "a", provider, project_id: "project-7" }],
+ accounts: [{ id: `${provider}.json`, auth_index: "a", provider }],
upstream: () => ({ status, body }),
});
const [account] = yield* (yield* test.api).readAccounts(config);
@@ -632,33 +528,13 @@ describe("CLIProxyAPI built-in management API", () => {
}),
);
- it.effect.each([undefined, "", " "])(
- "rejects a missing or blank Antigravity project (%s) before upstream calls",
- (project_id) =>
- Effect.gen(function* () {
- const test = fixture({
- accounts: [
- {
- id: "antigravity.json",
- auth_index: "a",
- provider: "antigravity",
- ...(project_id === undefined ? {} : { project_id }),
- },
- ],
- });
- const [account] = yield* (yield* test.api).readAccounts(config);
- expect(account?.usageLimits.unavailable?.reason).toBe("probeFailed");
- expect(test.requests.map((request) => request.path)).not.toContain(
- "/v0/management/api-call",
- );
- }),
- );
-
it.effect("skips accounts of providers the hub table does not know", () =>
Effect.gen(function* () {
const test = fixture({
accounts: [
{ id: "kiro.json", auth_index: "k", provider: "kiro", email: "k@example.com" },
+ // Antigravity only allows ACP clients, so its internal quota API is never called.
+ { id: "antigravity.json", auth_index: "g", provider: "antigravity", project_id: "p" },
{ ...accounts[0]!, provider: "claude" },
],
upstream: () => ({ status: 200, body: { five_hour: { utilization: 1, resets_at: null } } }),
@@ -666,6 +542,7 @@ describe("CLIProxyAPI built-in management API", () => {
const result = yield* (yield* test.api).readAccounts(config);
expect(result.map((account) => account.driver)).toEqual(["claudeAgent"]);
expect(test.requests.map((request) => request.body?.auth_index)).not.toContain("k");
+ expect(test.requests.map((request) => request.body?.auth_index)).not.toContain("g");
}),
);
diff --git a/apps/server/src/usage/cliproxyApi.ts b/apps/server/src/usage/cliproxyApi.ts
index af80091c3eb41..6393da96d1c3e 100644
--- a/apps/server/src/usage/cliproxyApi.ts
+++ b/apps/server/src/usage/cliproxyApi.ts
@@ -5,7 +5,6 @@ import {
type UsageLimitSourceAccount,
type UsageLimitSourceConfig,
} from "@t3tools/contracts";
-import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Cause from "effect/Cause";
import * as Digest from "effect/crypto/Digest";
import * as DateTime from "effect/DateTime";
@@ -23,15 +22,7 @@ import {
import { codexPlanLabel } from "../provider/CodexProvider.ts";
import { codexRateLimitsToLimits } from "../provider/codexUsageLimits.ts";
import { claudeUsageResponseToLimits } from "../provider/claudeUsageLimits.ts";
-import {
- antigravityAccountFingerprint,
- antigravitySummaryWindows,
- antigravityUserAgent,
-} from "../provider/antigravityUsageLimits.ts";
-import {
- makeUnavailableUsageLimits,
- makeUsageLimits,
-} from "@t3tools/provider-core/server/usageLimits";
+import { makeUnavailableUsageLimits } from "@t3tools/provider-core/server/usageLimits";
/** A hub with its management key already read from wherever the setting keeps it. */
export interface CliproxyHub {
@@ -45,7 +36,6 @@ const AuthFile = Schema.Struct({
provider: Schema.String,
email: Schema.optional(Schema.String),
disabled: Schema.optional(Schema.Boolean),
- project_id: Schema.optional(Schema.String),
id_token: Schema.optional(
Schema.Struct({
chatgpt_account_id: Schema.optional(Schema.String),
@@ -128,7 +118,6 @@ const decodeCreditList = Schema.decodeUnknownEffect(Schema.fromJsonString(Credit
const decodeClaudeUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaudeUsage));
const decodeCodexUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(CodexUsage));
const decodeGrokUsage = Schema.decodeUnknownEffect(Schema.fromJsonString(GrokUsageResponse));
-const decodeJson = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const isUsageLimitSourceError = Schema.is(UsageLimitSourceError);
// Extra CAs can fix untrusted chains; expiry/hostname failures report codes only.
@@ -206,16 +195,12 @@ type HubCall = (
type HubReading = Omit;
interface HubProvider {
readonly driver: ProviderDriverKind;
- readonly header: (
- account: AuthFile,
- platform: NodeJS.Platform,
- architecture: NodeJS.Architecture,
- ) => Record;
+ readonly header: (account: AuthFile) => Record;
readonly read: (input: {
readonly account: AuthFile;
readonly call: HubCall;
readonly checkedAt: string;
- }) => Effect.Effect;
+ }) => Effect.Effect;
}
const listedIdentity = (account: AuthFile) => ({
@@ -296,8 +281,6 @@ const CODEX_HUB: HubProvider = {
};
const GROK_CLI_VERSION = "1.0.77";
-const ANTIGRAVITY_SUMMARY_URL =
- "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary";
// Keyed by the auth-files `provider`; accounts of any other provider are skipped.
const HUB_PROVIDERS = new Map([
@@ -364,49 +347,11 @@ const HUB_PROVIDERS = new Map([
}),
},
],
- [
- "antigravity",
- {
- driver: ProviderDriverKind.make("antigravity"),
- header: (_account, platform, architecture) => ({
- Authorization: "Bearer $TOKEN$",
- "Content-Type": "application/json",
- "User-Agent": antigravityUserAgent(platform, architecture),
- }),
- read: Effect.fnUntraced(function* ({ account, call, checkedAt }) {
- const project = account.project_id?.trim();
- if (!project) {
- return yield* new UsageLimitSourceError({ detail: "No Antigravity project reported." });
- }
- const requestedAt = DateTime.toEpochMillis(yield* DateTime.now);
- const summary = yield* call(ANTIGRAVITY_SUMMARY_URL, { project });
- const windows = yield* antigravitySummaryWindows(yield* decodeJson(summary), requestedAt);
- if (windows.length === 0) {
- return yield* new UsageLimitSourceError({ detail: "No Antigravity quota reported." });
- }
- // Local Antigravity reports no e-mail, so the Google account fingerprint is what pools the two.
- const fingerprint = yield* call("https://www.googleapis.com/oauth2/v2/userinfo").pipe(
- Effect.flatMap(decodeJson),
- Effect.flatMap(antigravityAccountFingerprint),
- Effect.option,
- );
- const usageLimits = makeUsageLimits({ checkedAt, windows });
- return Option.match(fingerprint, {
- onNone: () => ({ ...listedIdentity(account), usageLimits }),
- onSome: (credentialFingerprint) => ({
- usageLimits: { ...usageLimits, credentialFingerprint },
- }),
- });
- }),
- },
- ],
]);
export const makeCliproxyApi = Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const digest = yield* Digest.Digest;
- const platform = yield* HostProcess.Platform;
- const architecture = yield* HostProcess.Architecture;
const management = Effect.fn("CliproxyApi.management")(function* (
hub: CliproxyHub,
@@ -486,10 +431,8 @@ export const makeCliproxyApi = Effect.gen(function* () {
provider: HubProvider,
) {
const checkedAt = DateTime.formatIso(yield* DateTime.now);
- const call: HubCall = (url, data) =>
- apiCall(hub, account, provider.header(account, platform, architecture), url, data);
+ const call: HubCall = (url, data) => apiCall(hub, account, provider.header(account), url, data);
const reading = yield* provider.read({ account, call, checkedAt }).pipe(
- Effect.provideService(Digest.Digest, digest),
Effect.catch((error) =>
Effect.succeed({
...listedIdentity(account),
@@ -561,7 +504,7 @@ export const makeCliproxyApi = Effect.gen(function* () {
const body = yield* apiCall(
hub,
account,
- CODEX_HUB.header(account, platform, architecture),
+ CODEX_HUB.header(account),
`${CREDIT_URL}/consume`,
{
redeem_request_id: yield* creditRedeemRequestId(
diff --git a/apps/web/src/components/chat/ThreadDetailsUsage.logic.ts b/apps/web/src/components/chat/ThreadDetailsUsage.logic.ts
index d968638ed65f9..45cbb68ea61d3 100644
--- a/apps/web/src/components/chat/ThreadDetailsUsage.logic.ts
+++ b/apps/web/src/components/chat/ThreadDetailsUsage.logic.ts
@@ -6,7 +6,6 @@ import {
type UsageLimitSourceSnapshots,
} from "@t3tools/contracts";
import {
- antigravityWindowLimitsModel,
collectLimitAccounts,
collectLimitPools,
collectProviderUsageLimits,
@@ -83,19 +82,7 @@ function hubPool(
const routes = hubRoutes(sources, driver, model);
const routed = sources.map((source) => ({
...source,
- accounts: source.accounts.filter(routes).map((account) =>
- account.driver === "antigravity"
- ? {
- ...account,
- usageLimits: {
- ...account.usageLimits,
- windows: account.usageLimits.windows.filter((window) =>
- antigravityWindowLimitsModel(window, model),
- ),
- },
- }
- : account,
- ),
+ accounts: source.accounts.filter(routes),
}));
const readable = routed
.flatMap((source) => source.accounts)
diff --git a/docs/user/usage.md b/docs/user/usage.md
index d7a921454f54e..6681bd34ea402 100644
--- a/docs/user/usage.md
+++ b/docs/user/usage.md
@@ -183,8 +183,8 @@ using a proxy through `ANTHROPIC_AUTH_TOKEN`.
To see pooled accounts, open **Settings → Providers → Usage providers → Add hub**. Choose the
environment that will connect to the hub and enter its URL and management key.
-The hub's Codex, Claude, xAI (shown as Grok) and Antigravity accounts appear under **Usage → Limits**;
-accounts for other providers are not read. Codex accounts show banked reset credits; select an
+The hub's Codex, Claude and xAI (shown as Grok) accounts appear under **Usage → Limits**;
+accounts for other providers, including Antigravity, are not read. Codex accounts show banked reset credits; select an
account and choose **Use reset** to redeem one. No hub plugin is required.
This connection supplies usage information; configure
diff --git a/knip.jsonc b/knip.jsonc
index 6f2a40fe94473..dafe7ba4fd21e 100644
--- a/knip.jsonc
+++ b/knip.jsonc
@@ -76,7 +76,6 @@
"ignoreDependencies": [
"@effect/platform-node-shared",
"@t3tools/web",
- "@napi-rs/keyring",
"ffi-rs",
"transcribe-cpp",
],
diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts
index 2aab03105b5d9..b2ce03d006418 100644
--- a/packages/shared/src/usageLimits.test.ts
+++ b/packages/shared/src/usageLimits.test.ts
@@ -130,9 +130,6 @@ describe("new thread model fallback", () => {
["cursor", ["autoPercentUsed"], "claude-opus-5-5", false, undefined, undefined],
["cursor", ["autoPercentUsed"], "composer-2.5", false, undefined, undefined],
["cursor", ["autoPercentUsed", "apiPercentUsed"], "composer-2.5", true, undefined, undefined],
- ["antigravity", ["gemini-weekly"], "claude-opus-5-5", false, undefined, undefined],
- ["antigravity", ["3p-weekly"], "claude-opus-5-5", true, undefined, undefined],
- ["antigravity", ["gemini-weekly"], "antigravity-default", true, undefined, undefined],
["codex", ["individual"], "gpt-5.5", true, undefined, undefined],
["opencode", ["go_weekly"], "opencode/big-pickle", false, undefined, undefined],
["opencode", ["go_weekly"], "opencode-go/big-pickle", true, undefined, undefined],
diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts
index 77710a8d5852d..f890298d82260 100644
--- a/packages/shared/src/usageLimits.ts
+++ b/packages/shared/src/usageLimits.ts
@@ -48,18 +48,6 @@ export function exhaustedUsageWindow(
const auto = exhausted.find((window) => window.id === "autoPercentUsed");
return /^(auto|default|grok|composer)/.test(model) ? auto && api : api;
}
- case "antigravity": {
- const family = model.match(/^(gemini|claude|gpt)-/)?.[1];
- return exhausted.find((window) => {
- const pool = window.id.match(/^(gemini|claude|gpt|3p)-/)?.[1];
- return (
- pool === undefined ||
- family === undefined ||
- pool === family ||
- (pool === "3p" && (family === "claude" || family === "gpt"))
- );
- });
- }
case "codex": {
// Seat-based plans spend credits only past their plan windows, so the credit cap blocks only plans without them.
const hasPlanWindows = windows.some(
@@ -554,16 +542,6 @@ function hasDuplicateCursorTotal(pool: LimitPool): boolean {
}
export function displayLimitWindows(pool: LimitPool) {
- if (pool.driver === "antigravity") {
- return [...pool.windows].sort(
- (left, right) =>
- Number(!left.id.startsWith("gemini-")) - Number(!right.id.startsWith("gemini-")) ||
- left.id
- .replace(/-(5h|weekly|quota)$/, "")
- .localeCompare(right.id.replace(/-(5h|weekly|quota)$/, "")) ||
- WINDOW_KIND_ORDER[left.kind] - WINDOW_KIND_ORDER[right.kind],
- );
- }
if (pool.driver !== "cursor") return pool.windows;
const hasAuto = pool.windows.some((window) => window.id === "autoPercentUsed");
const hasApi = pool.windows.some((window) => window.id === "apiPercentUsed");
@@ -934,24 +912,6 @@ export function instanceHubs(
return endpoint === undefined ? [] : sources.filter((source) => source.origin === endpoint);
}
-// Antigravity meters Gemini Argon, Gemini Carbon, other Gemini, and Claude/GPT models apart.
-function antigravityQuotaFamily(id: string) {
- if (!id.startsWith("gemini")) return "shared";
- return id.includes("argon") ? "argon" : id.includes("carbon") ? "carbon" : "gemini";
-}
-
-/** Each Antigravity quota blocks only the models it meters. */
-export function antigravityWindowLimitsModel(
- window: Pick,
- model: string | null,
-): boolean {
- // A hub can prefix model ids, such as "ag/gemini-3.1-pro".
- const base = model?.slice(model.lastIndexOf("/") + 1);
- // An alias such as "fast" may route to either quota, so both hold it back.
- if (base === undefined || !/^(gemini|claude|gpt)/.test(base)) return true;
- return antigravityQuotaFamily(window.id) === antigravityQuotaFamily(base);
-}
-
/** The hub accounts that serve a model: those that list it, else every account of the driver. */
export function hubRoutes(
sources: UsageLimitSourceSnapshots,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fe5737b876011..9d58d22dad3de 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -877,9 +877,6 @@ importers:
'@muse-code/sdk':
specifier: 1.4.6
version: 1.4.6(patch_hash=7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101)(@types/node@24.12.4)
- '@napi-rs/keyring':
- specifier: ^1.3.0
- version: 1.3.0
'@t3tools/issue-tracker-linear':
specifier: workspace:*
version: link:../../packages/issue-tracker-linear
From 9a3ad0bec2eec307b638309570159f29ff50905d Mon Sep 17 00:00:00 2001
From: Vir Khanna <102773390+v-khanna@users.noreply.github.com>
Date: Wed, 25 Nov 2026 13:26:56 -0600
Subject: [PATCH 088/238] fix(web): recognize composerEmpty in keybinding
settings (#42986)
Co-authored-by: Julius Marminge
---
.../settings/KeybindingsSettings.logic.test.ts | 13 +++++++++----
.../settings/KeybindingsSettings.logic.ts | 1 +
2 files changed, 10 insertions(+), 4 deletions(-)
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
index 4d940f657901d..f02d934fa94cf 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts
@@ -328,10 +328,15 @@ describe("KeybindingsSettings.logic", () => {
},
},
});
- const previewOpenDraft = parseWhenExpressionDraft("previewOpen && !previewFocus");
- assert(previewOpenDraft.ok);
- expect(unknownWhenVariables(previewOpenDraft.value)).toEqual([]);
- expect(buildWhenVariableOptions()).toContain("previewOpen");
+ for (const [expression, condition] of [
+ ["previewOpen && !previewFocus", "previewOpen"],
+ ["composerFocus && turnRunning && composerEmpty", "composerEmpty"],
+ ] as const) {
+ const draft = parseWhenExpressionDraft(expression);
+ assert(draft.ok);
+ expect(unknownWhenVariables(draft.value)).toEqual([]);
+ expect(buildWhenVariableOptions()).toContain(condition);
+ }
expect(parseWhenExpressionDraft("editorFocus &&")).toEqual({
ok: false,
message: "Use variables with !, &&, ||, and parentheses.",
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
index 32c6a87fd0a37..0654c187f3f93 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
@@ -71,6 +71,7 @@ const CORE_WHEN_VARIABLES = [
"terminalFocus",
"terminalOpen",
"previewOpen",
+ "composerEmpty",
"isWeb",
"isDesktop",
"true",
From 74b5186f2ed99a60bd14664c1633e524aad6a94b Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 20:27:10 +0100
Subject: [PATCH 089/238] fix(terminal): finish shell startup after disconnect
(#42940)
Co-authored-by: Julius Marminge
---
.../src/terminal/Manager.startup.test.ts | 190 ++++++++++++++++++
apps/server/src/terminal/Manager.test.ts | 30 +++
apps/server/src/terminal/Manager.ts | 168 +++++++++++-----
.../src/terminal/NodePtyAdapter.test.ts | 44 ++++
apps/server/src/terminal/NodePtyAdapter.ts | 30 ++-
5 files changed, 393 insertions(+), 69 deletions(-)
create mode 100644 apps/server/src/terminal/Manager.startup.test.ts
diff --git a/apps/server/src/terminal/Manager.startup.test.ts b/apps/server/src/terminal/Manager.startup.test.ts
new file mode 100644
index 0000000000000..54b8382b13a0c
--- /dev/null
+++ b/apps/server/src/terminal/Manager.startup.test.ts
@@ -0,0 +1,190 @@
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- this test substitutes real stalled children for selected probes.
+import * as NodeChildProcess from "node:child_process";
+import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { it } from "@effect/vitest";
+import { DEFAULT_TERMINAL_ID, type TerminalSessionSnapshot } from "@t3tools/contracts";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import type { PtyExitEvent, PtyProcess } from "@t3tools/shared/PtyAdapter";
+import { SpawnExecutableResolution } from "@t3tools/shared/shell";
+import * as Deferred from "effect/Deferred";
+import * as Effect from "effect/Effect";
+import * as Fiber from "effect/Fiber";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Path from "effect/Path";
+import * as TestClock from "effect/testing/TestClock";
+import { expect, vi } from "vite-plus/test";
+import * as ProcessRunner from "../processRunner.ts";
+import { makeWithOptions } from "./Manager.ts";
+
+const node = Layer.mergeAll(NodeServices.layer, NodeCrypto.layer);
+const services = Layer.mergeAll(node, ProcessRunner.layer.pipe(Layer.provide(node)));
+
+vi.mock("node:child_process", { spy: true });
+
+function fakePtyProcess(): PtyProcess {
+ const exitListeners = new Set<(event: PtyExitEvent) => void>();
+ return {
+ pid: 42,
+ write: () => {},
+ resize: () => {},
+ kill: () => {
+ for (const listener of exitListeners) listener({ exitCode: 0, signal: null });
+ },
+ onData: () => () => {},
+ onExit: (listener) => {
+ exitListeners.add(listener);
+ return () => exitListeners.delete(listener);
+ },
+ };
+}
+
+it.layer(services, { excludeTestServices: true })("terminal startup deadlines", (it) => {
+ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
+ "starts local fallbacks while concurrent shell probes time out",
+ () =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-terminal-probes-" });
+ const first = yield* Deferred.make();
+ const second = yield* Deferred.make();
+ const stalled: NodeChildProcess.ChildProcess[] = [];
+ const configured = path.join(root, "configured");
+ const preferred = path.join(root, "preferred");
+ const fallback = path.join(root, "local-shell");
+ yield* fs.writeFileString(fallback, "#!/bin/sh\nexit 0\n");
+ yield* fs.chmod(fallback, 0o755);
+ const real = yield* Effect.promise(() =>
+ vi.importActual("node:child_process"),
+ );
+ const probe = vi.mocked(NodeChildProcess.execFile);
+ yield* Effect.addFinalizer(() => Effect.sync(() => probe.mockRestore()));
+ probe.mockImplementation((file, args, options, callback) => {
+ if (!args?.includes(configured) && !args?.includes(preferred)) {
+ return real.execFile(file, args, options, callback);
+ }
+ const child = real.execFile(file, ["-c", "exec /bin/sleep 60"], options, callback);
+ stalled.push(child);
+ if (stalled.length === 2) Deferred.doneUnsafe(first, Effect.void);
+ if (stalled.length === 4) Deferred.doneUnsafe(second, Effect.void);
+ return child;
+ });
+ const manager = yield* makeWithOptions({
+ logsDir: path.join(root, "logs"),
+ env: { T3CODE_TERMINAL_SHELL: configured, SHELL: fallback },
+ shellResolver: () => preferred,
+ ptyAdapter: { spawn: () => Effect.sync(fakePtyProcess) },
+ });
+ const openings = yield* Effect.forEach(["first", "second"], (threadId) =>
+ Effect.gen(function* () {
+ const cwd = path.join(root, threadId);
+ yield* fs.makeDirectory(cwd);
+ return yield* manager
+ .open({ cwd, threadId, terminalId: DEFAULT_TERMINAL_ID })
+ .pipe(Effect.forkChild({ startImmediately: true }));
+ }),
+ );
+ yield* Deferred.await(first);
+ yield* TestClock.adjust("2 seconds");
+ yield* Deferred.await(second);
+ yield* TestClock.adjust("2 seconds");
+
+ const sessions = yield* Effect.forEach(openings, Fiber.join);
+ expect(sessions.map((session) => session.status)).toEqual(["running", "running"]);
+ const shells = yield* Effect.forEach(sessions, (session) => manager.getShell(session));
+ expect(shells).toEqual([fallback, fallback]);
+ expect(stalled.every((child) => child.killed)).toBe(true);
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+
+ it.effect.each([
+ { name: "reports a timeout when no shell resolves", stalled: "lookup", fallback: false },
+ { name: "starts a fallback shell after a lookup stalls", stalled: "lookup", fallback: true },
+ {
+ name: "keeps the original PATH when the managed scan stalls",
+ stalled: "scan",
+ fallback: true,
+ },
+ ] as const)("$name", ({ stalled, fallback }) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-terminal-startup-" });
+ const cacheDir = path.join(cwd, "cache");
+ const receiptsDir = path.join(cacheDir, "acp-registry", "package-installs");
+ const waiting = yield* Deferred.make();
+ const spawned: Array<{ shell: string; path: string | undefined }> = [];
+ let lookupRecovered = false;
+ const manager = yield* makeWithOptions({
+ logsDir: path.join(cwd, "logs"),
+ env: { PATH: "/usr/bin" },
+ shellResolver: () => "local-shell",
+ ...(stalled === "scan"
+ ? { managedBinaryCacheDir: cacheDir, managedBinaryToolsDir: path.join(cwd, "tools") }
+ : {}),
+ ptyAdapter: {
+ spawn: (input) =>
+ Effect.sync(() => {
+ spawned.push({ shell: input.shell, path: input.env.PATH });
+ return fakePtyProcess();
+ }),
+ },
+ }).pipe(
+ Effect.provideService(HostProcess.Platform, "linux"),
+ Effect.provideService(SpawnExecutableResolution, (command) => {
+ if (stalled === "lookup" && command === "stalled-shell" && !lookupRecovered) {
+ Deferred.doneUnsafe(waiting, Effect.void);
+ return new Promise(() => {});
+ }
+ return command === "local-shell" && (fallback || lookupRecovered) ? command : undefined;
+ }),
+ Effect.provideService(FileSystem.FileSystem, {
+ ...fs,
+ readDirectory: (directory, options) =>
+ stalled === "scan" && directory === receiptsDir
+ ? Deferred.succeed(waiting, undefined).pipe(Effect.andThen(Effect.never))
+ : fs.readDirectory(directory, options),
+ }),
+ );
+
+ const input = {
+ cwd,
+ threadId: "thread",
+ terminalId: DEFAULT_TERMINAL_ID,
+ ...(stalled === "lookup" ? { env: { T3CODE_TERMINAL_SHELL: "stalled-shell" } } : {}),
+ };
+ const opening = yield* manager.open(input).pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Deferred.await(waiting);
+ const disconnect = yield* Fiber.interrupt(opening).pipe(
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* TestClock.adjust("16 seconds");
+ yield* Fiber.join(disconnect);
+
+ const snapshots: TerminalSessionSnapshot[] = [];
+ const stop = yield* manager.attachStream(input, (event) =>
+ Effect.sync(() => {
+ if (event.type === "snapshot") snapshots.push(event.snapshot);
+ }),
+ );
+ stop();
+
+ if (fallback) {
+ expect(snapshots).toEqual([expect.objectContaining({ status: "running" })]);
+ expect(spawned).toEqual([{ shell: "local-shell", path: "/usr/bin" }]);
+ } else {
+ expect(snapshots).toEqual([
+ expect.objectContaining({
+ status: "error",
+ error: "Terminal shell preparation timed out.",
+ }),
+ ]);
+ expect(spawned).toEqual([]);
+ lookupRecovered = true;
+ expect((yield* manager.open(input)).status).toBe("running");
+ }
+ }).pipe(Effect.provide(TestClock.layer())),
+ );
+});
diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts
index 649eb097a654f..1b88e4ab310f5 100644
--- a/apps/server/src/terminal/Manager.test.ts
+++ b/apps/server/src/terminal/Manager.test.ts
@@ -3325,6 +3325,36 @@ it.layer(
}),
);
+ it.effect("attaches to a working shell after the original open is interrupted", () =>
+ Effect.gen(function* () {
+ const ptyAdapter = new GatedPtyAdapter();
+ const { manager } = yield* createManager(5, { ptyAdapter });
+ const input = openInput();
+ const gate = {
+ spawning: yield* Deferred.make(),
+ release: yield* Deferred.make(),
+ };
+ ptyAdapter.gate = gate;
+ const opening = yield* manager.open(input).pipe(Effect.forkChild({ startImmediately: true }));
+ yield* Deferred.await(gate.spawning);
+ const cancelled = yield* Fiber.interrupt(opening).pipe(
+ Effect.forkChild({ startImmediately: true }),
+ );
+ yield* Deferred.succeed(gate.release, undefined);
+ yield* Fiber.join(cancelled);
+
+ const events: TerminalAttachStreamEvent[] = [];
+ const stop = yield* manager.attachStream(input, (event) =>
+ Effect.sync(() => {
+ events.push(event);
+ }),
+ );
+ stop();
+ const first = events[0];
+ expect(first?.type === "snapshot" ? first.snapshot.status : first?.type).toBe("running");
+ }),
+ );
+
it.effect("resyncs bounded history and follows close/reopen across a stalled stream", () =>
Effect.gen(function* () {
const ptyAdapter = new GatedPtyAdapter();
diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts
index 76b39f86372b8..93f8020ce65b0 100644
--- a/apps/server/src/terminal/Manager.ts
+++ b/apps/server/src/terminal/Manager.ts
@@ -1,5 +1,7 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off -- Effect's Crypto digest is effectful; a sync hash keeps historyPath a plain function.
import * as NodeCrypto from "node:crypto";
+// @effect-diagnostics-next-line nodeBuiltinImport:off -- an aborted executable probe must not wait for the child to exit a stalled mount.
+import * as NodeChildProcess from "node:child_process";
import { withWorkspaceLease } from "../workspace/workspaceLease.ts";
import {
@@ -51,6 +53,7 @@ import { SpawnExecutableResolution, mergePathEntries } from "@t3tools/shared/she
import { acpRegistryManagedBinaryDirectories } from "@t3tools/provider-acp-registry/server";
import { getTerminalLabel } from "@t3tools/shared/terminalLabels";
+import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
@@ -109,6 +112,9 @@ const MAX_HISTORY_CHUNK_LENGTH = 16 * 1024;
const DEFAULT_PERSIST_DEBOUNCE_MS = 250;
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
const MAX_SUBPROCESS_POLL_INTERVAL_MS = 60_000;
+const SHELL_PREPARATION_TIMEOUT = "15 seconds";
+// A short per-candidate limit bounds the fallback search across the finite candidate list.
+const SHELL_LOOKUP_TIMEOUT = "2 seconds";
// `ps` and WMI can take seconds on a loaded host and their tables are still
// valid then; the timeout only ends a query that is truly stuck.
const PROCESS_TABLE_QUERY_TIMEOUT = "15 seconds";
@@ -662,6 +668,38 @@ function uniqueShellCandidates(candidates: Array): ShellC
return ordered;
}
+// Preparation can wait on a stalled filesystem while startup holds the terminal locks.
+const withShellPreparationTimeout = (
+ effect: Effect.Effect ,
+ duration: Duration.Input = SHELL_PREPARATION_TIMEOUT,
+) =>
+ effect.pipe(
+ Effect.interruptible,
+ Effect.timeoutOrElse({
+ duration,
+ orElse: () => Effect.fail(new Cause.TimeoutError("Terminal shell preparation timed out.")),
+ }),
+ );
+
+const probeShellExecutable = (paths: ReadonlyArray) =>
+ Effect.promise(
+ (signal) =>
+ new Promise((resolve) => {
+ // Keep filesystem checks off the server's libuv pool. Pass paths as data to the probe.
+ NodeChildProcess.execFile(
+ "/bin/sh",
+ [
+ "-c",
+ 'for file do if [ -f "$file" ] && [ -x "$file" ]; then printf "%s" "$file"; exit 0; fi; done; exit 1',
+ "terminal-shell-probe",
+ ...paths.filter((path) => !path.includes("\0")),
+ ],
+ { env: {}, signal, killSignal: "SIGKILL" },
+ (error, stdout) => resolve(error ? undefined : stdout),
+ ).unref();
+ }),
+ );
+
const resolveShellCandidates = Effect.fn("terminal.resolveShellCandidates")(function* (
shellResolver: () => string,
platform: NodeJS.Platform,
@@ -2841,12 +2879,14 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
spawnEnv: NodeJS.ProcessEnv,
session: TerminalSessionState,
index = 0,
- lastError: PtyAdapter.PtySpawnError | null = null,
+ lastError: PtyAdapter.PtySpawnError | Cause.TimeoutError | null = null,
): Effect.fn.Return<
{ process: PtyAdapter.PtyProcess; shell: string; shellLabel: string },
- PtyAdapter.PtySpawnError
+ PtyAdapter.PtySpawnError | Cause.TimeoutError
> {
- if (index >= shellCandidates.length) {
+ const candidate = shellCandidates[index];
+ if (!candidate) {
+ if (Cause.isTimeoutError(lastError)) return yield* lastError;
return yield* new PtyAdapter.PtySpawnError({
adapter: "terminal-manager",
attemptedShells: shellCandidates.map((candidate) => formatShellCandidate(candidate)),
@@ -2854,54 +2894,61 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
});
}
- const candidate = shellCandidates[index];
- if (!candidate) {
- return yield* (
- lastError ??
- new PtyAdapter.PtySpawnError({
- adapter: "terminal-manager",
- attemptedShells: [],
- })
- );
- }
-
// PATH lookup must use the child's working directory, not the server's.
- const lookupEnv =
- platform === "win32"
- ? spawnEnv
- : {
- ...spawnEnv,
- PATH: (spawnEnv.PATH ?? spawnEnv.Path ?? spawnEnv.path ?? "")
- .split(":")
- // An empty entry means the working directory, which resolve("") yields.
- .map((entry) => path.resolve(session.cwd, entry.replace(/^"+|"+$/g, "")))
- .join(":"),
- };
+ const searchDirectories = (spawnEnv.PATH ?? spawnEnv.Path ?? spawnEnv.path ?? "")
+ .split(":")
+ // An empty entry means the working directory, which resolve("") yields.
+ .map((entry) => path.resolve(session.cwd, entry.replace(/^"+|"+$/g, "")));
// POSIX node-pty can return a PTY before exec fails, so validate before accepting a candidate.
const shellCommand = candidate.shell.includes("/")
? path.resolve(session.cwd, candidate.shell)
: candidate.shell;
- const executable =
- platform !== "win32"
- ? yield* Effect.promise(async () => resolveExecutable(shellCommand, platform, lookupEnv))
- : candidate.shell;
- if (executable === undefined) {
+ const explicitPath = shellCommand.includes("/") || shellCommand.includes("\\");
+ const lookup =
+ platform === "win32"
+ ? Result.succeed(candidate.shell)
+ : yield* withShellPreparationTimeout(
+ // The default resolver's fs promises cannot be aborted; an injected resolver is kept as given.
+ resolveExecutable === SpawnExecutableResolution.defaultValue()
+ ? probeShellExecutable(
+ explicitPath
+ ? [shellCommand]
+ : searchDirectories.map((directory) => path.join(directory, shellCommand)),
+ )
+ : Effect.promise(async () =>
+ resolveExecutable(shellCommand, platform, {
+ ...spawnEnv,
+ PATH: searchDirectories.join(":"),
+ }),
+ ),
+ SHELL_LOOKUP_TIMEOUT,
+ ).pipe(Effect.result);
+ if (Result.isFailure(lookup) || lookup.success === undefined) {
return yield* trySpawn(
shellCandidates,
spawnEnv,
session,
index + 1,
- new PtyAdapter.PtySpawnError({ adapter: "terminal-manager", shell: candidate.shell }),
+ Result.isFailure(lookup)
+ ? lookup.failure
+ : (lastError ??
+ new PtyAdapter.PtySpawnError({
+ adapter: "terminal-manager",
+ shell: candidate.shell,
+ })),
);
}
- const launch = yield* agentScope.wrap({
- command: executable,
- args: candidate.args ?? [],
- name: "terminal",
- env: spawnEnv,
- survivesRestart: true,
- });
+ const launch = yield* agentScope
+ .wrap({
+ command: lookup.success,
+ args: candidate.args ?? [],
+ name: "terminal",
+ env: spawnEnv,
+ survivesRestart: true,
+ })
+ .pipe(withShellPreparationTimeout);
+
const attempt = yield* Effect.result(
options.ptyAdapter.spawn({
shell: launch.command,
@@ -2926,7 +2973,13 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
return yield* spawnError;
}
- return yield* trySpawn(shellCandidates, spawnEnv, session, index + 1, spawnError);
+ return yield* trySpawn(
+ shellCandidates,
+ spawnEnv,
+ session,
+ index + 1,
+ Cause.isTimeoutError(lastError) ? lastError : spawnError,
+ );
});
const startSession = Effect.fn("terminal.startSession")(function* (
@@ -2974,7 +3027,10 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
platform,
baseEnv,
session.runtimeEnv?.T3CODE_TERMINAL_SHELL ?? baseEnv.T3CODE_TERMINAL_SHELL,
- ).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem));
+ ).pipe(
+ Effect.provideService(FileSystem.FileSystem, fileSystem),
+ withShellPreparationTimeout,
+ );
const terminalEnv = createTerminalSpawnEnv(
baseEnv,
session.runtimeEnv,
@@ -2995,6 +3051,8 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
+ withShellPreparationTimeout,
+ Effect.catchTags({ TimeoutError: () => Effect.succeed([]) }),
);
if (managedDirectories.length > 0) {
const delimiter = platform === "win32" ? ";" : ":";
@@ -3108,7 +3166,7 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
...(startedShell ? { shell: startedShell } : {}),
});
}
- });
+ }, Effect.uninterruptible);
const closeSession = Effect.fn("terminal.closeSession")(function* (
threadId: string,
@@ -3432,23 +3490,27 @@ export const makeWithOptions = Effect.fn("TerminalManager.makeWithOptions")(func
};
const createdSession = session;
+ // Once the session is visible as starting, finish startup even if the opener disconnects.
yield* modifyManagerState((state) => {
const sessions = new Map(state.sessions);
sessions.set(sessionKey, createdSession);
closedSessionKeys.delete(sessionKey);
return [undefined, { ...state, sessions }] as const;
- });
-
- yield* evictInactiveSessionsIfNeeded();
- yield* startSession(
- session,
- {
- cwd: input.cwd,
- ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
- cols,
- rows,
- },
- "started",
+ }).pipe(
+ Effect.andThen(() => evictInactiveSessionsIfNeeded()),
+ Effect.andThen(() =>
+ startSession(
+ session,
+ {
+ cwd: input.cwd,
+ ...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
+ cols,
+ rows,
+ },
+ "started",
+ ),
+ ),
+ Effect.uninterruptible,
);
return session;
}
diff --git a/apps/server/src/terminal/NodePtyAdapter.test.ts b/apps/server/src/terminal/NodePtyAdapter.test.ts
index 66704396e9e76..1baf7f7ccd330 100644
--- a/apps/server/src/terminal/NodePtyAdapter.test.ts
+++ b/apps/server/src/terminal/NodePtyAdapter.test.ts
@@ -6,8 +6,10 @@ import { assert, it } from "@effect/vitest";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
+import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Scheduler from "effect/Scheduler";
+import * as TestClock from "effect/testing/TestClock";
import { vi } from "vite-plus/test";
import * as NodePtyAdapter from "./NodePtyAdapter.ts";
@@ -197,3 +199,45 @@ it.effect("replays an exit to late subscribers and respects unsubscription", ()
assert.equal(nativeProcess.events.listenerCount("exit"), 0);
}).pipe(Effect.provide(layerTest)),
);
+
+it.effect("retries the spawn-helper repair after a stalled check times out", () =>
+ Effect.gen(function* () {
+ let stalled = true;
+ const chmod = vi.fn();
+ const fileSystem = Layer.effect(
+ FileSystem.FileSystem,
+ Effect.map(FileSystem.FileSystem, (fs) => ({
+ ...fs,
+ exists: () => (stalled ? Effect.never : Effect.succeed(true)),
+ chmod: (path: string) => Effect.sync(() => chmod(path)),
+ })),
+ ).pipe(Layer.provide(NodeServices.layer));
+ const adapter = yield* PtyAdapter.PtyAdapter.pipe(
+ Effect.provide(
+ NodePtyAdapter.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ NodeServices.layer,
+ fileSystem,
+ Layer.succeed(HostProcess.Platform, "linux"),
+ Layer.succeed(HostProcess.Architecture, "x64"),
+ Layer.succeed(NodePtyAdapter.NodePtyModuleLoaderRef, () =>
+ Promise.resolve(fakeNodePty),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ const input = { ...spawnInput, shell: "/bin/sh" };
+
+ const first = yield* adapter.spawn(input).pipe(Effect.forkChild({ startImmediately: true }));
+ yield* TestClock.adjust("5 seconds");
+ yield* Fiber.join(first);
+ assert.strictEqual(chmod.mock.calls.length, 0);
+
+ stalled = false;
+ yield* adapter.spawn(input);
+ assert.strictEqual(chmod.mock.calls.length, 1);
+ }),
+);
diff --git a/apps/server/src/terminal/NodePtyAdapter.ts b/apps/server/src/terminal/NodePtyAdapter.ts
index 4035e23f2b977..730ee0411faf1 100644
--- a/apps/server/src/terminal/NodePtyAdapter.ts
+++ b/apps/server/src/terminal/NodePtyAdapter.ts
@@ -77,14 +77,11 @@ const ensureNodePtySpawnHelperExecutable = Effect.fn(function* () {
if (didEnsureSpawnHelperExecutable) return;
const helperPath = yield* resolveNodePtySpawnHelperPath;
- if (!helperPath) return;
- didEnsureSpawnHelperExecutable = true;
-
- if (!(yield* fs.exists(helperPath))) {
- return;
+ if (helperPath && (yield* fs.exists(helperPath))) {
+ yield* fs.chmod(helperPath, 0o755).pipe(Effect.orElseSucceed(() => undefined));
}
-
- yield* fs.chmod(helperPath, 0o755).pipe(Effect.orElseSucceed(() => undefined));
+ // Set only after the repair finishes, so a check cut off by the spawn deadline runs again.
+ didEnsureSpawnHelperExecutable = true;
});
// node-pty has no public readiness event; ready_datapipe sets pid before our listener.
@@ -244,19 +241,20 @@ const make = Effect.fn("NodePtyAdapter.make")(function* () {
}),
}).pipe(Effect.orDie);
- const ensureNodePtySpawnHelperExecutableCached = yield* Effect.cached(
- ensureNodePtySpawnHelperExecutable().pipe(
- Effect.provideService(FileSystem.FileSystem, fs),
- Effect.provideService(Path.Path, path),
- Effect.provideService(HostProcess.Platform, platform),
- Effect.provideService(HostProcess.Architecture, architecture),
- Effect.orElseSucceed(() => undefined),
- ),
+ const ensureSpawnHelperExecutable = ensureNodePtySpawnHelperExecutable().pipe(
+ Effect.provideService(FileSystem.FileSystem, fs),
+ Effect.provideService(Path.Path, path),
+ Effect.provideService(HostProcess.Platform, platform),
+ Effect.provideService(HostProcess.Architecture, architecture),
+ Effect.orElseSucceed(() => undefined),
+ // Terminal startup runs uninterruptibly; a stalled helper check must not hold its locks.
+ Effect.interruptible,
+ Effect.timeoutOrElse({ duration: "5 seconds", orElse: () => Effect.void }),
);
return PtyAdapter.PtyAdapter.of({
spawn: Effect.fn("NodePtyAdapter.spawn")(function* (input) {
- yield* ensureNodePtySpawnHelperExecutableCached;
+ yield* ensureSpawnHelperExecutable;
// ConPTY ignores node-pty's name option for TERM; set it explicitly to avoid missing/16-color values.
const env =
platform === "win32" && input.env["TERM"] === undefined
From 605980d3971aa4f28257f9051019a7d033ba6569 Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 13:33:14 -0600
Subject: [PATCH 090/238] fix(web): pressing Escape on the Environments map
clears selection without closing Settings (#43017)
Co-authored-by: Julius Marminge
---
.../settings/EnvironmentsMap.browser.test.tsx | 81 +++++++++++++++++++
.../components/settings/EnvironmentsMap.tsx | 13 ++-
.../settings/EnvironmentsMapDetails.tsx | 7 ++
3 files changed, 99 insertions(+), 2 deletions(-)
create mode 100644 apps/web/src/components/settings/EnvironmentsMap.browser.test.tsx
diff --git a/apps/web/src/components/settings/EnvironmentsMap.browser.test.tsx b/apps/web/src/components/settings/EnvironmentsMap.browser.test.tsx
new file mode 100644
index 0000000000000..4302acdb53bf5
--- /dev/null
+++ b/apps/web/src/components/settings/EnvironmentsMap.browser.test.tsx
@@ -0,0 +1,81 @@
+import { describe, expect, it, vi } from "vite-plus/test";
+import { page, userEvent } from "vite-plus/test/browser";
+
+import "~/index.css";
+import { render } from "../../../test/render";
+import { AppRouteModal } from "../AppRouteModal";
+import { EnvironmentsMap } from "./EnvironmentsMap";
+
+vi.mock("../chat/GlobalVoiceInputIndicator", () => ({ GlobalVoiceInputIndicator: () => null }));
+
+const renderSettingsMap = () =>
+ render(
+
+ {}}
+ renderSavedEnvironment={() => null}
+ renderConnectMachine={() => null}
+ />
+ ,
+ { router: "/settings/connections" },
+ );
+
+describe("EnvironmentsMap", () => {
+ it("clears the selection on Esc before Settings closes", async () => {
+ await using _screen = await renderSettingsMap();
+ const settings = page.getByRole("dialog", { name: "Settings" });
+ const browser = page.getByRole("button", { name: "This browser", exact: true });
+
+ await expect.element(settings).toHaveFocus();
+ await browser.click();
+ await expect.element(browser).toHaveAttribute("aria-pressed", "true");
+ await userEvent.keyboard("{Escape}");
+
+ await expect.element(browser).toHaveAttribute("aria-pressed", "false");
+ // The close would render in the same commit that cleared the selection.
+ expect(settings.element()).toHaveAttribute("data-open");
+
+ await userEvent.keyboard("{Escape}");
+ await expect.element(settings).not.toBeInTheDocument();
+ });
+
+ it("clears the selection on Esc when a click does not focus the machine", async () => {
+ await using _screen = await renderSettingsMap();
+ // Safari leaves focus where it was when a button is clicked.
+ const keepFocus = (event: MouseEvent) => event.preventDefault();
+ document.addEventListener("mousedown", keepFocus, true);
+ using _keepFocus = {
+ [Symbol.dispose]: () => document.removeEventListener("mousedown", keepFocus, true),
+ };
+ const settings = page.getByRole("dialog", { name: "Settings" });
+ const browser = page.getByRole("button", { name: "This browser", exact: true });
+
+ await expect.element(settings).toHaveFocus();
+ await browser.click();
+ await expect.element(browser).toHaveAttribute("aria-pressed", "true");
+ await userEvent.keyboard("{Escape}");
+
+ await expect.element(browser).toHaveAttribute("aria-pressed", "false");
+ expect(settings.element()).toHaveAttribute("data-open");
+ });
+
+ it("clears the selection on Esc from the details before Settings closes", async () => {
+ await using _screen = await renderSettingsMap();
+ const settings = page.getByRole("dialog", { name: "Settings" });
+ const browser = page.getByRole("button", { name: "This browser", exact: true });
+ const details = page.getByRole("group", { name: "Details" });
+
+ await expect.element(settings).toHaveFocus();
+ await browser.click();
+ await expect.element(browser).toHaveAttribute("aria-pressed", "true");
+ // Choosing a machine or link inside the details leaves focus on the panel.
+ (details.element() as HTMLElement).focus();
+ await userEvent.keyboard("{Escape}");
+
+ await expect.element(browser).toHaveAttribute("aria-pressed", "false");
+ expect(settings.element()).toHaveAttribute("data-open");
+
+ await userEvent.keyboard("{Escape}");
+ await expect.element(settings).not.toBeInTheDocument();
+ });
+});
diff --git a/apps/web/src/components/settings/EnvironmentsMap.tsx b/apps/web/src/components/settings/EnvironmentsMap.tsx
index 5d4b2f96754c8..cd38521dc6b2e 100644
--- a/apps/web/src/components/settings/EnvironmentsMap.tsx
+++ b/apps/web/src/components/settings/EnvironmentsMap.tsx
@@ -863,8 +863,11 @@ function FleetCanvas({
if (event.key === "+" || event.key === "=") zoom(1.25);
else if (event.key === "-") zoom(0.8);
else if (event.key === "0") fit();
- else if (event.key === "Escape") onSelect(null);
- else return;
+ else if (event.key === "Escape" && selection !== null) {
+ // Base UI's dialog closes on a document Esc listener.
+ event.stopPropagation();
+ onSelect(null);
+ } else return;
event.preventDefault();
};
@@ -1020,6 +1023,12 @@ function FleetCanvas({
onPointerUp={(event) => endDrag(event, false)}
onPointerCancel={(event) => endDrag(event, true)}
onLostPointerCapture={(event) => endDrag(event, true)}
+ // Safari does not focus a clicked button, so its keys would skip the map.
+ onClick={(event) =>
+ (event.target as Element)
+ .closest("button[data-fleet-item]")
+ ?.focus({ preventScroll: true })
+ }
onKeyDown={onKeyDown}
>
{view === null ? null : (
diff --git a/apps/web/src/components/settings/EnvironmentsMapDetails.tsx b/apps/web/src/components/settings/EnvironmentsMapDetails.tsx
index 38c6d8d5eb93b..6e801521408be 100644
--- a/apps/web/src/components/settings/EnvironmentsMapDetails.tsx
+++ b/apps/web/src/components/settings/EnvironmentsMapDetails.tsx
@@ -160,6 +160,13 @@ export function FleetDetails(props: FleetDetailsProps) {
role="group"
aria-label={gt("Details")}
className="min-h-20 border-t border-border/60 text-xs outline-none"
+ onKeyDown={(event) => {
+ if (event.key !== "Escape" || selection === null || event.target !== panel.current) return;
+ // Base UI's dialog closes on a document Esc listener.
+ event.stopPropagation();
+ event.preventDefault();
+ onSelect(null);
+ }}
>
{connectProblem ? (
From 8987ba39d496ade970f27f7fcf04ffe6d09121f1 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 11:33:39 -0800
Subject: [PATCH 091/238] feat(workflows): a run can declare its subject and be
found by it (#42517)
Co-authored-by: Claude Opus 5.5
---
.../src/features/issues/IssueRouteScreen.tsx | 11 +
.../pull-requests/PullRequestRouteScreen.tsx | 16 ++
.../workflows/WorkflowRunRouteScreen.tsx | 23 +-
.../features/workflows/WorkflowRunsAbout.tsx | 81 +++++++
.../features/workflows/WorkflowSubject.tsx | 58 +++++
.../features/workflows/WorkflowsScreen.tsx | 29 ++-
apps/mobile/src/i18n/translations/de.json | 3 +-
apps/mobile/src/i18n/translations/en.json | 3 +-
apps/mobile/src/i18n/translations/es.json | 3 +-
apps/mobile/src/i18n/translations/fr.json | 3 +-
apps/mobile/src/i18n/translations/ja.json | 3 +-
apps/mobile/src/i18n/translations/ko.json | 3 +-
apps/mobile/src/i18n/translations/pt-BR.json | 3 +-
apps/mobile/src/i18n/translations/ru.json | 3 +-
apps/mobile/src/i18n/translations/sv.json | 3 +-
apps/mobile/src/i18n/translations/zh.json | 3 +-
apps/server/src/auth/RpcAuthorization.ts | 1 +
apps/server/src/cli/workflow.ts | 5 +
.../src/mcp/toolkits/workflow/handlers.ts | 1 +
.../server/src/mcp/toolkits/workflow/tools.ts | 3 +-
.../src/observability/RpcInstrumentation.ts | 1 +
apps/server/src/persistence/Migrations.ts | 2 +
.../Migrations/119_WorkflowRunSubject.ts | 20 ++
.../reconcileV2PreviewMigration.test.ts | 2 +
.../src/provider/agentContextBudget.json | 2 +-
apps/server/src/workflows/WorkflowEngine.ts | 39 +++-
apps/server/src/workflows/WorkflowForge.ts | 95 +++++++-
.../src/workflows/WorkflowRuntime.test.ts | 2 +
apps/server/src/workflows/WorkflowRuntime.ts | 6 +
.../src/workflows/WorkflowStore.test.ts | 36 +++
apps/server/src/workflows/WorkflowStore.ts | 84 ++++++-
apps/server/src/workflows/Workflows.test.ts | 206 ++++++++++++++++++
apps/server/src/workflows/Workflows.ts | 21 ++
apps/server/src/workflows/api.ts | 1 +
apps/server/src/workflows/runReferences.ts | 8 +
apps/server/src/workflows/stepServices.ts | 36 ++-
apps/server/src/workflows/workflow.ts | 32 ++-
apps/server/src/ws.ts | 2 +
.../src/components/issue/IssueDetailPanel.tsx | 9 +
.../pullRequest/PullRequestSummaryTab.tsx | 15 ++
.../workflows/WorkflowReferences.tsx | 25 ++-
.../workflows/WorkflowRunsAbout.tsx | 58 +++++
.../WorkflowRunsView.browser.test.tsx | 52 +++++
.../components/workflows/WorkflowRunsView.tsx | 38 +++-
.../components/workflows/WorkflowsPage.tsx | 23 +-
docs/user/workflows.md | 14 +-
evals/workflow-authoring/grade.ts | 2 +
packages/client-runtime/src/state/server.ts | 5 +
packages/client-runtime/src/workflows.test.ts | 15 ++
packages/client-runtime/src/workflows.ts | 23 +-
packages/contracts/src/rpc.ts | 10 +
packages/contracts/src/workflow.ts | 52 ++++-
skills/t3-workflows/SKILL.md | 49 +++--
53 files changed, 1157 insertions(+), 86 deletions(-)
create mode 100644 apps/mobile/src/features/workflows/WorkflowRunsAbout.tsx
create mode 100644 apps/mobile/src/features/workflows/WorkflowSubject.tsx
create mode 100644 apps/server/src/persistence/Migrations/119_WorkflowRunSubject.ts
create mode 100644 apps/web/src/components/workflows/WorkflowRunsAbout.tsx
diff --git a/apps/mobile/src/features/issues/IssueRouteScreen.tsx b/apps/mobile/src/features/issues/IssueRouteScreen.tsx
index 8312bb703894b..c128250bbc2ca 100644
--- a/apps/mobile/src/features/issues/IssueRouteScreen.tsx
+++ b/apps/mobile/src/features/issues/IssueRouteScreen.tsx
@@ -47,6 +47,7 @@ import { environmentThreadShells } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { usePullToRefresh } from "../../state/use-pull-to-refresh";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
+import { WorkflowRunsAbout } from "../workflows/WorkflowRunsAbout";
import { useAndroidWorkspaceBack } from "../layout/workspace/useAndroidWorkspaceNavigation";
import { PullRequestDescription } from "../pull-requests/PullRequestDescription";
import {
@@ -746,6 +747,16 @@ function IssueRoute({ params }: { readonly params: IssueParams }) {
) : null}
+
{detail.commentCount > 0
diff --git a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
index c0a644321a66f..6ddfbdc704c6a 100644
--- a/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
+++ b/apps/mobile/src/features/pull-requests/PullRequestRouteScreen.tsx
@@ -62,6 +62,8 @@ import { RegistryContext, useAtomRefresh, useAtomValue } from "@effect/atom-reac
import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
import { pullRequestReviewKey } from "./pullRequestReviewDrafts";
import {
+ EnvironmentId,
+ ProjectId,
pullRequestConversationThreads,
type PullRequestDetail,
type PullRequestListEntry,
@@ -146,6 +148,7 @@ import { usePullRequestEnvironmentFallback } from "./usePullRequestEnvironmentFa
import { subscribePullRequestFileJump } from "./pullRequestFileJump";
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
import { changeRequestTermKind } from "../../lib/changeRequestTerm";
+import { WorkflowRunsAbout } from "../workflows/WorkflowRunsAbout";
function usePullRequestActivityRows(params: PullRequestParams, filter: ActivityFilter) {
const navigation = useNavigation();
@@ -389,6 +392,19 @@ function PullRequestOverview(props: {
footer={ }
/>
+
);
}
diff --git a/apps/mobile/src/features/workflows/WorkflowRunRouteScreen.tsx b/apps/mobile/src/features/workflows/WorkflowRunRouteScreen.tsx
index f86c3089cd9a5..4fd2584416914 100644
--- a/apps/mobile/src/features/workflows/WorkflowRunRouteScreen.tsx
+++ b/apps/mobile/src/features/workflows/WorkflowRunRouteScreen.tsx
@@ -15,7 +15,7 @@ import { EnvironmentId, type WorkflowQuestion } from "@t3tools/contracts";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { T, Var, useGT, useMessages } from "gt-react-native";
import { useRef, useState } from "react";
-import { View } from "react-native";
+import { Pressable, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { RelativeTime } from "../../components/RelativeTime";
@@ -40,6 +40,7 @@ import {
workflowRunFeedOf,
} from "./WorkflowStepCard";
import { WORKFLOW_TONE_CLASS, WorkflowChip } from "./WorkflowsScreen";
+import { useWorkflowSubjectOpener, workflowSubjectLine } from "./WorkflowSubject";
import { WorkflowTimeline } from "./WorkflowTimeline";
export type WorkflowRunParams = {
@@ -178,6 +179,7 @@ function RunBody(props: { readonly environmentId: EnvironmentId; readonly node:
const gt = useGT();
const m = useMessages();
const sessionId = useEnvironmentSessionId(environmentId);
+ const subjectOpener = useWorkflowSubjectOpener(environmentId);
const detail = useEnvironmentQuery(
serverEnvironment.workflowRun({ environmentId, input: { runId: run.runId } }),
);
@@ -232,6 +234,7 @@ function RunBody(props: { readonly environmentId: EnvironmentId; readonly node:
),
),
);
+ const openSubject = run.subject === undefined ? null : subjectOpener(run.subject);
const threadOpener = useWorkflowThreadOpener(environmentId, (thread) =>
navigation.dispatch(StackActions.push("Thread", thread)),
);
@@ -321,6 +324,24 @@ function RunBody(props: { readonly environmentId: EnvironmentId; readonly node:
+ {run.subject === undefined ? null : (
+
+
+ {workflowSubjectLine(run.subject)}
+
+
+ )}
{feed === null ? (
<>
diff --git a/apps/mobile/src/features/workflows/WorkflowRunsAbout.tsx b/apps/mobile/src/features/workflows/WorkflowRunsAbout.tsx
new file mode 100644
index 0000000000000..4f85fc73016bc
--- /dev/null
+++ b/apps/mobile/src/features/workflows/WorkflowRunsAbout.tsx
@@ -0,0 +1,81 @@
+import {
+ allWorkflowRunNodes,
+ groupWorkflowRuns,
+ readWorkflowQuestion,
+ workflowRunState,
+} from "@t3tools/client-runtime/workflows";
+import type { EnvironmentId, WorkflowRunsAboutInput } from "@t3tools/contracts";
+import { StackActions, useNavigation } from "@react-navigation/native";
+import { useGT, useMessages } from "gt-react-native";
+import { Pressable, View } from "react-native";
+
+import { SymbolView } from "../../components/ui/AppSymbol";
+import { AppText as Text } from "../../components/ui/AppText";
+import { cn } from "../../lib/cn";
+import { useServerConfigs } from "../../state/entities";
+import { useEnvironmentQuery } from "../../state/query";
+import { serverEnvironment } from "../../state/server";
+import { PullRequestSectionHeading } from "../pull-requests/PullRequestSectionHeading";
+import { WORKFLOW_TONE_CLASS, WorkflowChip } from "./WorkflowsScreen";
+
+/** The workflow runs whose subject is `item`, on its own screen; hidden while there are none. */
+export function WorkflowRunsAbout(props: {
+ readonly environmentId: EnvironmentId;
+ readonly item: WorkflowRunsAboutInput;
+}) {
+ const gt = useGT();
+ const m = useMessages();
+ const navigation = useNavigation();
+ const enabled = useServerConfigs().get(props.environmentId)?.settings.workflowsEnabled === true;
+ const about = useEnvironmentQuery(
+ enabled
+ ? serverEnvironment.workflowRunsAbout({
+ environmentId: props.environmentId,
+ input: props.item,
+ })
+ : null,
+ );
+ if (!about.data || about.data.runs.length === 0) return null;
+ const nodes = allWorkflowRunNodes(groupWorkflowRuns([], about.data.runs, about.data.questions));
+ return (
+
+ {gt("Workflow runs")}
+ {nodes.map((node) => {
+ const state = workflowRunState(node, m);
+ const question = node.questions[0];
+ return (
+
+ navigation.dispatch(
+ StackActions.push("WorkflowRun", {
+ environmentId: props.environmentId,
+ runId: node.run.runId,
+ }),
+ )
+ }
+ className="flex-row items-center gap-2 rounded-2xl bg-grouped-card p-3 active:opacity-70"
+ >
+
+
+
+ {node.run.title}
+
+ {question === undefined ? null : (
+
+ {readWorkflowQuestion(question).title}
+
+ )}
+
+
+ {state.word}
+
+
+
+ );
+ })}
+
+ );
+}
diff --git a/apps/mobile/src/features/workflows/WorkflowSubject.tsx b/apps/mobile/src/features/workflows/WorkflowSubject.tsx
new file mode 100644
index 0000000000000..431529037b29d
--- /dev/null
+++ b/apps/mobile/src/features/workflows/WorkflowSubject.tsx
@@ -0,0 +1,58 @@
+import {
+ workflowReferenceIssue,
+ workflowReferenceLabel,
+ workflowReferencePullRequest,
+ workflowReferenceThreadId,
+} from "@t3tools/client-runtime/workflows";
+import type { EnvironmentId, WorkflowRunSubject } from "@t3tools/contracts";
+import { StackActions, useNavigation } from "@react-navigation/native";
+
+import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
+import { useWorkflowThreadOpener } from "./WorkflowStepCard";
+
+/** What a subject is called in one line: its label, then its title when that says more. */
+export function workflowSubjectLine(subject: WorkflowRunSubject): string {
+ const label = workflowReferenceLabel(subject);
+ return subject.title === "" || subject.title === label ? label : `${label} ${subject.title}`;
+}
+
+/** Opens a run's subject on its own screen, or its web address. Null when it has neither. */
+export function useWorkflowSubjectOpener(environmentId: EnvironmentId) {
+ const navigation = useNavigation();
+ const threadOpener = useWorkflowThreadOpener(environmentId, (thread) =>
+ navigation.dispatch(StackActions.push("Thread", thread)),
+ );
+ return (subject: WorkflowRunSubject): (() => void) | null => {
+ const issue = workflowReferenceIssue(subject);
+ if (issue !== null) {
+ return () =>
+ navigation.dispatch(
+ StackActions.push("Issue", {
+ environmentId,
+ projectId: issue.projectId,
+ tracker: issue.tracker,
+ ...(issue.host === undefined ? {} : { host: issue.host }),
+ scope: issue.scope,
+ issueKey: issue.key,
+ }),
+ );
+ }
+ const pullRequest = workflowReferencePullRequest(subject);
+ if (pullRequest !== null) {
+ return () =>
+ navigation.dispatch(
+ StackActions.push("PullRequest", {
+ environmentId,
+ projectId: pullRequest.projectId,
+ repository: pullRequest.repository,
+ number: pullRequest.number,
+ ...(pullRequest.host === undefined ? {} : { host: pullRequest.host }),
+ }),
+ );
+ }
+ const threadId = workflowReferenceThreadId(subject);
+ if (threadId !== null) return threadOpener({ threadId, environmentId: null });
+ const url = subject.url;
+ return url === null ? null : () => void tryOpenExternalUrl(url);
+ };
+}
diff --git a/apps/mobile/src/features/workflows/WorkflowsScreen.tsx b/apps/mobile/src/features/workflows/WorkflowsScreen.tsx
index 365fb4de036eb..d23c083b25b94 100644
--- a/apps/mobile/src/features/workflows/WorkflowsScreen.tsx
+++ b/apps/mobile/src/features/workflows/WorkflowsScreen.tsx
@@ -34,6 +34,7 @@ import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/prefer
import { formatEnvironmentQueryError } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
+import { useWorkflowSubjectOpener, workflowSubjectLine } from "./WorkflowSubject";
const TABS = [
{
@@ -77,7 +78,12 @@ export function WorkflowChip(props: { readonly name: string }) {
);
}
-function RunRow(props: { readonly node: WorkflowRunNode; readonly onOpen: () => void }) {
+function RunRow(props: {
+ readonly node: WorkflowRunNode;
+ readonly onOpen: () => void;
+ /** Null when the run has no subject, or one this device cannot open. */
+ readonly onOpenSubject: (() => void) | null;
+}) {
const { run } = props.node;
const m = useMessages();
const state = workflowRunState(props.node, m);
@@ -100,6 +106,25 @@ function RunRow(props: { readonly node: WorkflowRunNode; readonly onOpen: () =>
{run.title}
+ {run.subject === undefined ? null : (
+
+
+ {workflowSubjectLine(run.subject)}
+
+
+ )}
{workflowRunNow(props.node, m)}
@@ -124,6 +149,7 @@ function EnvironmentRuns(props: {
const navigation = useNavigation();
const gt = useGT();
const m = useMessages();
+ const subjectOpener = useWorkflowSubjectOpener(props.environmentId);
const [showSkipped, setShowSkipped] = useState(false);
const { snapshot, tab } = props;
const visible = listedWorkflowRuns(snapshot.runs, showSkipped);
@@ -151,6 +177,7 @@ function EnvironmentRuns(props: {
navigation.navigate("WorkflowRun", {
environmentId: props.environmentId,
diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json
index 7cb5f2fc625ce..e16c1987a3999 100644
--- a/apps/mobile/src/i18n/translations/de.json
+++ b/apps/mobile/src/i18n/translations/de.json
@@ -5698,5 +5698,6 @@
"1a1beecff68a6e61": "Google-Konto bestätigen",
"99451a5d2d40440f": "Zurückgezogen von {by}.",
"3ee30a50b70fffab": "Zurückgezogen von {by}: {reason}",
- "201490988858b511": "zurückgezogen von {by}"
+ "201490988858b511": "zurückgezogen von {by}",
+ "46d614fa7b4bf1e5": "Workflow-Ausführungen"
}
diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json
index 04fd867277e19..a07f9f9b0dfda 100644
--- a/apps/mobile/src/i18n/translations/en.json
+++ b/apps/mobile/src/i18n/translations/en.json
@@ -5700,5 +5700,6 @@
"1a1beecff68a6e61": "Verify Google account",
"99451a5d2d40440f": "Withdrawn by {by}.",
"3ee30a50b70fffab": "Withdrawn by {by}: {reason}",
- "201490988858b511": "withdrawn by {by}"
+ "201490988858b511": "withdrawn by {by}",
+ "46d614fa7b4bf1e5": "Workflow runs"
}
diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json
index 6397909e086d0..cfa00cdafc4e6 100644
--- a/apps/mobile/src/i18n/translations/es.json
+++ b/apps/mobile/src/i18n/translations/es.json
@@ -5692,5 +5692,6 @@
"1a1beecff68a6e61": "Verificar cuenta de Google",
"99451a5d2d40440f": "Retirada por {by}.",
"3ee30a50b70fffab": "Retirada por {by}: {reason}",
- "201490988858b511": "retirada por {by}"
+ "201490988858b511": "retirada por {by}",
+ "46d614fa7b4bf1e5": "Ejecuciones de flujos de trabajo"
}
diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json
index 149061977f2ba..79f76441ca8d2 100644
--- a/apps/mobile/src/i18n/translations/fr.json
+++ b/apps/mobile/src/i18n/translations/fr.json
@@ -5692,5 +5692,6 @@
"1a1beecff68a6e61": "Vérifier le compte Google",
"99451a5d2d40440f": "Retirée par {by}.",
"3ee30a50b70fffab": "Retirée par {by} : {reason}",
- "201490988858b511": "retirée par {by}"
+ "201490988858b511": "retirée par {by}",
+ "46d614fa7b4bf1e5": "Exécutions de workflow"
}
diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json
index 416f65e6307ef..ca748841bd565 100644
--- a/apps/mobile/src/i18n/translations/ja.json
+++ b/apps/mobile/src/i18n/translations/ja.json
@@ -5669,5 +5669,6 @@
"1a1beecff68a6e61": "Google アカウントを確認",
"99451a5d2d40440f": "{by} が取り下げました。",
"3ee30a50b70fffab": "{by} が取り下げました: {reason}",
- "201490988858b511": "{by} が取り下げ"
+ "201490988858b511": "{by} が取り下げ",
+ "46d614fa7b4bf1e5": "ワークフローの実行"
}
diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json
index 4ba4ae039be88..405dcc854c4f5 100644
--- a/apps/mobile/src/i18n/translations/ko.json
+++ b/apps/mobile/src/i18n/translations/ko.json
@@ -5676,5 +5676,6 @@
"1a1beecff68a6e61": "Google 계정 확인",
"99451a5d2d40440f": "{by}에서 철회했습니다.",
"3ee30a50b70fffab": "{by}에서 철회했습니다: {reason}",
- "201490988858b511": "{by}에서 철회함"
+ "201490988858b511": "{by}에서 철회함",
+ "46d614fa7b4bf1e5": "워크플로 실행"
}
diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json
index cbd3a8957a2ed..4aa513088d3a8 100644
--- a/apps/mobile/src/i18n/translations/pt-BR.json
+++ b/apps/mobile/src/i18n/translations/pt-BR.json
@@ -5692,5 +5692,6 @@
"1a1beecff68a6e61": "Verificar conta Google",
"99451a5d2d40440f": "Retirada por {by}.",
"3ee30a50b70fffab": "Retirada por {by}: {reason}",
- "201490988858b511": "retirada por {by}"
+ "201490988858b511": "retirada por {by}",
+ "46d614fa7b4bf1e5": "Execuções de workflow"
}
diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json
index f9f254560865a..00ec4d5f0eab2 100644
--- a/apps/mobile/src/i18n/translations/ru.json
+++ b/apps/mobile/src/i18n/translations/ru.json
@@ -5772,5 +5772,6 @@
"1a1beecff68a6e61": "Подтвердить аккаунт Google",
"99451a5d2d40440f": "Отозван: {by}.",
"3ee30a50b70fffab": "Отозван ({by}): {reason}",
- "201490988858b511": "отозван: {by}"
+ "201490988858b511": "отозван: {by}",
+ "46d614fa7b4bf1e5": "Запуски воркфлоу"
}
diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json
index f62c445602d56..eceea4366f667 100644
--- a/apps/mobile/src/i18n/translations/sv.json
+++ b/apps/mobile/src/i18n/translations/sv.json
@@ -5698,5 +5698,6 @@
"1a1beecff68a6e61": "Verifiera Google-konto",
"99451a5d2d40440f": "Återkallad av {by}.",
"3ee30a50b70fffab": "Återkallad av {by}: {reason}",
- "201490988858b511": "återkallad av {by}"
+ "201490988858b511": "återkallad av {by}",
+ "46d614fa7b4bf1e5": "Arbetsflödeskörningar"
}
diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json
index 64c79639eface..6afc2045efc9f 100644
--- a/apps/mobile/src/i18n/translations/zh.json
+++ b/apps/mobile/src/i18n/translations/zh.json
@@ -5679,5 +5679,6 @@
"1a1beecff68a6e61": "验证 Google 账户",
"99451a5d2d40440f": "已由 {by} 撤回。",
"3ee30a50b70fffab": "已由 {by} 撤回:{reason}",
- "201490988858b511": "已由 {by} 撤回"
+ "201490988858b511": "已由 {by} 撤回",
+ "46d614fa7b4bf1e5": "工作流运行"
}
diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts
index c768b933e5e6c..367ab10be6c0c 100644
--- a/apps/server/src/auth/RpcAuthorization.ts
+++ b/apps/server/src/auth/RpcAuthorization.ts
@@ -133,6 +133,7 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.workflowsSubscribe]: AuthOrchestrationReadScope,
[WS_METHODS.workflowsCounts]: AuthOrchestrationReadScope,
[WS_METHODS.workflowsGet]: AuthOrchestrationReadScope,
+ [WS_METHODS.workflowsAbout]: AuthOrchestrationReadScope,
[WS_METHODS.workflowsGetDefinition]: AuthFilesystemReadScope,
[WS_METHODS.secretsAnswerRequest]: AuthOrchestrationOperateScope,
[WS_METHODS.agentFeedbackAnswerRequest]: AuthOrchestrationOperateScope,
diff --git a/apps/server/src/cli/workflow.ts b/apps/server/src/cli/workflow.ts
index c744ab77f03e2..3e979a8b147f4 100644
--- a/apps/server/src/cli/workflow.ts
+++ b/apps/server/src/cli/workflow.ts
@@ -108,6 +108,10 @@ const listCommand = Command.make("list", {
Flag.withDescription("Only runs their workflow tagged with this."),
Flag.optional,
),
+ subject: Flag.String("subject").pipe(
+ Flag.withDescription("Only runs about this: the web address of their subject, or a thread id."),
+ Flag.optional,
+ ),
json: jsonFlag,
}).pipe(
Command.withDescription("List workflow runs, newest first."),
@@ -121,6 +125,7 @@ const listCommand = Command.make("list", {
action: "list",
...(Option.isSome(flags.status) ? { status: flags.status.value } : {}),
...(Option.isSome(flags.tag) ? { tag: flags.tag.value } : {}),
+ ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
},
RunsResult,
);
diff --git a/apps/server/src/mcp/toolkits/workflow/handlers.ts b/apps/server/src/mcp/toolkits/workflow/handlers.ts
index d633d54ca68b2..ebab358885e7c 100644
--- a/apps/server/src/mcp/toolkits/workflow/handlers.ts
+++ b/apps/server/src/mcp/toolkits/workflow/handlers.ts
@@ -43,6 +43,7 @@ export const layer = McpToolAccess.toLayer(WorkflowToolkit, {
.list({
...(input.status === undefined ? {} : { status: input.status }),
...(input.tag === undefined ? {} : { tag: input.tag }),
+ ...(input.subject === undefined ? {} : { subject: input.subject }),
})
.pipe(Effect.mapError(refused)),
};
diff --git a/apps/server/src/mcp/toolkits/workflow/tools.ts b/apps/server/src/mcp/toolkits/workflow/tools.ts
index d226f14a35fb1..0b5b4793d13c9 100644
--- a/apps/server/src/mcp/toolkits/workflow/tools.ts
+++ b/apps/server/src/mcp/toolkits/workflow/tools.ts
@@ -17,7 +17,7 @@ const ExactName = Schema.String.check(
const WorkflowTool = Tool.make("t3_workflow", {
description:
- "Durable workflow runs on this server. start: `workflow`, `input`, `idempotencyKey` (same key, same run). list: runs, by `status` and `tag`. read: one run and its steps. questions: what runs ask a person, by `kind`. hooks: the URL paths that start runs. store: what workflows keep, under keys starting with `key`; store_set a `key` to `value`; store_delete. signal: wake a wait with `value`, addressed by `runId` and `wait`, or by `workflow` and `channel`; answers a question as `{choice, reason?}`. withdraw: end the question `wait` of `runId` unanswered, with an optional `reason`; its run goes on as if the question timed out. resume: run a paused run's failed step again. cancel.",
+ "Durable workflow runs on this server. start: `workflow`, `input`, `idempotencyKey` (same key, same run). list: runs, by `status`, `tag` and `subject` (the web address or thread id a run is about). read: one run and its steps. questions: what runs ask a person, by `kind`. hooks: the URL paths that start runs. store: what workflows keep, under keys starting with `key`; store_set a `key` to `value`; store_delete. signal: wake a wait with `value`, addressed by `runId` and `wait`, or by `workflow` and `channel`; answers a question as `{choice, reason?}`. withdraw: end the question `wait` of `runId` unanswered, with an optional `reason`; its run goes on as if the question timed out. resume: run a paused run's failed step again. cancel.",
parameters: Schema.Struct({
action: Schema.Literals([
...WORKFLOW_READ_ACTIONS,
@@ -36,6 +36,7 @@ const WorkflowTool = Tool.make("t3_workflow", {
runId: Schema.optional(TrimmedNonEmptyString),
status: Schema.optional(WorkflowRunStatus),
tag: Schema.optional(ExactName),
+ subject: Schema.optional(ExactName),
kind: Schema.optional(ExactName),
wait: Schema.optional(ExactName),
key: Schema.optional(ExactName),
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index cab2bfec74988..6e265f668ef87 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -108,6 +108,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.workflowsSubscribe]: "workflows",
[WS_METHODS.workflowsCounts]: "workflows",
[WS_METHODS.workflowsGet]: "workflows",
+ [WS_METHODS.workflowsAbout]: "workflows",
[WS_METHODS.workflowsAnswer]: "workflows",
[WS_METHODS.workflowsResume]: "workflows",
[WS_METHODS.workflowsCancel]: "workflows",
diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts
index 9fd406b898758..5d29aa358584e 100644
--- a/apps/server/src/persistence/Migrations.ts
+++ b/apps/server/src/persistence/Migrations.ts
@@ -129,6 +129,7 @@ import Migration0115 from "./Migrations/115_WorkflowRunTags.ts";
import Migration0116 from "./Migrations/116_ForkHistoryMembership.ts";
import Migration0117 from "./Migrations/117_WorkflowMailSender.ts";
import Migration0118 from "./Migrations/118_WorkflowPools.ts";
+import Migration0119 from "./Migrations/119_WorkflowRunSubject.ts";
const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
@@ -250,6 +251,7 @@ const migrationEntries = [
[116, "ForkHistoryMembership", Migration0116],
[117, "WorkflowMailSender", Migration0117],
[118, "WorkflowPools", Migration0118],
+ [119, "WorkflowRunSubject", Migration0119],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
diff --git a/apps/server/src/persistence/Migrations/119_WorkflowRunSubject.ts b/apps/server/src/persistence/Migrations/119_WorkflowRunSubject.ts
new file mode 100644
index 0000000000000..117075e5be722
--- /dev/null
+++ b/apps/server/src/persistence/Migrations/119_WorkflowRunSubject.ts
@@ -0,0 +1,20 @@
+import * as Effect from "effect/Effect";
+import * as SqlClient from "effect/sql/SqlClient";
+
+export default Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ // The one thing a run declares it is about. Kind and key find runs of a subject, the url finds
+ // them by the address a person has; the JSON is what a client needs to show and open it.
+ yield* sql`ALTER TABLE workflow_runs ADD COLUMN subject_kind TEXT`;
+ yield* sql`ALTER TABLE workflow_runs ADD COLUMN subject_key TEXT`;
+ yield* sql`ALTER TABLE workflow_runs ADD COLUMN subject_url TEXT`;
+ yield* sql`ALTER TABLE workflow_runs ADD COLUMN subject_json TEXT`;
+ yield* sql`
+ CREATE INDEX IF NOT EXISTS workflow_runs_subject ON workflow_runs (subject_key)
+ WHERE subject_key IS NOT NULL
+ `;
+ yield* sql`
+ CREATE INDEX IF NOT EXISTS workflow_runs_subject_url ON workflow_runs (subject_url)
+ WHERE subject_url IS NOT NULL
+ `;
+});
diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
index d995a57ac767d..20289dd44997d 100644
--- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
+++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts
@@ -98,6 +98,7 @@ describe("V2 preview upgrade", () => {
[116, "ForkHistoryMembership"],
[117, "WorkflowMailSender"],
[118, "WorkflowPools"],
+ [119, "WorkflowRunSubject"],
]);
assert.deepStrictEqual(yield* runMigrations(), []);
assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports);
@@ -239,6 +240,7 @@ describe("V2 preview upgrade", () => {
[116, "ForkHistoryMembership"],
[117, "WorkflowMailSender"],
[118, "WorkflowPools"],
+ [119, "WorkflowRunSubject"],
]);
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
);
diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json
index 1ec3e92e381c8..6ee87b39f01a3 100644
--- a/apps/server/src/provider/agentContextBudget.json
+++ b/apps/server/src/provider/agentContextBudget.json
@@ -1,5 +1,5 @@
{
"claudeSystemAppendBytes": 6245,
"codexAdditionalContextBytes": 7639,
- "mcpToolListJsonBytes": 62055
+ "mcpToolListJsonBytes": 62140
}
diff --git a/apps/server/src/workflows/WorkflowEngine.ts b/apps/server/src/workflows/WorkflowEngine.ts
index 853b7181a2b25..6f03269434d47 100644
--- a/apps/server/src/workflows/WorkflowEngine.ts
+++ b/apps/server/src/workflows/WorkflowEngine.ts
@@ -48,7 +48,7 @@ import {
type Woke,
type WorkflowDefinition,
} from "./workflow.ts";
-import { issueReference, noteFor, stepReferences } from "./runReferences.ts";
+import { issueReference, noteFor, stepReferences, subjectSet } from "./runReferences.ts";
import { forStep, KeyValues, layerKeyValues, EngineLink, layerEngineLink } from "./stepServices.ts";
import { WorkflowAgents } from "./WorkflowAgents.ts";
import { answerProblem, settleTurn, TurnEnd, TurnWatch } from "./workflowAgent.ts";
@@ -193,6 +193,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* (
...(row.tags_json === "[]"
? {}
: { tags: WorkflowStore.jsonValue(row.tags_json) as ReadonlyArray }),
+ ...(row.subject_json === null ? {} : { subject: WorkflowStore.subjectOf(row.subject_json) }),
startedAt: row.started_at,
updatedAt: row.updated_at,
endedAt: row.ended_at,
@@ -341,6 +342,9 @@ const make = Effect.fn("WorkflowEngine.make")(function* (
// The key is unique, so the row holding it is the run, even one another version started.
const holder = yield* store.runByKey(name, options.idempotencyKey);
if (holder !== undefined && holder.run_id !== runId) return yield* other(holder);
+ if (earlier === undefined && options.subject !== undefined) {
+ yield* subjectSet(store, runId, options.subject);
+ }
yield* withEngine(engine.execute(payload, { discard: true }));
if (options.parent !== undefined) {
// The key named a run that someone else started: it would never tell this parent.
@@ -1238,6 +1242,7 @@ const make = Effect.fn("WorkflowEngine.make")(function* (
status: row.status,
detail: row.detail,
tags: WorkflowStore.jsonValue(row.tags_json) as ReadonlyArray,
+ subject: row.subject_json === null ? null : WorkflowStore.subjectOf(row.subject_json),
startedAt: row.started_at,
endedAt: row.ended_at,
}));
@@ -1287,11 +1292,39 @@ const make = Effect.fn("WorkflowEngine.make")(function* (
}),
list: Effect.fn("Workflows.list")(function* (filter) {
const rows =
- filter?.tag === undefined
+ filter?.tag === undefined && filter?.subject === undefined
? yield* store.runs(filter?.status)
- : yield* store.runsWhere({ status: filter.status, tag: filter.tag });
+ : yield* store.runsWhere({
+ status: filter.status,
+ tag: filter.tag,
+ subject: filter.subject,
+ });
return rows.map(toRun);
}),
+ about: Effect.fn("Workflows.about")(function* (item) {
+ // Keyed as the subject was kept, so an item named without its address is found too.
+ const identity =
+ item.issue !== undefined
+ ? issueReference(item.issue)
+ : item.pullRequest !== undefined
+ ? pullRequestReferenceOf(item.pullRequest, { url: item.subject })
+ : undefined;
+ const found = [
+ ...(yield* store.runsWhere({ subject: item.subject })),
+ ...(identity === undefined
+ ? []
+ : yield* store.runsWhere({ subject: { kind: identity.kind, key: identity.key } })),
+ ];
+ const runs = [...new Map(found.map((row) => [row.run_id, row])).values()]
+ .toSorted((left, right) =>
+ left.started_at === right.started_at ? 0 : left.started_at < right.started_at ? 1 : -1,
+ )
+ .slice(0, 500)
+ .map(toRun);
+ const about = new Set(runs.map((run) => run.runId));
+ const open = yield* questions;
+ return { runs, questions: open.filter((question) => about.has(question.runId)) };
+ }),
waitFor: Effect.fn("Workflows.waitFor")(function* (runId, done) {
// Subscribed before the first look, so a change in between is not missed.
const changes = yield* PubSub.subscribe(store.changes);
diff --git a/apps/server/src/workflows/WorkflowForge.ts b/apps/server/src/workflows/WorkflowForge.ts
index dab867593b4dd..b4e90ab591804 100644
--- a/apps/server/src/workflows/WorkflowForge.ts
+++ b/apps/server/src/workflows/WorkflowForge.ts
@@ -6,14 +6,17 @@ import {
IssueListEntry,
type IssueCreateResult,
type IssueListState,
- type IssueRef,
+ IssueRef,
type PullRequestAction,
type PullRequestDetail,
PullRequestListEntry,
type PullRequestListState,
type PullRequestMergeMethod,
type PullRequestRef,
+ PositiveInt,
ProjectId,
+ TrimmedNonEmptyString,
+ WorkflowReferenceKind,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -31,6 +34,7 @@ import {
} from "../sourceControl/threadPullRequests.ts";
import { issueReference, noteReference, pullRequestReference } from "./runReferences.ts";
import { isProjectPath } from "./WorkflowAgents.ts";
+import type { ReferenceInput } from "./WorkflowStore.ts";
export class WorkflowForgeError extends Schema.TaggedError()(
"WorkflowForgeError",
@@ -186,6 +190,95 @@ export const linkedPullRequestReferences = (
),
);
+/**
+ * What `subject` and `runs({ subject })` take: an issue or a pull request as a trigger or a
+ * listing gave it, `{ threadId }`, or a web address.
+ */
+export type SubjectInput =
+ | string
+ | (Pick & {
+ readonly title?: string;
+ readonly url?: string;
+ })
+ | (Pick