From 2a6b2c8298856fdbcb46713542b41d65d88758ab Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:03:16 +0000 Subject: [PATCH 001/253] feat(web): switch the UI language from Settings, with Spanish and Chinese (#31313) --- apps/web/gt.config.json | 9 + apps/web/package.json | 6 +- apps/web/src/AppRoot.tsx | 13 +- apps/web/src/appInit.tsx | 2 + .../settings/SettingsBreadcrumb.tsx | 13 +- .../components/settings/SettingsPanels.tsx | 181 ++-- .../settings/SettingsSidebarNav.tsx | 27 +- .../settings/settingsSearch.test.ts | 2 + .../src/components/settings/settingsSearch.ts | 81 +- apps/web/src/i18n/I18nProvider.tsx | 15 + apps/web/src/i18n/initializeI18n.ts | 21 + apps/web/src/i18n/locales.ts | 37 + apps/web/src/i18n/runtime.ts | 84 ++ apps/web/src/i18n/translations/en.json | 74 ++ apps/web/src/i18n/translations/es.json | 74 ++ apps/web/src/i18n/translations/zh.json | 74 ++ apps/web/src/main.tsx | 4 +- apps/web/test/browserSetup.ts | 5 + apps/web/tsconfig.json | 1 + packages/contracts/src/settings.ts | 3 + pnpm-lock.yaml | 818 +++++++++++++++++- 21 files changed, 1432 insertions(+), 112 deletions(-) create mode 100644 apps/web/gt.config.json create mode 100644 apps/web/src/i18n/I18nProvider.tsx create mode 100644 apps/web/src/i18n/initializeI18n.ts create mode 100644 apps/web/src/i18n/locales.ts create mode 100644 apps/web/src/i18n/runtime.ts create mode 100644 apps/web/src/i18n/translations/en.json create mode 100644 apps/web/src/i18n/translations/es.json create mode 100644 apps/web/src/i18n/translations/zh.json diff --git a/apps/web/gt.config.json b/apps/web/gt.config.json new file mode 100644 index 0000000000000..965dec405f56e --- /dev/null +++ b/apps/web/gt.config.json @@ -0,0 +1,9 @@ +{ + "defaultLocale": "en", + "locales": ["es", "zh"], + "files": { + "gt": { + "output": "src/i18n/translations/[locale].json" + } + } +} diff --git a/apps/web/package.json b/apps/web/package.json index e017a7965302e..a7959f92357bd 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -8,8 +8,10 @@ "dev": "vp dev", "dev:built": "vp build --watch", "build": "vp build", + "i18n:generate": "gt generate", "preview": "vp preview", - "test": "vp test run --passWithNoTests --project unit --project browser" + "test": "vp test run --passWithNoTests --project unit --project browser", + "i18n:translate": "gt translate" }, "dependencies": { "@base-ui/react": "^1.9.0", @@ -62,6 +64,7 @@ "effect": "catalog:", "entities": "8.1.0", "fast-xml-parser": "5.7.3", + "gt-react": "11.4.18", "hast-util-to-html": "^9.0.5", "hast-util-to-jsx-runtime": "^2.3.6", "heic-to": "^1.5.2", @@ -108,6 +111,7 @@ "@vitejs/plugin-react": "^6.1.2", "@vitest/browser-playwright": "5.0.5", "compression": "^1.8.2", + "gt": "2.27.0", "micromark-util-types": "catalog:", "oxc-transform-react": "~0.152.0", "playwright": "1.64.1", diff --git a/apps/web/src/AppRoot.tsx b/apps/web/src/AppRoot.tsx index 2491e9a813af2..279e1b70d5fa0 100644 --- a/apps/web/src/AppRoot.tsx +++ b/apps/web/src/AppRoot.tsx @@ -2,16 +2,19 @@ import { RouterProvider } from "@tanstack/react-router"; import { ElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { QuitHoldOverlay } from "./components/QuitHoldOverlay"; +import { I18nProvider } from "./i18n/I18nProvider"; import { AppAtomRegistryProvider } from "./rpc/atomRegistry"; import type { AppRouter } from "./router"; // Keep webviews outside the router but inside its atom registry so route changes preserve them. export function AppRoot({ router }: { readonly router: AppRouter }) { return ( - - - - - + + + + + + + ); } diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index dd38a292718dc..fa8e88e6b1a90 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -58,6 +58,7 @@ import { primaryServerConfigAtom } from "./state/server"; import { environmentShell } from "./state/shell"; import { installChatRouteCommands } from "./shortcuts/chatRouteCommands"; import { startWorkspaceFocus } from "./lib/workspaceFocus"; +import { startI18n } from "./i18n/runtime"; import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands"; import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut"; import { environmentThreadShells, threadEnvironment } from "./state/threads"; @@ -249,6 +250,7 @@ export function startAppServices(): AppRouter { installDesktopPasteAsText(window.desktopBridge, window); startClientAppearance(); + startI18n(); startDocumentTitle(router); startHostEnvironmentLookup(); startEnvironmentThemeRepaint(); diff --git a/apps/web/src/components/settings/SettingsBreadcrumb.tsx b/apps/web/src/components/settings/SettingsBreadcrumb.tsx index b23e9d71fc3e1..5b62a54df6ad8 100644 --- a/apps/web/src/components/settings/SettingsBreadcrumb.tsx +++ b/apps/web/src/components/settings/SettingsBreadcrumb.tsx @@ -1,3 +1,5 @@ +import { msg, useMessages } from "gt-react"; + import { WorkspaceBreadcrumb, WorkspaceBreadcrumbItem, @@ -5,10 +7,12 @@ import { } from "../WorkspaceBreadcrumb"; import { SETTINGS_SECTION_LABELS } from "./settingsSearch"; +const SETTINGS_LABEL = msg("Settings"); + const SETTINGS_BREADCRUMB_LABELS: Readonly> = { ...SETTINGS_SECTION_LABELS, - "/settings/diagnostics": "Diagnostics", - "/settings/open-source-licenses": "Open source licenses", + "/settings/diagnostics": msg("Diagnostics"), + "/settings/open-source-licenses": msg("Open source licenses"), }; function settingsBreadcrumbLabel(pathname: string): string | null { @@ -17,18 +21,19 @@ function settingsBreadcrumbLabel(pathname: string): string | null { } export function SettingsBreadcrumb({ pathname }: { pathname: string }) { + const m = useMessages(); const sectionLabel = settingsBreadcrumbLabel(pathname); return ( {sectionLabel ? ( <> - Settings + {m(SETTINGS_LABEL)} ) : null} - {sectionLabel ?? "Settings"} + {m(sectionLabel ?? SETTINGS_LABEL)} ); diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index dcaca88e6c7f7..c5548175fd1e7 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -2,6 +2,7 @@ import { useAtomValue } from "@effect/atom-react"; import { NotificationSettings } from "./NotificationSettings"; import { PRIVACY_POLICY_URL } from "../../legalLinks"; import { CheckIcon } from "lucide-react"; +import { msg, T, useGT, useMessages } from "gt-react"; import { Link, useNavigate } from "@tanstack/react-router"; import { useRef, useState } from "react"; import { @@ -103,7 +104,8 @@ import { SettingsRow, SettingsSection, } from "./settingsLayout"; -import { searchableSetting } from "./settingsSearch"; +import { searchableSetting, type SettingsSearchItemId } from "./settingsSearch"; +import { nativeLanguageName, SUPPORTED_LOCALES, SYSTEM_LANGUAGE } from "../../i18n/locales"; import { BackgroundActivitySettingsRow } from "./BackgroundActivitySettings"; import { AdvancedSettings } from "./AdvancedSettings"; import { PullRequestLinksOpenInAppSetting } from "./IntegrationsSettings"; @@ -128,17 +130,17 @@ const RESPONSE_STREAMING_MODE_DESCRIPTIONS: Record = { - updated_at: "Last user message", - created_at: "Created at", - manual: "Manual", + updated_at: msg("Last user message"), + created_at: msg("Created at"), + manual: msg("Manual"), }; const isSidebarProjectSortOrder = Schema.is(SidebarProjectSortOrder); const TIMESTAMP_FORMAT_LABELS = { - locale: "System default", - "12-hour": "12-hour", - "24-hour": "24-hour", -} as const; + locale: msg("System default"), + "12-hour": msg("12-hour"), + "24-hour": msg("24-hour"), +}; const DIFF_LAYOUT_LABELS: Record = { stacked: "Stacked", @@ -146,9 +148,9 @@ const DIFF_LAYOUT_LABELS: Record = { }; const QUIT_CONFIRMATION_MODE_LABELS: Record = { - direct: "Direct", - hold: "Hold", - "double-click": "Double press", + direct: msg("Direct"), + hold: msg("Hold"), + "double-click": msg("Double press"), }; const DEFAULT_DRIVER_KIND = ProviderDriverKind.make("codex"); @@ -475,6 +477,7 @@ export function useSettingsRestore(onRestored?: () => void) { DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode ? ["Environment identification"] : []), + ...(settings.language !== DEFAULT_UNIFIED_SETTINGS.language ? ["Language"] : []), ...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? ["Time format"] : []), @@ -645,6 +648,7 @@ export function useSettingsRestore(onRestored?: () => void) { chatWidth: DEFAULT_UNIFIED_SETTINGS.chatWidth, effortDisplay: DEFAULT_UNIFIED_SETTINGS.effortDisplay, mathRenderingEnabled: DEFAULT_UNIFIED_SETTINGS.mathRenderingEnabled, + language: DEFAULT_UNIFIED_SETTINGS.language, timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat, notificationMode: DEFAULT_UNIFIED_SETTINGS.notificationMode, inAppNotificationsEnabled: DEFAULT_UNIFIED_SETTINGS.inAppNotificationsEnabled, @@ -760,34 +764,54 @@ function AutoSettleDaysInput({ ); } +/** Row anchor props with the registry title in the active language. */ +function useTranslatedSearchableSetting() { + const m = useMessages(); + return (id: SettingsSearchItemId) => { + const setting = searchableSetting(id); + return { ...setting, title: m(setting.title) }; + }; +} + export function GeneralSettingsPanel() { + const gt = useGT(); + const m = useMessages(); + const setting = useTranslatedSearchableSetting(); const settings = useScopedSettings(); const updateSettings = useUpdateScopedSettings(); const lastEnabledProjectGroupingMode = useRef( readLastEnabledProjectGroupingMode(), ); + const languageValue = SUPPORTED_LOCALES.includes(settings.language) + ? settings.language + : SYSTEM_LANGUAGE; return ( - + + Show a toast when another thread finishes, fails, or needs input or approval while + this app has focus. + + } control={ updateSettings({ inAppNotificationsEnabled: checked })} - aria-label="In-app notifications" + aria-label={gt("In-app notifications")} /> } /> - + Combine matching repositories across environments.} resetAction={ settings.sidebarProjectGroupingMode !== DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode ? ( @@ -816,13 +840,13 @@ export function GeneralSettingsPanel() { ), }); }} - aria-label="Project grouping" + aria-label={gt("Project grouping")} /> } /> Order of projects in the sidebar project picker and command palette.} resetAction={ settings.sidebarProjectSortOrder !== DEFAULT_UNIFIED_SETTINGS.sidebarProjectSortOrder ? ( @@ -845,15 +869,15 @@ export function GeneralSettingsPanel() { } }} > - + - {SIDEBAR_PROJECT_SORT_ORDER_LABELS[settings.sidebarProjectSortOrder]} + {m(SIDEBAR_PROJECT_SORT_ORDER_LABELS[settings.sidebarProjectSortOrder])} {SidebarProjectSortOrder.literals.map((sortOrder) => ( - {SIDEBAR_PROJECT_SORT_ORDER_LABELS[sortOrder]} + {m(SIDEBAR_PROJECT_SORT_ORDER_LABELS[sortOrder])} ))} @@ -861,8 +885,13 @@ export function GeneralSettingsPanel() { } /> + Fold working and monitoring threads into a Working section. They return to the top of + the inbox when they need you. The boring sidebar in Labs has no Working section. + + } resetAction={ settings.sidebarWorkingShelfEnabled !== DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled ? ( @@ -882,16 +911,16 @@ export function GeneralSettingsPanel() { onCheckedChange={(checked) => updateSettings({ sidebarWorkingShelfEnabled: Boolean(checked) }) } - aria-label="Working section" + aria-label={gt("Working section")} /> } /> - + Ask before unpinning a thread from the pinned section.} resetAction={ settings.confirmThreadUnpin !== DEFAULT_UNIFIED_SETTINGS.confirmThreadUnpin ? ( updateSettings({ confirmThreadUnpin: Boolean(checked) }) } - aria-label="Confirm thread unpinning" + aria-label={gt("Confirm thread unpinning")} /> } /> Require a second click on the inline archive action before a thread is archived. + } resetAction={ settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive ? ( updateSettings({ confirmThreadArchive: Boolean(checked) }) } - aria-label="Confirm thread archiving" + aria-label={gt("Confirm thread archiving")} /> } /> Ask before deleting a thread and its chat history.} resetAction={ settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete ? ( updateSettings({ confirmThreadDelete: Boolean(checked) }) } - aria-label="Confirm thread deletion" + aria-label={gt("Confirm thread deletion")} /> } /> {isElectron ? ( Hold mode also quits on two quick presses.} resetAction={ settings.confirmQuit !== DEFAULT_UNIFIED_SETTINGS.confirmQuit ? ( - {QUIT_CONFIRMATION_MODE_LABELS[settings.confirmQuit]} + + {m(QUIT_CONFIRMATION_MODE_LABELS[settings.confirmQuit])} + {Object.entries(QUIT_CONFIRMATION_MODE_LABELS).map(([value, label]) => ( - {label} + {m(label)} ))} @@ -1007,10 +1040,54 @@ export function GeneralSettingsPanel() { ) : null} - + System default follows your browser or OS language.} + resetAction={ + settings.language !== DEFAULT_UNIFIED_SETTINGS.language ? ( + + updateSettings({ + language: DEFAULT_UNIFIED_SETTINGS.language, + }) + } + /> + ) : null + } + control={ + + } + /> + System default follows your browser or OS clock preference.} resetAction={ settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat ? ( - - {TIMESTAMP_FORMAT_LABELS[settings.timestampFormat]} + + {m(TIMESTAMP_FORMAT_LABELS[settings.timestampFormat])} - {TIMESTAMP_FORMAT_LABELS.locale} + {m(TIMESTAMP_FORMAT_LABELS.locale)} - {TIMESTAMP_FORMAT_LABELS["12-hour"]} + {m(TIMESTAMP_FORMAT_LABELS["12-hour"])} - {TIMESTAMP_FORMAT_LABELS["24-hour"]} + {m(TIMESTAMP_FORMAT_LABELS["24-hour"])} diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 2b7a085ede053..c34c48694ae87 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -35,6 +35,7 @@ import { } from "lucide-react"; import { resolveEventKeys } from "@t3tools/shared/keybindings"; import { useLocation, useNavigate } from "@tanstack/react-router"; +import { T, useGT, useMessages } from "gt-react"; import { cn } from "../../lib/utils"; import { Button } from "../ui/button"; @@ -129,7 +130,9 @@ function SettingsSectionIcon({ to }: { to: SettingsPath }) { } export function SettingsSidebarNav({ pathname }: { pathname: string }) { - const navArea = workspaceAreaProps("settings-nav", 0, "Settings sections"); + const gt = useGT(); + const m = useMessages(); + const navArea = workspaceAreaProps("settings-nav", 0, gt("Settings sections")); const navigate = useNavigate(); const currentHash = useLocation({ select: (location) => location.hash }); const activePath = SETTINGS_DETAIL_PAGE_PARENTS[pathname] ?? pathname; @@ -139,7 +142,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { const [compactSearchOpen, setCompactSearchOpen] = useState(false); const [activeResultIndex, setActiveResultIndex] = useState(0); const searchableItems = useAvailableSettingsSearchItems(); - const results = searchSettings(query, searchableItems); + const results = searchSettings(query, searchableItems, m); const isSearching = query.trim().length > 0; const hasResults = results.length > 0; const maxResultIndex = Math.max(results.length - 1, 0); @@ -285,8 +288,8 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { onBlur={() => { if (!isSearching) setCompactSearchOpen(false); }} - placeholder="Search" - aria-label="Search settings" + placeholder={gt("Search")} + aria-label={gt("Search settings")} role="combobox" aria-autocomplete="list" aria-expanded={isSearching && hasResults} @@ -304,7 +307,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { size="icon-micro" variant="ghost-muted" className="shrink-0" - aria-label="Clear settings search" + aria-label={gt("Clear settings search")} onClick={() => { clearSearch(); searchInputRef.current?.focus(); @@ -321,14 +324,14 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { role="status" className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground" > - No settings found + No settings found

) : null} {isSearching ? ( {results.map((item, index) => ( - {item.title} + {m(item.title)} - {SETTINGS_SECTION_LABELS[item.to]} + {m(SETTINGS_SECTION_LABELS[item.to])} @@ -366,7 +369,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { setCompactSearchOpen(true)} > @@ -388,7 +391,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { !compactSearchOpen && "max-md:sr-only", )} > - {group.heading} + {m(group.heading)} ) : null} {/* The heading stays outside the group it names so NVDA does not read the name twice. */} @@ -415,7 +418,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { !compactSearchOpen && "max-md:sr-only", )} > - {SETTINGS_SECTION_LABELS[to]} + {m(SETTINGS_SECTION_LABELS[to])} diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index c360265f81e31..cb3b446d6d02f 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -64,6 +64,8 @@ describe("searchSettings", () => { expect(searchSettings("sharing", ITEMS).map((item) => item.id)).toEqual(["network-access"]); expect(searchSettings("claude", ITEMS).map((item) => item.id)).toEqual(["providers"]); expect(searchSettings("long lines", ITEMS).map((item) => item.id)).toEqual(["word-wrap"]); + const spanish = (message: string) => (message === "Word wrap" ? "Ajuste de línea" : message); + expect(searchSettings("ajuste", ITEMS, spanish).map((item) => item.id)).toEqual(["word-wrap"]); for (const query of ["fallback", "fallback agent", "fallback model"]) { expect(searchSettings(query)[0]).toMatchObject({ id: "fallback-model", diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 4f61ba41c0d86..567a5d6e2aba6 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -10,6 +10,7 @@ import { } from "@t3tools/client-runtime/source-control-clients"; import { DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings"; import * as Schema from "effect/Schema"; +import { msg } from "gt-react"; import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts"; import { writeLocalStorageValue } from "../../hooks/useLocalStorage"; import { commandLabel } from "./KeybindingsSettings.logic"; @@ -92,29 +93,29 @@ export interface SettingsSearchAvailability { } export const SETTINGS_SECTION_LABELS: Readonly> = { - "/settings/diagnostics": "Diagnostics", - "/settings/projects": "Projects", - "/settings/general": "General", - "/settings/appearance": "Appearance", - "/settings/chat": "Chat", - "/settings/diffs": "Diffs & pull requests", - "/settings/keybindings": "Keybindings", - "/settings/snap-shot": "SnapShots", - "/settings/providers": "Providers", - "/settings/threads": "Threads", - "/settings/browser": "Browser", - "/settings/devices": "Devices", - "/settings/scheduled-tasks": "Scheduled tasks", - "/settings/source-control": "Source control", - "/settings/worktrees": "Worktrees", - "/settings/connections": "Environments", - "/settings/access": "Sharing & access", - "/settings/secrets": "Secrets", - "/settings/maintenance": "Maintenance", - "/settings/labs": "Labs", - "/settings/about": "About", - "/settings/voice": "Voice", - "/settings/archived": "Archive", + "/settings/diagnostics": msg("Diagnostics"), + "/settings/projects": msg("Projects"), + "/settings/general": msg("General"), + "/settings/appearance": msg("Appearance"), + "/settings/chat": msg("Chat"), + "/settings/diffs": msg("Diffs & pull requests"), + "/settings/keybindings": msg("Keybindings"), + "/settings/snap-shot": msg("SnapShots"), + "/settings/providers": msg("Providers"), + "/settings/threads": msg("Threads"), + "/settings/browser": msg("Browser"), + "/settings/devices": msg("Devices"), + "/settings/scheduled-tasks": msg("Scheduled tasks"), + "/settings/source-control": msg("Source control"), + "/settings/worktrees": msg("Worktrees"), + "/settings/connections": msg("Environments"), + "/settings/access": msg("Sharing & access"), + "/settings/secrets": msg("Secrets"), + "/settings/maintenance": msg("Maintenance"), + "/settings/labs": msg("Labs"), + "/settings/about": msg("About"), + "/settings/voice": msg("Voice"), + "/settings/archived": msg("Archive"), }; /** Sidebar order. A group without a heading is set apart by space alone. */ @@ -135,7 +136,7 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ ], }, { - heading: "Agents", + heading: msg("Agents"), paths: [ "/settings/providers", "/settings/threads", @@ -145,11 +146,11 @@ export const SETTINGS_NAV_GROUPS: ReadonlyArray<{ ], }, { - heading: "Code", + heading: msg("Code"), paths: ["/settings/projects", "/settings/source-control", "/settings/worktrees"], }, { - heading: "Connections", + heading: msg("Connections"), paths: [ "/settings/connections", "/settings/access", @@ -425,13 +426,13 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "project-grouping", - title: "Project grouping", + title: msg("Project grouping"), to: "/settings/general", searchTerms: ["combine matching repositories environments sidebar"], }, { id: "project-order", - title: "Project order", + title: msg("Project order"), to: "/settings/general", searchTerms: ["sort projects sidebar manual created recent"], }, @@ -457,7 +458,7 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "working-shelf", - title: "Working section", + title: msg("Working section"), to: "/settings/general", searchTerms: ["hide fold running monitoring threads inbox sidebar shelf"], }, @@ -674,13 +675,19 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "in-app-notifications", - title: "In-app notifications", + title: msg("In-app notifications"), to: "/settings/general", searchTerms: ["notification toast popup completion input approval failure"], }, + { + id: "language", + title: msg("Language"), + to: "/settings/general", + searchTerms: ["locale translation english español spanish chinese 中文 idioma 语言"], + }, { id: "time-format", - title: "Time format", + title: msg("Time format"), to: "/settings/general", searchTerms: ["timestamp clock locale system browser os 12 hour 24 hour"], }, @@ -803,25 +810,25 @@ export const SETTINGS_SEARCH_ITEMS = [ }, { id: "unpin-confirmation", - title: "Unpin confirmation", + title: msg("Unpin confirmation"), to: "/settings/general", searchTerms: ["ask before thread pinned section"], }, { id: "archive-confirmation", - title: "Archive confirmation", + title: msg("Archive confirmation"), to: "/settings/general", searchTerms: ["ask before thread second click inline action"], }, { id: "delete-confirmation", - title: "Delete confirmation", + title: msg("Delete confirmation"), to: "/settings/general", searchTerms: ["ask before thread chat history"], }, { id: "quit-confirmation", - title: "Quit shortcut", + title: msg("Quit shortcut"), to: "/settings/general", searchTerms: ["confirmation desktop app exit direct hold double click press twice"], desktopOnly: true, @@ -1506,6 +1513,7 @@ export function settingsForThisPlatform( export function searchSettings( query: string, items: ReadonlyArray = SETTINGS_SEARCH_ITEMS, + translate: (message: string) => string = (message) => message, ): ReadonlyArray { const normalizedQuery = normalizeSearchText(query); if (normalizedQuery.length === 0) return []; @@ -1517,6 +1525,9 @@ export function searchSettings( const fields = [ title, normalizeSearchText(SETTINGS_SECTION_LABELS[item.to]), + // The labels as displayed, so search also works in the active language. + normalizeSearchText(translate(item.title)), + normalizeSearchText(translate(SETTINGS_SECTION_LABELS[item.to])), ...(item.searchTerms ?? []).map(normalizeSearchText), ]; if (!queryTokens.every((token) => fields.some((field) => field.includes(token)))) return []; diff --git a/apps/web/src/i18n/I18nProvider.tsx b/apps/web/src/i18n/I18nProvider.tsx new file mode 100644 index 0000000000000..d676e7f72b58e --- /dev/null +++ b/apps/web/src/i18n/I18nProvider.tsx @@ -0,0 +1,15 @@ +import { GTProvider } from "gt-react"; +import { useSyncExternalStore, type ReactNode } from "react"; + +import { getI18nSnapshot, persistGTLocale, subscribeI18n } from "./runtime"; + +const reloadToSetting = (state: { readonly locale: string }) => persistGTLocale(state.locale); + +export function I18nProvider({ children }: { readonly children: ReactNode }) { + const { locale, translations } = useSyncExternalStore(subscribeI18n, getI18nSnapshot); + return ( + + {children} + + ); +} diff --git a/apps/web/src/i18n/initializeI18n.ts b/apps/web/src/i18n/initializeI18n.ts new file mode 100644 index 0000000000000..9f6ba94900288 --- /dev/null +++ b/apps/web/src/i18n/initializeI18n.ts @@ -0,0 +1,21 @@ +import { initializeGTSPA } from "gt-react"; + +import { DEFAULT_LOCALE, SUPPORTED_LOCALES } from "./locales"; + +// English is the source text, so it never loads a chunk. +async function loadTranslations(locale: string): Promise { + if (locale === DEFAULT_LOCALE) return {}; + const module: { default: unknown } = await import(`./translations/${locale}.json`); + return module.default; +} + +/** Sets up GT's singletons. `onLocaleRequest` receives GT's own locale changes. */ +export function initializeI18n(onLocaleRequest: (locale: string) => void): void { + void initializeGTSPA({ + defaultLocale: DEFAULT_LOCALE, + locales: [...SUPPORTED_LOCALES], + locale: DEFAULT_LOCALE, + loadTranslations, + _reload: (state) => onLocaleRequest(state.locale), + }); +} diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts new file mode 100644 index 0000000000000..a55d6f86ca946 --- /dev/null +++ b/apps/web/src/i18n/locales.ts @@ -0,0 +1,37 @@ +import gtConfig from "../../gt.config.json"; + +export const SYSTEM_LANGUAGE = "system"; +export const DEFAULT_LOCALE = gtConfig.defaultLocale; +export const SUPPORTED_LOCALES: ReadonlyArray = [DEFAULT_LOCALE, ...gtConfig.locales]; + +// Shown in their own language so a user can find theirs from any UI language. +const NATIVE_LANGUAGE_NAMES: Readonly> = { + en: "English", + es: "Español", + zh: "中文(简体)", +}; + +export function nativeLanguageName(locale: string): string { + return NATIVE_LANGUAGE_NAMES[locale] ?? locale; +} + +// Our `zh` is Simplified, so Traditional tags only match an exact locale. +const TRADITIONAL_CHINESE = /^zh[-_](hant|tw|hk|mo)\b/; + +function matchSupportedLocale(tag: string): string | undefined { + const normalized = tag.trim().toLowerCase(); + const language = normalized.split(/[-_]/)[0]; + const exact = SUPPORTED_LOCALES.find((locale) => locale.toLowerCase() === normalized); + if (exact || TRADITIONAL_CHINESE.test(normalized)) return exact; + return SUPPORTED_LOCALES.find((locale) => locale.toLowerCase() === language); +} + +/** Saved setting to active locale; "system" and unknown values follow the host's languages. */ +export function resolveLocale(language: string, systemLocales: ReadonlyArray): string { + if (SUPPORTED_LOCALES.includes(language)) return language; + for (const tag of systemLocales) { + const match = matchSupportedLocale(tag); + if (match) return match; + } + return DEFAULT_LOCALE; +} diff --git a/apps/web/src/i18n/runtime.ts b/apps/web/src/i18n/runtime.ts new file mode 100644 index 0000000000000..82b3f8d6ceb8d --- /dev/null +++ b/apps/web/src/i18n/runtime.ts @@ -0,0 +1,84 @@ +import { getTranslationsSnapshot } from "gt-react"; + +import { + getClientSettings, + subscribeClientSettings, + updateClientSettings, +} from "../hooks/useSettings"; +import { initializeI18n } from "./initializeI18n"; +import { DEFAULT_LOCALE, resolveLocale } from "./locales"; + +type LocaleTranslations = Awaited>; + +export interface I18nSnapshot { + readonly locale: string; + readonly translations: LocaleTranslations; +} + +const loadedTranslations: LocaleTranslations = { [DEFAULT_LOCALE]: {} }; +const pendingLoads = new Map>(); +const listeners = new Set<() => void>(); +let snapshot: I18nSnapshot = { locale: DEFAULT_LOCALE, translations: { ...loadedTranslations } }; +let requestedLocale = DEFAULT_LOCALE; + +function loadLocale(locale: string): Promise { + if (locale in loadedTranslations) return Promise.resolve(); + let load = pendingLoads.get(locale); + if (!load) { + // GT resolves a failed load to an empty catalog. Leave it uncached: English renders now + // and the next request retries. + load = getTranslationsSnapshot(locale).then((loaded) => { + pendingLoads.delete(locale); + const translations = loaded[locale]; + if (translations && Object.keys(translations).length > 0) { + loadedTranslations[locale] = translations; + } + }); + pendingLoads.set(locale, load); + } + return load; +} + +function activateLocale(locale: string): void { + if (requestedLocale !== locale) return; + if (snapshot.locale === locale && snapshot.translations[locale] === loadedTranslations[locale]) { + return; + } + snapshot = { locale, translations: { ...loadedTranslations } }; + document.documentElement.lang = locale; + for (const listener of listeners) listener(); +} + +function applyLanguageSetting(): void { + // Not desktopBridge.getSystemLocale(): that is the regional/time locale, not the UI language. + requestedLocale = resolveLocale(getClientSettings().language, navigator.languages); + void whenLocaleReady(); +} + +/** GT's own locale setters write the saved setting, which stays the only source of truth. */ +export function persistGTLocale(locale: string): void { + void updateClientSettings({ language: locale }); +} + +export function startI18n(): void { + initializeI18n(persistGTLocale); + subscribeClientSettings(applyLanguageSetting); + applyLanguageSetting(); +} + +/** Resolves once the requested locale's translations are ready; immediate for English. */ +export function whenLocaleReady(): Promise { + const locale = requestedLocale; + return loadLocale(locale).then(() => activateLocale(locale)); +} + +export function subscribeI18n(listener: () => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export function getI18nSnapshot(): I18nSnapshot { + return snapshot; +} diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json new file mode 100644 index 0000000000000..5e09077eff8be --- /dev/null +++ b/apps/web/src/i18n/translations/en.json @@ -0,0 +1,74 @@ +{ + "0a75e464d833bca8": "Settings", + "6aa1c88c4fa5be28": "Diagnostics", + "fb29e435b1219373": "Open source licenses", + "c0b0406e0cafa1d1": "Last user message", + "cb0775162a9b6419": "Created at", + "62570d4bfe4ab517": "Manual", + "7eed14b9c7fd7661": "System default", + "7fa9414ef5e9dd6c": "12-hour", + "2f42917064c97f09": "24-hour", + "7e8c995646a967d3": "Direct", + "51497bd401292062": "Hold", + "9d6cc6ac23312071": "Double press", + "e1483914168d6b8e": "Notifications", + "798dc6846ed39fa0": "In-app notifications", + "d9b0fbd680d5f175": "Sidebar", + "cd5452cc9e13c818": "Project grouping", + "6147d6fc04079525": "Project order", + "bdf39fd139a04325": "Working section", + "76f3c3e2f8dd0120": "Confirmations", + "859e386f8af841f0": "Confirm thread unpinning", + "de0d79b74d3e4af6": "Confirm thread archiving", + "4ab8a4878cd80c77": "Confirm thread deletion", + "0c853c878aab1908": "Quit shortcut behavior", + "22e745b7db60e52f": "Display", + "2c1c93a646bbea6e": "Language", + "c7b0bcb64f48db85": "Timestamp format", + "cbf6a6bbc17e75e1": "Show a toast when another thread finishes, fails, or needs input or approval while this app has focus.", + "83ca942c7163904f": "Combine matching repositories across environments.", + "609da998ca13521e": "Order of projects in the sidebar project picker and command palette.", + "b4c541137a76b351": "Fold working and monitoring threads into a Working section. They return to the top of the inbox when they need you. The boring sidebar in Labs has no Working section.", + "e815f49e5abedcfd": "Ask before unpinning a thread from the pinned section.", + "41210f99adeeba78": "Require a second click on the inline archive action before a thread is archived.", + "84f3d2cefc8d2a74": "Ask before deleting a thread and its chat history.", + "3fc130f1e8170073": "Hold mode also quits on two quick presses.", + "72c7fda6ae301e6d": "System default follows your browser or OS language.", + "b9ebecdb8db71466": "System default follows your browser or OS clock preference.", + "425f7ce2f24cb248": "Settings sections", + "ee3e8bd8b7918aec": "Search", + "858561b97fdd72f2": "Search settings", + "fed2d32de2b0c566": "Clear settings search", + "833639e235c97484": "Settings search results", + "be82bbfef472ab44": "No settings found", + "cc84bfe0ee5d0174": "Projects", + "81d0d1e78b196630": "General", + "fa19046edd6cfbd4": "Appearance", + "afda415d2d75a5d3": "Chat", + "4beeab8d1814b251": "Diffs & pull requests", + "3b958faa12d54484": "Keybindings", + "1a6679bbe62703b2": "SnapShots", + "2f77cc3105ddd7f8": "Providers", + "6d9bf91f0d4b7ba3": "Threads", + "795854feef8d2f52": "Browser", + "9cc48e5c9ee46026": "Devices", + "2ab325baee3ec9a3": "Scheduled tasks", + "a4380762611c94e4": "Source control", + "4889f7885396c26b": "Worktrees", + "b5adbf54cbefee38": "Environments", + "1de0df2b8a4fb96e": "Sharing & access", + "4c70e3e7b3e6c493": "Secrets", + "79b768229c9ef672": "Maintenance", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "About", + "af4b7734da1d5ce7": "Voice", + "2a546119bf3879ee": "Archive", + "2632f324dc2d9c48": "Agents", + "58058320796d28f6": "Code", + "1a07e4d043f5df4e": "Connections", + "e5144f91364fd9b7": "Time format", + "7e4d81ca21a72019": "Unpin confirmation", + "1d5052cbe70d0b28": "Archive confirmation", + "d5dd27a4eb853248": "Delete confirmation", + "86b43caa9ff41ea2": "Quit shortcut" +} diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json new file mode 100644 index 0000000000000..eb0d16d62515f --- /dev/null +++ b/apps/web/src/i18n/translations/es.json @@ -0,0 +1,74 @@ +{ + "0a75e464d833bca8": "Ajustes", + "6aa1c88c4fa5be28": "Diagnóstico", + "fb29e435b1219373": "Licencias de código abierto", + "c0b0406e0cafa1d1": "Último mensaje", + "cb0775162a9b6419": "Fecha de creación", + "62570d4bfe4ab517": "Manual", + "7eed14b9c7fd7661": "Del sistema", + "7fa9414ef5e9dd6c": "12 horas", + "2f42917064c97f09": "24 horas", + "7e8c995646a967d3": "Directo", + "51497bd401292062": "Mantener pulsado", + "9d6cc6ac23312071": "Doble pulsación", + "e1483914168d6b8e": "Notificaciones", + "798dc6846ed39fa0": "Notificaciones en la app", + "d9b0fbd680d5f175": "Barra lateral", + "cd5452cc9e13c818": "Agrupación de proyectos", + "6147d6fc04079525": "Orden de proyectos", + "bdf39fd139a04325": "Sección Working", + "76f3c3e2f8dd0120": "Confirmaciones", + "859e386f8af841f0": "Confirmar al desfijar hilos", + "de0d79b74d3e4af6": "Confirmar al archivar hilos", + "4ab8a4878cd80c77": "Confirmar al eliminar hilos", + "0c853c878aab1908": "Comportamiento del atajo para salir", + "22e745b7db60e52f": "Pantalla", + "2c1c93a646bbea6e": "Idioma", + "c7b0bcb64f48db85": "Formato de marca de tiempo", + "cbf6a6bbc17e75e1": "Muestra un aviso cuando otro hilo termina, falla o necesita una respuesta o aprobación mientras la app está en primer plano.", + "83ca942c7163904f": "Combina los repositorios coincidentes de distintos entornos.", + "609da998ca13521e": "Orden de los proyectos en el selector de la barra lateral y en la paleta de comandos.", + "b4c541137a76b351": "Agrupa los hilos en curso y en seguimiento en una sección Working. Vuelven arriba de la bandeja de entrada cuando te necesitan. La boring sidebar de Labs no tiene sección Working.", + "e815f49e5abedcfd": "Pregunta antes de desfijar un hilo de la sección de fijados.", + "41210f99adeeba78": "Pide un segundo clic en la acción de archivar antes de archivar un hilo.", + "84f3d2cefc8d2a74": "Pregunta antes de eliminar un hilo y su historial de chat.", + "3fc130f1e8170073": "El modo mantener también sale con dos pulsaciones rápidas.", + "72c7fda6ae301e6d": "Del sistema usa el idioma de tu navegador o sistema operativo.", + "b9ebecdb8db71466": "Del sistema usa el formato de hora de tu navegador o sistema operativo.", + "425f7ce2f24cb248": "Secciones de ajustes", + "ee3e8bd8b7918aec": "Buscar", + "858561b97fdd72f2": "Buscar ajustes", + "fed2d32de2b0c566": "Borrar búsqueda de ajustes", + "833639e235c97484": "Resultados de búsqueda de ajustes", + "be82bbfef472ab44": "No se encontraron ajustes", + "cc84bfe0ee5d0174": "Proyectos", + "81d0d1e78b196630": "General", + "fa19046edd6cfbd4": "Apariencia", + "afda415d2d75a5d3": "Chat", + "4beeab8d1814b251": "Diffs y pull requests", + "3b958faa12d54484": "Atajos de teclado", + "1a6679bbe62703b2": "SnapShots", + "2f77cc3105ddd7f8": "Proveedores", + "6d9bf91f0d4b7ba3": "Hilos", + "795854feef8d2f52": "Navegador", + "9cc48e5c9ee46026": "Dispositivos", + "2ab325baee3ec9a3": "Tareas programadas", + "a4380762611c94e4": "Control de versiones", + "4889f7885396c26b": "Worktrees", + "b5adbf54cbefee38": "Entornos", + "1de0df2b8a4fb96e": "Compartir y acceso", + "4c70e3e7b3e6c493": "Secretos", + "79b768229c9ef672": "Mantenimiento", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "Acerca de", + "af4b7734da1d5ce7": "Voz", + "2a546119bf3879ee": "Archivo", + "2632f324dc2d9c48": "Agentes", + "58058320796d28f6": "Código", + "1a07e4d043f5df4e": "Conexiones", + "e5144f91364fd9b7": "Formato de hora", + "7e4d81ca21a72019": "Confirmación al desfijar", + "1d5052cbe70d0b28": "Confirmación al archivar", + "d5dd27a4eb853248": "Confirmación al eliminar", + "86b43caa9ff41ea2": "Atajo para salir" +} diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json new file mode 100644 index 0000000000000..8d7459a055f89 --- /dev/null +++ b/apps/web/src/i18n/translations/zh.json @@ -0,0 +1,74 @@ +{ + "0a75e464d833bca8": "设置", + "6aa1c88c4fa5be28": "诊断", + "fb29e435b1219373": "开源许可证", + "c0b0406e0cafa1d1": "最近一条用户消息", + "cb0775162a9b6419": "创建时间", + "62570d4bfe4ab517": "手动", + "7eed14b9c7fd7661": "系统默认", + "7fa9414ef5e9dd6c": "12 小时制", + "2f42917064c97f09": "24 小时制", + "7e8c995646a967d3": "直接", + "51497bd401292062": "长按", + "9d6cc6ac23312071": "按两次", + "e1483914168d6b8e": "通知", + "798dc6846ed39fa0": "应用内通知", + "d9b0fbd680d5f175": "侧边栏", + "cd5452cc9e13c818": "项目分组", + "6147d6fc04079525": "项目排序", + "bdf39fd139a04325": "Working 分区", + "76f3c3e2f8dd0120": "确认", + "859e386f8af841f0": "取消置顶线程前确认", + "de0d79b74d3e4af6": "归档线程前确认", + "4ab8a4878cd80c77": "删除线程前确认", + "0c853c878aab1908": "退出快捷键行为", + "22e745b7db60e52f": "显示", + "2c1c93a646bbea6e": "语言", + "c7b0bcb64f48db85": "时间戳格式", + "cbf6a6bbc17e75e1": "当本应用处于焦点时,如有其他线程完成、失败或需要输入或批准,显示提示。", + "83ca942c7163904f": "合并不同环境中相同的仓库。", + "609da998ca13521e": "侧边栏项目选择器和命令面板中的项目顺序。", + "b4c541137a76b351": "将进行中和监控中的线程收进 Working 分区。需要你处理时,它们会回到收件箱顶部。Labs 中的 boring sidebar 没有 Working 分区。", + "e815f49e5abedcfd": "从置顶分区取消置顶线程前询问。", + "41210f99adeeba78": "归档线程前需要再次点击行内归档按钮。", + "84f3d2cefc8d2a74": "删除线程及其聊天记录前询问。", + "3fc130f1e8170073": "长按模式下,快速按两次也会退出。", + "72c7fda6ae301e6d": "系统默认跟随浏览器或操作系统的语言。", + "b9ebecdb8db71466": "系统默认跟随浏览器或操作系统的时钟偏好。", + "425f7ce2f24cb248": "设置分区", + "ee3e8bd8b7918aec": "搜索", + "858561b97fdd72f2": "搜索设置", + "fed2d32de2b0c566": "清除设置搜索", + "833639e235c97484": "设置搜索结果", + "be82bbfef472ab44": "未找到设置", + "cc84bfe0ee5d0174": "项目", + "81d0d1e78b196630": "通用", + "fa19046edd6cfbd4": "外观", + "afda415d2d75a5d3": "聊天", + "4beeab8d1814b251": "差异与拉取请求", + "3b958faa12d54484": "快捷键", + "1a6679bbe62703b2": "SnapShots", + "2f77cc3105ddd7f8": "提供方", + "6d9bf91f0d4b7ba3": "线程", + "795854feef8d2f52": "浏览器", + "9cc48e5c9ee46026": "设备", + "2ab325baee3ec9a3": "计划任务", + "a4380762611c94e4": "源代码管理", + "4889f7885396c26b": "工作树", + "b5adbf54cbefee38": "环境", + "1de0df2b8a4fb96e": "共享与访问", + "4c70e3e7b3e6c493": "密钥", + "79b768229c9ef672": "维护", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "关于", + "af4b7734da1d5ce7": "语音", + "2a546119bf3879ee": "归档", + "2632f324dc2d9c48": "代理", + "58058320796d28f6": "代码", + "1a07e4d043f5df4e": "连接", + "e5144f91364fd9b7": "时间格式", + "7e4d81ca21a72019": "取消置顶确认", + "1d5052cbe70d0b28": "归档确认", + "d5dd27a4eb853248": "删除确认", + "86b43caa9ff41ea2": "退出快捷键" +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index d6cf4ce77b91b..4469f9cbf6ba3 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -8,6 +8,7 @@ import { hasCloudPublicConfig } from "./cloud/publicConfig"; import { isElectron } from "./env"; import { startAppServices } from "./appInit"; import { AppRoot } from "./AppRoot"; +import { whenLocaleReady } from "./i18n/runtime"; import { clearChunkReloadGuard, reloadOnceForChunkLoadError } from "./lib/chunkReloadGuard"; const router = startAppServices(); @@ -36,7 +37,8 @@ const managedAuthShellModule = export const startup = Promise.all([ managedAuthShellModule?.then((module) => module.default) ?? null, - router.load(), + // Chained so settings have usually hydrated; English resolves without a chunk load. + router.load().then(whenLocaleReady), ]) .then(([ManagedAuthShell]) => { // Route chunk failures resolve router.load() and surface later through the error boundary. diff --git a/apps/web/test/browserSetup.ts b/apps/web/test/browserSetup.ts index 5b40698aac075..90e4ffcb149f5 100644 --- a/apps/web/test/browserSetup.ts +++ b/apps/web/test/browserSetup.ts @@ -1,6 +1,8 @@ import { beforeEach } from "vite-plus/test"; import { commands } from "vite-plus/test/browser"; +import { initializeI18n } from "../src/i18n/initializeI18n"; + declare module "vite-plus/test/browser" { interface BrowserCommands { /** Defined in vite.config.ts. Moves Playwright's mouse off the page. */ @@ -15,3 +17,6 @@ declare module "vite-plus/test/browser" { beforeEach(async () => { await commands.resetPointer(); }); + +// The app initializes GT at startup; components using its hooks need the same here. +initializeI18n(() => {}); diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index b9cd3ad6b5e47..c60a2173e971e 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -30,6 +30,7 @@ "vite", "vite.config.ts", "vercel.ts", + "gt.config.json", "test", "scripts/verify-built-boot.ts", "scripts/warm-dep-cache.ts", diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 346213992e4b2..5622b7d32a86f 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -562,6 +562,8 @@ export const ClientSettingsSchema = Schema.Struct({ ), ), speechCorrectionWord: SpeechCorrectionCue.pipe(Schema.withDecodingDefault(Effect.succeed(""))), + // A locale code or "system". Open string so new locales and downgrades need no migration. + language: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed("en"))), snapShotEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), snapShotIncludeAccessibility: Schema.Boolean.pipe( Schema.withDecodingDefault(Effect.succeed(true)), @@ -2056,6 +2058,7 @@ export const ClientSettingsPatch = Schema.Struct({ speechRemoveFillerWords: Schema.optionalKey(Schema.Boolean), speechPostProcessingPrompt: Schema.optionalKey(SpeechPostProcessingPromptSettings), speechCorrectionWord: Schema.optionalKey(SpeechCorrectionCue), + language: Schema.optionalKey(Schema.String), snapShotEnabled: Schema.optionalKey(Schema.Boolean), snapShotIncludeAccessibility: Schema.optionalKey(Schema.Boolean), snapShotShortcut: Schema.optionalKey(SnapShotShortcut), diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f3d8eeb81a285..35e9c290c86f7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1163,6 +1163,9 @@ importers: fast-xml-parser: specifier: 5.7.3 version: 5.7.3 + gt-react: + specifier: 11.4.18 + version: 11.4.18(react-dom@19.3.0(react@19.3.0))(react@19.3.0) hast-util-to-html: specifier: ^9.0.5 version: 9.0.5 @@ -1296,6 +1299,9 @@ importers: compression: specifier: ^1.8.2 version: 1.8.2(supports-color@8.1.1) + gt: + specifier: 2.27.0 + version: 2.27.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) micromark-util-types: specifier: 'catalog:' version: 2.0.2 @@ -3340,10 +3346,16 @@ packages: resolution: {integrity: sha512-CuNiSqg7+e1cO/GjffyMOm5Tt2jUF9CWHHnvQ/UkqvtkGfHdgwEC0wpmq7fkN3gxwpRnrAN0WzO3vREKmNolMQ==} engines: {node: '>=18'} + '@clack/core@1.0.0-alpha.6': + resolution: {integrity: sha512-eG5P45+oShFG17u9I1DJzLkXYB1hpUgTLi32EfsMjSHLEqJUR8BOBCVFkdbUX2g08eh/HCi6UxNGpPhaac1LAA==} + '@clack/core@1.5.1': resolution: {integrity: sha512-iHTrHA8MtVuLl2TfZySmcKv1qO2PoyC9Z7pfSDozEuV5vtY3/wcOPKJXlqJ5Oq2Cx5DDGQGAMVx6HZfRRoVEbQ==} engines: {node: '>= 20.12.0'} + '@clack/prompts@1.0.0-alpha.6': + resolution: {integrity: sha512-75NCtYOgDHVBE2nLdKPTDYOaESxO0GLAKC7INREp5VbS988Xua1u+588VaGlcvXiLc/kSwc25Cd+4PeTSpY6QQ==} + '@clack/prompts@1.8.1': resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==} engines: {node: '>= 20.12.0'} @@ -4459,6 +4471,30 @@ packages: '@fontsource-variable/inter@5.3.0': resolution: {integrity: sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==} + '@generaltranslation/api@0.5.6': + resolution: {integrity: sha512-rPcqH7BomEIRQKX6oyOagfqrfHddi3EcOkgWC/dgs2qSRhkoZYcpn68RWCr3ZFnmCMib7uDtSR9v8BjUI7AZLQ==} + + '@generaltranslation/format@0.1.9': + resolution: {integrity: sha512-GwXbdajc7pIBsnrxVXE4PqjBHRwgKef4GyauH7CLaXSormRLU8G58ahqfwmQRL6ie1xt5KMMb6UAekdj1i9Sxg==} + + '@generaltranslation/icu@0.1.2': + resolution: {integrity: sha512-2A0txUrZdAWAc42N58/PtoWv7vNB0U1Iyl+nDzf7RSswLHPMsonp7OmPnSraQgkoRSVSlueARVQK4T+zanWsyA==} + + '@generaltranslation/python-extractor@0.2.64': + resolution: {integrity: sha512-9mif4P7pOwO6gj78/xX8Eo7Y46Vov4vEaMTeqySAKeJF4+SxPRMVzqquCEhnZM88uGTom48vbv0VWXcd7NBiyg==} + engines: {node: '>=16.0.0'} + + '@generaltranslation/react-core@11.4.18': + resolution: {integrity: sha512-1fFrMeddHH0mUTvg2iCSzL2Bfsc34j2EtL9hc4wxI8Xkwh2umHHtuZcD2Z3H7uA94w2kXEShgXe1kX/HFxqlOg==} + peerDependencies: + react: '>=18.0.0' + + '@generaltranslation/supported-locales@2.1.45': + resolution: {integrity: sha512-OqKHSJgvcMxWvUz74HLvvaI1c8brLslTNyAsh7RID4YUTxhL1OLbrd6HPJKPlURoExQ72lE+R3KHwtMt1wjOXg==} + + '@generaltranslation/vue-extractor@0.1.23': + resolution: {integrity: sha512-eGWcDLoFdJCcfNlwc16fBoTcjqfhS9e4UQo68wvceeK/2sMxYm+klGyEbOxC+pIXh5rhG9mK7l8sMzp4p1zVlA==} + '@handy-computer/models@0.2.3': resolution: {integrity: sha512-EcyPojMY8hG5adDZGR/2h/m9jniqAnSND00gmiAErRLB1BQqMD9jrJaqsfoYF/UfPC8ocKZFUNSkTegoYqjF5w==} engines: {node: '>=20.10'} @@ -4672,6 +4708,18 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@jsep-plugin/assignment@1.4.0': + resolution: {integrity: sha512-nw2Px23Eirx0PFTVoPrb3FEq9Wkmg6vxcDtt38MtBCf1G0tjLCB9cK+3seOXyiw+6+aalgYhvJabQbWwMVKlEQ==} + engines: {node: '>= 10.16.0'} + peerDependencies: + jsep: ^0.4.0||^1.0.0 + + '@jsep-plugin/regex@1.1.0': + resolution: {integrity: sha512-2Vkbda+XRjK6VTI6Lrh0sNBuMT8mZ51EhqMvO+V2rSdmqjs7NAGssxPZfkL23EFzYfSrvxyd1ZjOdqPQMM50og==} + engines: {node: '>= 10.16.0'} + peerDependencies: + jsep: ^0.4.0||^1.0.0 + '@koromix/koffi-android-arm64@3.3.6': resolution: {integrity: sha512-wxsPuEMDrqOR5RUdABYFNDTabhh/xwDetCUDI+/CN93QF1T7Yeq218kvDWmYT/g1wV2kU1aYdRO4D7cH9PDskw==} cpu: [arm64] @@ -5057,9 +5105,25 @@ packages: resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} engines: {node: ^14.21.3 || >=16} + '@noble/hashes@2.4.0': + resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==} + engines: {node: '>= 20.19.0'} + '@nodable/entities@2.1.1': resolution: {integrity: sha512-Pig3HxDIoMgjdEH8OCf/dkcTmLFjJRjWuq8jSnklu284/TKOPibSRERmOykiwmyXTtv61mP+44f3GMx0tLAyjg==} + '@nodelib/fs.scandir@2.1.5': + resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} + engines: {node: '>= 8'} + + '@nodelib/fs.stat@2.0.5': + resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} + engines: {node: '>= 8'} + + '@nodelib/fs.walk@1.2.8': + resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} + engines: {node: '>= 8'} + '@nornagon/put@0.0.8': resolution: {integrity: sha512-ugvXJjwF5ldtUpa7D95kruNJ41yFQDEKyF5CW4TgKJnh+W/zmlBzXXeKTyqIgwMFrkePN2JqOBqcF0M0oOunow==} engines: {node: '>=0.3.0'} @@ -6243,6 +6307,9 @@ packages: react: ^18.3.1 || ^19.0.0 react-dom: ^18.3.1 || ^19.0.0 + '@pinojs/redact@0.4.0': + resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} + '@polka/url@1.0.0-next.29': resolution: {integrity: sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww==} @@ -7510,6 +7577,9 @@ packages: '@vscode/l10n@0.0.18': resolution: {integrity: sha512-KYSIHVmslkaCDyw013pphY+d7x1qV8IZupYfeIfzNA+nsaWHbn5uPuQRvdRFsa9zFzGeudPuoGoZ1Op4jrJXIQ==} + '@vue/shared@3.5.45': + resolution: {integrity: sha512-ue9fgHmVNPlP7iW3+cxoBX/Cnlw53dHlVSw0JKGY6z1lObg8pHoj928M2nzG4/yVsMZ3NaRZ2s2z61uC16NDwQ==} + '@webgpu/types@0.1.74': resolution: {integrity: sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==} @@ -7682,6 +7752,11 @@ packages: resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} engines: {node: '>= 0.6'} + acorn-jsx@5.3.2: + resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} + peerDependencies: + acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 + acorn@8.16.0: resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} engines: {node: '>=0.4.0'} @@ -7868,6 +7943,10 @@ packages: resolution: {integrity: sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==} engines: {node: '>= 4.0.0'} + atomic-sleep@1.0.0: + resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==} + engines: {node: '>=8.0.0'} + atomically@1.7.0: resolution: {integrity: sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w==} engines: {node: '>=10.12.0'} @@ -8037,6 +8116,10 @@ packages: bun-types@1.3.14: resolution: {integrity: sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ==} + bundle-name@4.1.1: + resolution: {integrity: sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA==} + engines: {node: '>=18'} + bytes@3.1.2: resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} engines: {node: '>= 0.8'} @@ -8218,6 +8301,9 @@ packages: resolution: {integrity: sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==} engines: {node: '>=12.5.0'} + colorette@2.0.20: + resolution: {integrity: sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==} + combined-stream@1.0.8: resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} engines: {node: '>= 0.8'} @@ -8400,6 +8486,9 @@ packages: date-fns@4.4.0: resolution: {integrity: sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==} + dateformat@4.6.3: + resolution: {integrity: sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==} + dbus-next@0.10.2: resolution: {integrity: sha512-kLNQoadPstLgKKGIXKrnRsMgtAK/o+ix3ZmcfTfvBHzghiO9yHXpoKImGnB50EXwnfSFaSAullW/7UrSkAISSQ==} @@ -8442,6 +8531,14 @@ packages: resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} engines: {node: '>=10'} + default-browser-id@5.0.1: + resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==} + engines: {node: '>=18'} + + default-browser@5.5.1: + resolution: {integrity: sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==} + engines: {node: '>=18'} + defaults@1.0.4: resolution: {integrity: sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==} @@ -8457,6 +8554,10 @@ packages: resolution: {integrity: sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==} engines: {node: '>=8'} + define-lazy-prop@3.0.0: + resolution: {integrity: sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==} + engines: {node: '>=12'} + define-properties@1.2.1: resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} engines: {node: '>= 0.4'} @@ -8835,6 +8936,10 @@ packages: resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==} engines: {node: '>=0.12'} + entities@7.0.1: + resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==} + engines: {node: '>=0.12'} + entities@8.1.0: resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==} engines: {node: '>=20.19.0'} @@ -8878,6 +8983,11 @@ packages: es6-promise@3.3.1: resolution: {integrity: sha512-SOp9Phqvqn7jtEUxPWdWfWoLmyt2VaJ6MpvP9Comy1MceMXqE6bxvaTu4iaxpYYPzhny28Lc+M87/c2cPK6lDg==} + esbuild-wasm@0.27.7: + resolution: {integrity: sha512-1k03e2/tGz+sLz3/xzoZmUsIqtaGIvJa8k4UqUeqCUry83nHmlxQYZUUES0WBFUYilSQUf7nDUGAciIIklljSg==} + engines: {node: '>=18'} + hasBin: true + esbuild@0.28.2: resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} engines: {node: '>=18'} @@ -8905,6 +9015,9 @@ packages: estree-util-is-identifier-name@3.0.0: resolution: {integrity: sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg==} + estree-util-visit@2.0.0: + resolution: {integrity: sha512-m5KgiH85xAhhW8Wta0vShLcUvOsh3LLPI2YVwcbio1l7E09NTLL1EyMZFM1OyWowoH0skScNbhOPl4kcBgzTww==} + estree-walker@3.0.3: resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} @@ -9305,6 +9418,9 @@ packages: extend@3.0.2: resolution: {integrity: sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==} + fast-copy@4.3.1: + resolution: {integrity: sha512-CRzQaTFOFUs6PuhsAq7lk9Zqr995soJBcFNZlfJS/5keTSl1awREV9dZW4xS2nX4pWbhIIR0xp4h+J8PQxCkvg==} + fast-deep-equal@3.1.3: resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} @@ -9312,6 +9428,10 @@ packages: resolution: {integrity: sha512-Ywe6jodPTWOTL9/k0bV7gdfP8twKL5Y8I8CZ933fAY5gBekICZSUQTbyH6ut2NZCNyB05mSUwAuEqdEIaOOlDQ==} engines: {node: '>=6.0.0'} + fast-glob@3.3.3: + resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} + engines: {node: '>=8.6.0'} + fast-json-stable-stringify@2.1.0: resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} @@ -9347,6 +9467,12 @@ packages: resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} engines: {node: '>= 4.9.1'} + fastq@1.20.3: + resolution: {integrity: sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==} + + fault@2.0.1: + resolution: {integrity: sha512-WtySTkS4OKev5JtpHXnib4Gxiurzh5NCGvWrFaZ34m6JehfTUhKZvn9njTfw48t6JumVQOmrKqpmGcdwxnhqBQ==} + fb-dotslash@0.5.8: resolution: {integrity: sha512-XHYLKk9J4BupDxi9bSEhkfss0m+Vr9ChTrjhf9l2iw3jB5C7BnY4GVPoMcqbrTutsKJso6yj2nAB6BI/F2oZaA==} engines: {node: '>=20'} @@ -9432,10 +9558,17 @@ packages: resolution: {integrity: sha512-Wp1zXWPVUPBmfoa3Cqc9ctaKuzKAV6uLstRqlR56kSjplf5uAce+qeyYym7F+PHbGTk+tCEdkCW6RD7DX/gBZw==} engines: {node: '>=20'} + foreach@2.0.6: + resolution: {integrity: sha512-k6GAGDyqLe9JaebCsFCoudPPWfihKu8pylYXRlqP1J7ms39iPoTtk2fviNglIeQEwdh0bQeKJ01ZPyuyQvKzwg==} + form-data@4.0.6: resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==} engines: {node: '>= 6'} + format@0.2.2: + resolution: {integrity: sha512-wzsgA6WOq+09wrU1tsJ09udeR/YZRaeArL9e1wPbFg3GG2yDnC2ldKpxs4xunpFF9DgqCqOIra3bc1HWrJ37Ww==} + engines: {node: '>=0.4.x'} + formatly@0.7.0: resolution: {integrity: sha512-7CXJtIIA0zy/u12StsYk25qVKxvdLA2ep2sTNxK3ov0mGNIIDqIvAXDSgTnAfDJFsPfWjuz0WjfYSdpvnLA5Tg==} engines: {node: '>=18.3.0'} @@ -9491,6 +9624,9 @@ packages: function-bind@1.1.2: resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + generaltranslation@9.5.9: + resolution: {integrity: sha512-/R/MvEEiB+Us/fj/YfuSTfhvzUfmvFpiHxGx2f+C6Wv0O875T0yJI3RLGDopqZVbnKPimog9eXofJL7W0SOxJg==} + gensync@1.0.0-beta.2: resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} engines: {node: '>=6.9.0'} @@ -9529,6 +9665,10 @@ packages: github-slugger@2.0.0: resolution: {integrity: sha512-IaOQ9puYtjrkq7Y0Ygl9KDZnrf/aiUJYUpVf89y8kyaxbRG7Y1SrX/jaumrv81vc61+kiMempujsM3Yw7w5qcw==} + glob-parent@5.1.2: + resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} + engines: {node: '>= 6'} + glob-to-regexp@0.4.1: resolution: {integrity: sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==} @@ -9563,6 +9703,22 @@ packages: resolution: {integrity: sha512-cQOsSMS/IrDz82PVyRDvf/Q1F/bRbBVjJlh+xYOkI1qw2bWRvWGiWc+m2O0d6l4Bt1fyY+8kzJ8JFWGJqNeDBg==} engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0} + gt-i18n@1.0.40: + resolution: {integrity: sha512-EbDhYhtyUrZI4iBSWpe1AMRoYrmEn52/hnVG6NAqVhVvY85t15JCJWMdVOkDoB1TRVH9nbSzAttaYwcv0LF3KQ==} + + gt-react@11.4.18: + resolution: {integrity: sha512-c6T+oqvXdT2DSW6kXDc3HYj4MA9fR4B1VgSXaIVG8emAWhZ9Dih4npJBjRWBJNr1D3KrG0nU/+1FPxJ1Zzkhnw==} + peerDependencies: + react: '>=18.0.0' + react-dom: '>=18.0.0' + + gt-remark@1.0.12: + resolution: {integrity: sha512-mqW6BkvfLGHwtIIdsy3C0QW26HbZDJ7EdQz7c7pL8KZrLIBzbcu2rHVqWEoleeB5+TsqMQIFWRhsUt5UpbrDWw==} + + gt@2.27.0: + resolution: {integrity: sha512-VV0hxuHPZ5+BdTQBThIAwHuXK3ax8/OT3bcSXci/6Ch6ersbkENWanYZw5C3wjHEhNH9jMhkvYyzpOMH/GsGtg==} + hasBin: true + h3@1.15.11: resolution: {integrity: sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==} @@ -9619,6 +9775,9 @@ packages: heic-to@1.5.2: resolution: {integrity: sha512-8Fns+lZHAWmz5U5IUxDeXKwIf3foBoKNPLxxFY4B0MkLjNuomEIHCoDbDE+x/llFK3NCEO1cu4+n3iUKY+Svmw==} + help-me@5.0.0: + resolution: {integrity: sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==} + hermes-compiler@260318099.0.5: resolution: {integrity: sha512-4Gze+pGTGTUBRmnv6LtdOMo6ZzMMh3hEkvDiWzvuNL5LM0EO5YGhr8xh3fRjFaEqReUwEGjJGcGgEPFe9+E6Gw==} @@ -9648,6 +9807,9 @@ packages: resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==} engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} + html-entities@2.6.0: + resolution: {integrity: sha512-kig+rMn/QOVRvr7c86gQ8lWXq+Hkv6CbAH1hLu+RG338StTpE8Z0b44SDVaqVu7HGKf27frdmUYEs9hTUX/cLQ==} + html-escaper@3.0.3: resolution: {integrity: sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==} @@ -9753,18 +9915,36 @@ packages: engines: {node: '>=8'} hasBin: true + is-docker@3.0.0: + resolution: {integrity: sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + hasBin: true + is-docker@4.0.0: resolution: {integrity: sha512-LHE+wROyG/Y/0ZnbktRCoTix2c1RhgWaZraMZ8o1Q7zCh0VSrICJQO5oqIIISrcSBtrXv0o233w1IYwsWCjTzA==} engines: {node: '>=20'} hasBin: true + is-extglob@2.1.1: + resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} + engines: {node: '>=0.10.0'} + is-fullwidth-code-point@3.0.0: resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==} engines: {node: '>=8'} + is-glob@4.0.3: + resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} + engines: {node: '>=0.10.0'} + is-hexadecimal@2.0.1: resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==} + is-inside-container@1.0.0: + resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==} + engines: {node: '>=14.16'} + hasBin: true + is-interactive@2.0.0: resolution: {integrity: sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==} engines: {node: '>=12'} @@ -9795,6 +9975,10 @@ packages: resolution: {integrity: sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==} engines: {node: '>=8'} + is-wsl@3.1.1: + resolution: {integrity: sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==} + engines: {node: '>=16'} + isarray@1.0.0: resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} @@ -9849,9 +10033,16 @@ packages: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} hasBin: true + jose@6.2.17: + resolution: {integrity: sha512-wOuK9V1yujQFH5S0ZWmLcDZN7+IKh9bUCC2ZPCf2HDlol3WWHy+PPyNjEI75FXRLMp3vDKQcupP59xhVU95hcg==} + jose@6.2.2: resolution: {integrity: sha512-d7kPDd34KO/YnzaDOlikGpOurfF0ByC2sEV4cANCtdqLlTfBlw2p14O/5d/zv40gJPbIQxfES3nSx1/oYNyuZQ==} + joycon@3.1.1: + resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} + engines: {node: '>=10'} + js-base64@3.7.8: resolution: {integrity: sha512-hNngCeKxIUQiEUN3GPJOkz4wF/YvdUdbNL9hsBcMQTkKzboD7T/q3OYOuuPZLUE6dBxSGpwhk5mwuDud7JVAow==} @@ -9880,6 +10071,10 @@ packages: canvas: optional: true + jsep@1.6.0: + resolution: {integrity: sha512-Y8Tr54CX7B5YGAwo7/n8eumidEX3Opx98RyyQVnlHqUaZcPA8uUzL2v1rshr9ypW9Q6hNjfJtg3sL+8kaNE7TA==} + engines: {node: '>= 20.16.0'} + jsesc@3.1.0: resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} engines: {node: '>=6'} @@ -9888,6 +10083,9 @@ packages: json-buffer@3.0.1: resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} + json-pointer@0.6.2: + resolution: {integrity: sha512-vLWcKbOaXlO+jvRy4qNd+TI1QUPZzfJj1tpJ3vAXDych5XJf93ftpUKe5pKCrzyIIwgBJcOcCVRUfqQP25afBw==} + json-schema-to-ts@3.1.1: resolution: {integrity: sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==} engines: {node: '>=16'} @@ -9927,6 +10125,15 @@ packages: jsonfile@6.2.1: resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==} + jsonpath-plus@10.4.0: + resolution: {integrity: sha512-T92WWatJXmhBbKsgH/0hl+jxjdXrifi5IKeMY02DWggRxX0UElcbVzPlmgLTbvsPeW1PasQ6xE2Q75stkhGbsA==} + engines: {node: '>=18.0.0'} + hasBin: true + + jsonpointer@5.0.1: + resolution: {integrity: sha512-p/nXbhSEcu3pZRdkW1OfJhpsVtW1gd4Wa1fnQc9YLiTfAjn0312eMKimbdIQzuZl9aa9xUGaRlP9T/CJE/ditQ==} + engines: {node: '>=0.10.0'} + jszip@3.10.1: resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==} @@ -10156,6 +10363,9 @@ packages: mdast-util-from-markdown@2.0.3: resolution: {integrity: sha512-W4mAWTvSlKvf8L6J+VN9yLSqQ9AOAAvHuoDAmPkz4dHf553m5gVj2ejadHJhoJmcmxEnOv6Pa8XJhpxE93kb8Q==} + mdast-util-frontmatter@2.0.1: + resolution: {integrity: sha512-LRqI9+wdgC25P0URIJY9vwocIzCcksduHQ9OF2joxQoyTNVduwLAFUzjoopuRJbJAReaKrNQKAZKL3uCMugWJA==} + mdast-util-gfm-autolink-literal@2.0.1: resolution: {integrity: sha512-5HVP2MKaP6L+G6YaxPNjuL0BPrq9orG3TsrZ9YXbA3vDw/ACI4MEsnoDpn6ZNm7GnZgtAcONJyPhOP8tNJQavQ==} @@ -10183,6 +10393,9 @@ packages: mdast-util-mdx-jsx@3.2.0: resolution: {integrity: sha512-lj/z8v0r6ZtsN/cGNNtemmmfoLAFZnjMbNyLzBafjzikOM+glrjNHPlf6lQDOTccj9n5b0PPihEBbhneMyGs1Q==} + mdast-util-mdx@3.0.0: + resolution: {integrity: sha512-JfbYLAW7XnYTTbUsmpu0kdBUVe+yKVJZBItEjwyYJiDJuZ9w4eeaqks4HQO+R7objWgS2ymV60GYpI14Ug554w==} + mdast-util-mdxjs-esm@2.0.1: resolution: {integrity: sha512-EcmOpxsZ96CvlP03NghtH1EsLtr0n9Tm4lPUJUBccV9RwUOneqSycg19n5HGzCf+10LozMRSObtVr3ee1WoHtg==} @@ -10224,6 +10437,10 @@ packages: merge-stream@2.0.0: resolution: {integrity: sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==} + merge2@1.4.1: + resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} + engines: {node: '>= 8'} + meshoptimizer@0.22.0: resolution: {integrity: sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==} @@ -10291,6 +10508,9 @@ packages: micromark-extension-directive@4.0.0: resolution: {integrity: sha512-/C2nqVmXXmiseSSuCdItCMho7ybwwop6RrrRPk0KbOHW21JKoCldC+8rFOaundDoRBUWBnJJcxeA/Kvi34WQXg==} + micromark-extension-frontmatter@2.0.0: + resolution: {integrity: sha512-C4AkuM3dA58cgZha7zVnuVxBhDsbttIMiytjgsM2XbHAB2faRVaHRle40558FBN+DJcrLNCoqG5mlrpdU4cRtg==} + micromark-extension-gfm-autolink-literal@2.1.0: resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==} @@ -10315,12 +10535,30 @@ packages: micromark-extension-llm-math@3.1.0: resolution: {integrity: sha512-VIYHuIEk0gpHrojEtNGaxGwdpSLtdWYlLL2vu9PM4M1ilEtak10S8F9zzbNAPBNRoWFs/bjs+J7R3yUBoIQUEA==} + micromark-extension-mdx-expression@3.0.1: + resolution: {integrity: sha512-dD/ADLJ1AeMvSAKBwO22zG22N4ybhe7kFIZ3LsDI0GlsNr2A3KYxb0LdC1u5rj4Nw+CHKY0RVdnHX8vj8ejm4Q==} + + micromark-extension-mdx-jsx@3.0.2: + resolution: {integrity: sha512-e5+q1DjMh62LZAJOnDraSSbDMvGJ8x3cbjygy2qFEi7HCeUT4BDKCvMozPozcD6WmOt6sVvYDNBKhFSz3kjOVQ==} + + micromark-extension-mdx-md@2.0.0: + resolution: {integrity: sha512-EpAiszsB3blw4Rpba7xTOUptcFeBFi+6PY8VnJ2hhimH+vCQDirWgsMpz7w1XcZE7LVrSAUGb9VJpG9ghlYvYQ==} + + micromark-extension-mdxjs-esm@3.0.0: + resolution: {integrity: sha512-DJFl4ZqkErRpq/dAPyeWp15tGrcrrJho1hKK5uBS70BCtfrIFg81sqcTVu3Ta+KD1Tk5vAtBNElWxtAa+m8K9A==} + + micromark-extension-mdxjs@3.0.0: + resolution: {integrity: sha512-A873fJfhnJ2siZyUrJ31l34Uqwy4xIFmvPY1oj+Ean5PHcPBYzEsvqvWGaWcfEIr11O5Dlw3p2y0tZWpKHDejQ==} + micromark-factory-destination@2.0.1: resolution: {integrity: sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==} micromark-factory-label@2.0.1: resolution: {integrity: sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==} + micromark-factory-mdx-expression@2.0.3: + resolution: {integrity: sha512-kQnEtA3vzucU2BkrIa8/VaSAsP+EJ3CKOvhMuJgOEGg9KDC6OAY6nSnNDVRiVNRqj7Y4SlSzcStaH/5jge8JdQ==} + micromark-factory-space@2.0.1: resolution: {integrity: sha512-zRkxjtBxxLd2Sc0d+fbnEunsTj46SWXgXciZmHq0kDYGnck/ZSGj9/wULTV95uoeYiK5hRXP2mJ98Uo4cq/LQg==} @@ -10351,6 +10589,9 @@ packages: micromark-util-encode@2.0.1: resolution: {integrity: sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==} + micromark-util-events-to-acorn@2.0.3: + resolution: {integrity: sha512-jmsiEIiZ1n7X1Rr5k8wVExBQCg5jy4UXVADItHmNk1zkwEVhBuIUKRu3fqv+hs4nxLISi2DQGlqIOGiFxgbfHg==} + micromark-util-html-tag-name@2.0.1: resolution: {integrity: sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==} @@ -10617,6 +10858,9 @@ packages: oas-validator@5.0.8: resolution: {integrity: sha512-cu20/HE5N5HKqVygs3dt94eYJfBi0TsZvPVXDhbXQHiEityDN+RROTleefoKRKKJ9dFAF2JBkDHgvWj0sjKGmw==} + oauth4webapi@3.8.8: + resolution: {integrity: sha512-8N28E+a/oxfXWBgOMt+ZP/JUf/XR+IFbvkAEPP3gznXOMv9BpAAwiIj0TFNz3tGTPc0ZQ8zmWBNgN1nAys0gng==} + ob1@0.87.1: resolution: {integrity: sha512-i8iA8uij0g1YQzS8uOJPSRCgwDjO9warIHUAu1Fqj877Wc3wlfxDYBioYWgKTBF2+URVJttyDWSEpmd99nlvtQ==} engines: {node: ^22.13.0 || ^24.3.0 || >= 26.0.0} @@ -10647,6 +10891,10 @@ packages: ohash@2.0.12: resolution: {integrity: sha512-65S/5gk9YSsaRjcyf7Nfa6h/d3E8/1gslpXfI4W7Dxn/oap8IKRuNT5VXkLQ1YFKIEg4apRY4Pj6aiwFzrDdmw==} + on-exit-leak-free@2.1.2: + resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==} + engines: {node: '>=14.0.0'} + on-finished@2.3.0: resolution: {integrity: sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==} engines: {node: '>= 0.8'} @@ -10680,10 +10928,17 @@ packages: oniguruma-to-es@4.3.6: resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==} + open@10.2.0: + resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==} + engines: {node: '>=18'} + open@8.4.2: resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==} engines: {node: '>=12'} + openid-client@6.8.8: + resolution: {integrity: sha512-ZsucJA5Ad04Uv7YN4ql+s4GXNmb9uAYQwyJTsJx7CH/MX3JZioLE2pVKi1SC+YrbSLA4Px3Gi30dMjgOZtb6pA==} + ora@3.4.0: resolution: {integrity: sha512-eNwHudNbO1folBP3JsZ19v9azXWtQZjICdr3Q0TDPIaeBQ3mXLrh54wM+er0+hSp+dWKf+Z8KM58CYzEyIYxYg==} engines: {node: '>=6'} @@ -10910,6 +11165,20 @@ packages: resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} engines: {node: '>=12'} + pino-abstract-transport@3.0.0: + resolution: {integrity: sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==} + + pino-pretty@13.2.0: + resolution: {integrity: sha512-jjghD1ML+Di/WxjJDz6j6Y4FT7hIXOlb8h27AyJ+ohtAXJXH4PS/xkv7si+RCCIW59HMgZsMKTDgzdr0RhuRrg==} + hasBin: true + + pino-std-serializers@7.1.0: + resolution: {integrity: sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==} + + pino@10.4.0: + resolution: {integrity: sha512-bk1ZMTwG/Vymx+zPoa28MhNzucFvXJWp3csrSuxuHPSMeUettaCoQ5Jvg07mtC4JGNpcfTwz41oVCnNgBK9+vA==} + hasBin: true + pixelmatch@8.0.0: resolution: {integrity: sha512-cIqOLfh5k52us715qf3B3+kTOxZv+WDv77HN7xokLScYQGYQHi4m/ynoDIPpvF2LvCyUJGyvzY64i0QCXtzu1g==} hasBin: true @@ -11021,6 +11290,9 @@ packages: process-nextick-args@2.0.1: resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==} + process-warning@5.1.1: + resolution: {integrity: sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==} + progress@2.0.3: resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==} engines: {node: '>=0.4.0'} @@ -11106,6 +11378,12 @@ packages: resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} engines: {node: '>=0.6'} + queue-microtask@1.2.3: + resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} + + quick-format-unescaped@4.0.4: + resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==} + quick-lru@5.1.1: resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==} engines: {node: '>=10'} @@ -11301,6 +11579,9 @@ packages: resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==} engines: {node: '>= 20.19.0'} + real-require@1.0.0: + resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==} + redis-errors@1.2.0: resolution: {integrity: sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==} engines: {node: '>=4'} @@ -11355,12 +11636,18 @@ packages: remark-breaks@4.0.0: resolution: {integrity: sha512-IjEjJOkH4FuJvHZVIW0QCDWxcG96kCq7An/KVH2NfJe6rKZU2AsHeB3OEjPNRxi4QC34Xdx7I2KGYn6IpT7gxQ==} + remark-frontmatter@5.0.0: + resolution: {integrity: sha512-XTFYvNASMe5iPN0719nPrdItC9aU0ssC4v14mH1BCi1u0n1gAocqcujWUrByftZTbLhRtiKRyjYTSIOcr69UVQ==} + remark-gfm@4.0.1: resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==} remark-math@6.0.0: resolution: {integrity: sha512-MMqgnP74Igy+S3WwnhQ7kqGlEerTETXMvJhrUzDikVZ2/uogJCb+WHUg97hK9/jcfc0dkD73s3LN8zU49cTEtA==} + remark-mdx@3.1.1: + resolution: {integrity: sha512-Pjj2IYlUY3+D8x00UJsIOg5BEvfMyeI+2uLPn9VO9Wg4MEtN/VTIq2NEJQfde9PnX15KgtHyl9S0BcTnWrIuWg==} + remark-parse@11.0.0: resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==} @@ -11427,6 +11714,10 @@ packages: resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==} engines: {node: '>= 4'} + reusify@1.1.0: + resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} + engines: {iojs: '>=1.0.0', node: '>=0.10.0'} + rimraf@2.6.3: resolution: {integrity: sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==} deprecated: Rimraf versions prior to v4 are no longer supported @@ -11453,12 +11744,23 @@ packages: resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} engines: {node: '>= 18'} + run-applescript@7.1.0: + resolution: {integrity: sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==} + engines: {node: '>=18'} + + run-parallel@1.2.0: + resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} + safe-buffer@5.1.2: resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==} safe-buffer@5.2.1: resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + safe-stable-stringify@2.5.0: + resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} + engines: {node: '>=10'} + safer-buffer@2.1.2: resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} @@ -11488,6 +11790,9 @@ packages: resolution: {integrity: sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==} engines: {node: '>= 10.13.0'} + secure-json-parse@4.1.1: + resolution: {integrity: sha512-lnd81MQEZKjhW/Gd2TQqdd4XP6QYNdDW/EP+I7nTrFHP9y2LmaGPIHk9xsnzcOiEr1c39c/e84xFgGviQKBTRw==} + semver-compare@1.0.0: resolution: {integrity: sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==} @@ -11644,6 +11949,12 @@ packages: resolution: {integrity: sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==} engines: {node: '>= 18'} + sonic-boom@4.2.1: + resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==} + + sonic-boom@5.0.2: + resolution: {integrity: sha512-/JEruzo6yhNVhsLblTRchgTQHIt7SsdJP0YyrfWaNKjIOQDfrdZv9gwYraYCAsmKV39/LAdV31FLL5NCDpoL/A==} + source-map-js@1.2.2: resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} @@ -11756,6 +12067,10 @@ packages: resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} engines: {node: '>=12'} + strip-bom@3.0.0: + resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} + engines: {node: '>=4'} + strip-json-comments@5.0.3: resolution: {integrity: sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==} engines: {node: '>=14.16'} @@ -11839,6 +12154,10 @@ packages: engines: {node: '>=10'} hasBin: true + thread-stream@4.2.1: + resolution: {integrity: sha512-Stg6edJXC/6/xqGwSXwFokrUhChJ18amEjpKH89WrQQ0oVFDF+pUUcTpiwWhFUrE89Vf16FBOlwhaw+lescxMQ==} + engines: {node: '>=20'} + three@0.180.0: resolution: {integrity: sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w==} @@ -11950,6 +12269,10 @@ packages: ts-morph@28.0.0: resolution: {integrity: sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g==} + tsconfig-paths@4.2.0: + resolution: {integrity: sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg==} + engines: {node: '>=6'} + tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} @@ -12052,6 +12375,9 @@ packages: unist-util-is@6.0.1: resolution: {integrity: sha512-LsiILbtBETkDz8I9p1dQ0uyRUWuaQzd/cuEeS1hoRSyW5E5XGmTzlwY1OrNzzakGowI9Dr/I8HVaw4hTtnxy8g==} + unist-util-position-from-estree@2.0.0: + resolution: {integrity: sha512-KaFVRjoqLyF6YXCbVLNad/eS4+OfPQQn2yOd7zF/h5T/CSL2v8NpN6a5TPvtbXthAGw5nG+PuTtq+DdIZr+cRQ==} + unist-util-position@5.0.0: resolution: {integrity: sha512-fucsC7HjXvkB5R3kTCO7kUjRdrS0BJt3M/FPxmHMBOm8JQi2BsHAHFsy27E0EolP8rp0NzXsJ+jNPyDWvOJZPA==} @@ -12418,6 +12744,9 @@ packages: web-namespaces@2.0.1: resolution: {integrity: sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ==} + web-tree-sitter@0.26.13: + resolution: {integrity: sha512-5bUZ7vbQ1kcondet96wzP974+JfCZDeQ7bTpacICm2nnvHpa5cO0ByRsoMcAhUP+743vpkb4m0BFlVSm+Ye9VA==} + webcrypto-core@1.9.2: resolution: {integrity: sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==} @@ -12512,6 +12841,10 @@ packages: utf-8-validate: optional: true + wsl-utils@0.1.0: + resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==} + engines: {node: '>=18'} + xcode@4.0.0: resolution: {integrity: sha512-dDaoWzc9EP2fp9FS9PVZUkyvFxY4y1TOV9pcKaKLk++Ei/qb97XDFEVP7GnW7Osii/TzVABJ0jq2F+9/lq0TVA==} engines: {node: '>=14.17.0'} @@ -13524,11 +13857,22 @@ snapshots: dependencies: fontkitten: 1.0.3 + '@clack/core@1.0.0-alpha.6': + dependencies: + picocolors: 1.1.1 + sisteransi: 1.0.5 + '@clack/core@1.5.1': dependencies: fast-wrap-ansi: 0.2.2 sisteransi: 1.0.5 + '@clack/prompts@1.0.0-alpha.6': + dependencies: + '@clack/core': 1.0.0-alpha.6 + picocolors: 1.1.1 + sisteransi: 1.0.5 + '@clack/prompts@1.8.1': dependencies: '@clack/core': 1.5.1 @@ -14779,6 +15123,48 @@ snapshots: '@fontsource-variable/inter@5.3.0': {} + '@generaltranslation/api@0.5.6': {} + + '@generaltranslation/format@0.1.9': + dependencies: + '@generaltranslation/icu': 0.1.2 + + '@generaltranslation/icu@0.1.2': {} + + '@generaltranslation/python-extractor@0.2.64': + dependencies: + generaltranslation: 9.5.9 + web-tree-sitter: 0.26.13 + + '@generaltranslation/react-core@11.4.18(react@19.3.0)': + dependencies: + '@generaltranslation/format': 0.1.9 + generaltranslation: 9.5.9 + gt-i18n: 1.0.40 + react: 19.3.0 + + '@generaltranslation/supported-locales@2.1.45': + dependencies: + generaltranslation: 9.5.9 + + '@generaltranslation/vue-extractor@0.1.23(supports-color@8.1.1)': + dependencies: + '@babel/parser': 7.29.8 + '@babel/traverse': 7.29.7(supports-color@8.1.1) + '@babel/types': 7.29.8 + '@generaltranslation/format': 0.1.9 + '@vue/shared': 3.5.45 + enhanced-resolve: 5.24.5 + entities: 7.0.1 + es-module-lexer: 2.3.2 + fast-glob: 3.3.3 + generaltranslation: 9.5.9 + semver: 7.8.5 + tsconfig-paths: 4.2.0 + yaml: 2.9.0 + transitivePeerDependencies: + - supports-color + '@handy-computer/models@0.2.3': {} '@hono/node-server@2.1.6(hono@4.13.17)': @@ -14939,6 +15325,14 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.6.0 + '@jsep-plugin/assignment@1.4.0(jsep@1.6.0)': + dependencies: + jsep: 1.6.0 + + '@jsep-plugin/regex@1.1.0(jsep@1.6.0)': + dependencies: + jsep: 1.6.0 + '@koromix/koffi-android-arm64@3.3.6': optional: true @@ -15257,8 +15651,22 @@ snapshots: '@noble/hashes@1.8.0': {} + '@noble/hashes@2.4.0': {} + '@nodable/entities@2.1.1': {} + '@nodelib/fs.scandir@2.1.5': + dependencies: + '@nodelib/fs.stat': 2.0.5 + run-parallel: 1.2.0 + + '@nodelib/fs.stat@2.0.5': {} + + '@nodelib/fs.walk@1.2.8': + dependencies: + '@nodelib/fs.scandir': 2.1.5 + fastq: 1.20.3 + '@nornagon/put@0.0.8': {} '@noxcturnal/noxcturnal-darwin-arm64@0.1.12': @@ -15903,6 +16311,8 @@ snapshots: - '@shikijs/themes' - shiki + '@pinojs/redact@0.4.0': {} + '@polka/url@1.0.0-next.29': {} '@puppeteer/browsers@3.2.6(yauzl@3.4.0)': @@ -17235,6 +17645,8 @@ snapshots: '@vscode/l10n@0.0.18': {} + '@vue/shared@3.5.45': {} + '@webgpu/types@0.1.74': {} '@xmldom/xmldom@0.8.15': {} @@ -17334,6 +17746,10 @@ snapshots: mime-types: 3.0.2 negotiator: 1.0.0 + acorn-jsx@5.3.2(acorn@8.16.0): + dependencies: + acorn: 8.16.0 + acorn@8.16.0: {} agent-base@7.1.4: {} @@ -17619,6 +18035,8 @@ snapshots: at-least-node@1.0.0: {} + atomic-sleep@1.0.0: {} + atomically@1.7.0: {} await-lock@2.2.2: {} @@ -17865,6 +18283,10 @@ snapshots: '@types/node': 24.12.4 optional: true + bundle-name@4.1.1: + dependencies: + run-applescript: 7.1.0 + bytes@3.1.2: {} bytestreamjs@2.0.1: {} @@ -18015,6 +18437,8 @@ snapshots: color-convert: 2.0.1 color-string: 1.9.1 + colorette@2.0.20: {} + combined-stream@1.0.8: dependencies: delayed-stream: 1.0.0 @@ -18189,6 +18613,8 @@ snapshots: date-fns@4.4.0: {} + dateformat@4.6.3: {} + dbus-next@0.10.2(patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4): dependencies: '@nornagon/put': 0.0.8 @@ -18231,6 +18657,13 @@ snapshots: dependencies: mimic-response: 3.1.0 + default-browser-id@5.0.1: {} + + default-browser@5.5.1: + dependencies: + bundle-name: 4.1.1 + default-browser-id: 5.0.1 + defaults@1.0.4: dependencies: clone: 1.0.4 @@ -18246,6 +18679,8 @@ snapshots: define-lazy-prop@2.0.0: {} + define-lazy-prop@3.0.0: {} + define-properties@1.2.1: dependencies: define-data-property: 1.1.4 @@ -18513,6 +18948,8 @@ snapshots: entities@6.0.1: {} + entities@7.0.1: {} + entities@8.1.0: {} env-paths@2.2.1: {} @@ -18547,6 +18984,8 @@ snapshots: es6-promise@3.3.1: {} + esbuild-wasm@0.27.7: {} + esbuild@0.28.2: optionalDependencies: '@esbuild/aix-ppc64': 0.28.2 @@ -18588,6 +19027,11 @@ snapshots: estree-util-is-identifier-name@3.0.0: {} + estree-util-visit@2.0.0: + dependencies: + '@types/estree-jsx': 1.0.5 + '@types/unist': 3.0.3 + estree-walker@3.0.3: dependencies: '@types/estree': 1.0.9 @@ -19087,12 +19531,21 @@ snapshots: extend@3.0.2: {} + fast-copy@4.3.1: {} + fast-deep-equal@3.1.3: {} fast-equals@5.4.2: {} - fast-json-stable-stringify@2.1.0: - optional: true + fast-glob@3.3.3: + dependencies: + '@nodelib/fs.stat': 2.0.5 + '@nodelib/fs.walk': 1.2.8 + glob-parent: 5.1.2 + merge2: 1.4.1 + micromatch: 4.0.8 + + fast-json-stable-stringify@2.1.0: {} fast-png@8.0.0: dependencies: @@ -19129,6 +19582,14 @@ snapshots: fastest-levenshtein@1.0.16: {} + fastq@1.20.3: + dependencies: + reusify: 1.1.0 + + fault@2.0.1: + dependencies: + format: 0.2.2 + fb-dotslash@0.5.8: {} fb-watchman@2.0.2: @@ -19224,6 +19685,8 @@ snapshots: dependencies: tiny-inflate: 1.0.3 + foreach@2.0.6: {} + form-data@4.0.6: dependencies: asynckit: 0.4.0 @@ -19232,6 +19695,8 @@ snapshots: hasown: 2.0.4 mime-types: 2.1.35 + format@0.2.2: {} + formatly@0.7.0: dependencies: fd-package-json: 2.0.0 @@ -19289,6 +19754,13 @@ snapshots: function-bind@1.1.2: {} + generaltranslation@9.5.9: + dependencies: + '@generaltranslation/api': 0.5.6 + '@generaltranslation/format': 0.1.9 + '@generaltranslation/icu': 0.1.2 + '@noble/hashes': 2.4.0 + gensync@1.0.0-beta.2: {} get-caller-file@2.0.5: {} @@ -19329,6 +19801,10 @@ snapshots: github-slugger@2.0.0: {} + glob-parent@5.1.2: + dependencies: + is-glob: 4.0.3 + glob-to-regexp@0.4.1: {} glob@13.0.7: @@ -19382,6 +19858,82 @@ snapshots: graphql@16.14.1: {} + gt-i18n@1.0.40: + dependencies: + '@generaltranslation/format': 0.1.9 + generaltranslation: 9.5.9 + + gt-react@11.4.18(react-dom@19.3.0(react@19.3.0))(react@19.3.0): + dependencies: + '@generaltranslation/react-core': 11.4.18(react@19.3.0) + generaltranslation: 9.5.9 + gt-i18n: 1.0.40 + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + + gt-remark@1.0.12(supports-color@8.1.1): + dependencies: + mdast-util-find-and-replace: 3.0.2 + mdast-util-gfm-footnote: 2.1.0(supports-color@8.1.1) + mdast-util-gfm-strikethrough: 2.0.0(supports-color@8.1.1) + mdast-util-gfm-table: 2.0.0(supports-color@8.1.1) + mdast-util-gfm-task-list-item: 2.0.0(supports-color@8.1.1) + micromark-extension-gfm-footnote: 2.1.0 + micromark-extension-gfm-strikethrough: 2.1.0 + micromark-extension-gfm-table: 2.1.1(patch_hash=9ad23a530e45d9f83cba1da8654fe16d5af8b59d5c73d5c7a7c91fd25b9be1d8) + micromark-extension-gfm-task-list-item: 2.1.0 + transitivePeerDependencies: + - supports-color + + gt@2.27.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1): + dependencies: + '@babel/generator': 7.29.7 + '@babel/parser': 7.29.8 + '@babel/plugin-transform-react-jsx': 7.29.7(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) + '@babel/traverse': 7.29.7(supports-color@8.1.1) + '@babel/types': 7.29.8 + '@clack/prompts': 1.0.0-alpha.6 + '@generaltranslation/format': 0.1.9 + '@generaltranslation/icu': 0.1.2 + '@generaltranslation/python-extractor': 0.2.64 + '@generaltranslation/supported-locales': 2.1.45 + '@generaltranslation/vue-extractor': 0.1.23(supports-color@8.1.1) + chalk: 5.6.2 + commander: 12.1.0 + dotenv: 16.6.1 + enhanced-resolve: 5.24.5 + esbuild-wasm: 0.27.7 + fast-glob: 3.3.3 + fast-json-stable-stringify: 2.1.0 + fflate: 0.8.3 + generaltranslation: 9.5.9 + gt-remark: 1.0.12(supports-color@8.1.1) + html-entities: 2.6.0 + json-pointer: 0.6.2 + jsonpath-plus: 10.4.0 + jsonpointer: 5.0.1 + mdast-util-find-and-replace: 3.0.2 + micromatch: 4.0.8 + open: 10.2.0 + openid-client: 6.8.8 + package-manager-detector: 1.8.0 + pino: 10.4.0 + pino-pretty: 13.2.0 + remark-frontmatter: 5.0.0(supports-color@8.1.1) + remark-mdx: 3.1.1(supports-color@8.1.1) + remark-parse: 11.0.0(supports-color@8.1.1) + remark-stringify: 11.0.0 + resolve: 1.22.12 + semver: 7.8.5 + smol-toml: 1.9.1 + tsconfig-paths: 4.2.0 + unified: 11.0.5 + unist-util-visit: 5.1.0 + yaml: 2.9.0 + transitivePeerDependencies: + - '@babel/core' + - supports-color + h3@1.15.11: dependencies: cookie-es: 1.2.3 @@ -19508,6 +20060,8 @@ snapshots: heic-to@1.5.2: {} + help-me@5.0.0: {} + hermes-compiler@260318099.0.5: {} hermes-estree@0.36.1: {} @@ -19534,6 +20088,8 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' + html-entities@2.6.0: {} + html-escaper@3.0.3: {} html-url-attributes@3.0.1: {} @@ -19640,12 +20196,24 @@ snapshots: is-docker@2.2.1: {} + is-docker@3.0.0: {} + is-docker@4.0.0: {} + is-extglob@2.1.1: {} + is-fullwidth-code-point@3.0.0: {} + is-glob@4.0.3: + dependencies: + is-extglob: 2.1.1 + is-hexadecimal@2.0.1: {} + is-inside-container@1.0.0: + dependencies: + is-docker: 3.0.0 + is-interactive@2.0.0: {} is-number@7.0.0: {} @@ -19664,6 +20232,10 @@ snapshots: dependencies: is-docker: 2.2.1 + is-wsl@3.1.1: + dependencies: + is-inside-container: 1.0.0 + isarray@1.0.0: {} isbinaryfile@4.0.10: {} @@ -19715,8 +20287,12 @@ snapshots: jiti@2.7.0: {} + jose@6.2.17: {} + jose@6.2.2: {} + joycon@3.1.1: {} + js-base64@3.7.8: optional: true @@ -19757,10 +20333,16 @@ snapshots: transitivePeerDependencies: - '@noble/hashes' + jsep@1.6.0: {} + jsesc@3.1.0: {} json-buffer@3.0.1: {} + json-pointer@0.6.2: + dependencies: + foreach: 2.0.6 + json-schema-to-ts@3.1.1: dependencies: '@babel/runtime': 7.29.7 @@ -19796,6 +20378,14 @@ snapshots: optionalDependencies: graceful-fs: 4.2.11 + jsonpath-plus@10.4.0: + dependencies: + '@jsep-plugin/assignment': 1.4.0(jsep@1.6.0) + '@jsep-plugin/regex': 1.1.0(jsep@1.6.0) + jsep: 1.6.0 + + jsonpointer@5.0.1: {} + jszip@3.10.1: dependencies: lie: 3.3.0 @@ -20056,6 +20646,17 @@ snapshots: transitivePeerDependencies: - supports-color + mdast-util-frontmatter@2.0.1(supports-color@8.1.1): + dependencies: + '@types/mdast': 4.0.4 + devlop: 1.1.0 + escape-string-regexp: 5.0.0 + mdast-util-from-markdown: 2.0.3(supports-color@8.1.1) + mdast-util-to-markdown: 2.1.2 + micromark-extension-frontmatter: 2.0.0 + transitivePeerDependencies: + - supports-color + mdast-util-gfm-autolink-literal@2.0.1: dependencies: '@types/mdast': 4.0.4 @@ -20153,6 +20754,16 @@ snapshots: transitivePeerDependencies: - supports-color + mdast-util-mdx@3.0.0(supports-color@8.1.1): + dependencies: + mdast-util-from-markdown: 2.0.3(supports-color@8.1.1) + mdast-util-mdx-expression: 2.0.1(supports-color@8.1.1) + mdast-util-mdx-jsx: 3.2.0(supports-color@8.1.1) + mdast-util-mdxjs-esm: 2.0.1(supports-color@8.1.1) + mdast-util-to-markdown: 2.1.2 + transitivePeerDependencies: + - supports-color + mdast-util-mdxjs-esm@2.0.1(supports-color@8.1.1): dependencies: '@types/estree-jsx': 1.0.5 @@ -20216,6 +20827,8 @@ snapshots: merge-stream@2.0.0: {} + merge2@1.4.1: {} + meshoptimizer@0.22.0: {} metro-babel-transformer@0.87.1(supports-color@8.1.1): @@ -20415,6 +21028,13 @@ snapshots: micromark-util-types: 2.0.2 parse-entities: 4.0.2 + micromark-extension-frontmatter@2.0.0: + dependencies: + fault: 2.0.1 + micromark-util-character: 2.1.1 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.2 + micromark-extension-gfm-autolink-literal@2.1.0: dependencies: micromark-util-character: 2.1.1 @@ -20483,6 +21103,57 @@ snapshots: micromark-util-symbol: 2.0.1 micromark-util-types: 2.0.2 + micromark-extension-mdx-expression@3.0.1: + dependencies: + '@types/estree': 1.0.9 + devlop: 1.1.0 + micromark-factory-mdx-expression: 2.0.3 + micromark-factory-space: 2.0.1 + micromark-util-character: 2.1.1 + micromark-util-events-to-acorn: 2.0.3 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.2 + + micromark-extension-mdx-jsx@3.0.2: + dependencies: + '@types/estree': 1.0.9 + devlop: 1.1.0 + estree-util-is-identifier-name: 3.0.0 + micromark-factory-mdx-expression: 2.0.3 + micromark-factory-space: 2.0.1 + micromark-util-character: 2.1.1 + micromark-util-events-to-acorn: 2.0.3 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.2 + vfile-message: 4.0.3 + + micromark-extension-mdx-md@2.0.0: + dependencies: + micromark-util-types: 2.0.2 + + micromark-extension-mdxjs-esm@3.0.0: + dependencies: + '@types/estree': 1.0.9 + devlop: 1.1.0 + micromark-core-commonmark: 2.0.3 + micromark-util-character: 2.1.1 + micromark-util-events-to-acorn: 2.0.3 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.2 + unist-util-position-from-estree: 2.0.0 + vfile-message: 4.0.3 + + micromark-extension-mdxjs@3.0.0: + dependencies: + acorn: 8.16.0 + acorn-jsx: 5.3.2(acorn@8.16.0) + micromark-extension-mdx-expression: 3.0.1 + micromark-extension-mdx-jsx: 3.0.2 + micromark-extension-mdx-md: 2.0.0 + micromark-extension-mdxjs-esm: 3.0.0 + micromark-util-combine-extensions: 2.0.1 + micromark-util-types: 2.0.2 + micromark-factory-destination@2.0.1: dependencies: micromark-util-character: 2.1.1 @@ -20496,6 +21167,18 @@ snapshots: micromark-util-symbol: 2.0.1 micromark-util-types: 2.0.2 + micromark-factory-mdx-expression@2.0.3: + dependencies: + '@types/estree': 1.0.9 + devlop: 1.1.0 + micromark-factory-space: 2.0.1 + micromark-util-character: 2.1.1 + micromark-util-events-to-acorn: 2.0.3 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.2 + unist-util-position-from-estree: 2.0.0 + vfile-message: 4.0.3 + micromark-factory-space@2.0.1: dependencies: micromark-util-character: 2.1.1 @@ -20548,6 +21231,16 @@ snapshots: micromark-util-encode@2.0.1: {} + micromark-util-events-to-acorn@2.0.3: + dependencies: + '@types/estree': 1.0.9 + '@types/unist': 3.0.3 + devlop: 1.1.0 + estree-util-visit: 2.0.0 + micromark-util-symbol: 2.0.1 + micromark-util-types: 2.0.2 + vfile-message: 4.0.3 + micromark-util-html-tag-name@2.0.1: {} micromark-util-normalize-identifier@2.0.1: @@ -20819,6 +21512,8 @@ snapshots: should: 13.2.3 yaml: 2.9.0 + oauth4webapi@3.8.8: {} + ob1@0.87.1: dependencies: flow-enums-runtime: 0.0.6 @@ -20846,6 +21541,8 @@ snapshots: ohash@2.0.12: {} + on-exit-leak-free@2.1.2: {} + on-finished@2.3.0: dependencies: ee-first: 1.1.1 @@ -20880,12 +21577,24 @@ snapshots: regex: 6.1.0 regex-recursion: 6.0.2 + open@10.2.0: + dependencies: + default-browser: 5.5.1 + define-lazy-prop: 3.0.0 + is-inside-container: 1.0.0 + wsl-utils: 0.1.0 + open@8.4.2: dependencies: define-lazy-prop: 2.0.0 is-docker: 2.2.1 is-wsl: 2.2.0 + openid-client@6.8.8: + dependencies: + jose: 6.2.17 + oauth4webapi: 3.8.8 + ora@3.4.0: dependencies: chalk: 2.4.2 @@ -21250,6 +21959,42 @@ snapshots: picomatch@4.0.7: {} + pino-abstract-transport@3.0.0: + dependencies: + split2: 4.2.0 + + pino-pretty@13.2.0: + dependencies: + colorette: 2.0.20 + dateformat: 4.6.3 + fast-copy: 4.3.1 + fast-safe-stringify: 2.1.1 + help-me: 5.0.0 + joycon: 3.1.1 + minimist: 1.2.8 + on-exit-leak-free: 2.1.2 + pino-abstract-transport: 3.0.0 + pump: 3.0.4 + secure-json-parse: 4.1.1 + sonic-boom: 5.0.2 + strip-json-comments: 5.0.3 + + pino-std-serializers@7.1.0: {} + + pino@10.4.0: + dependencies: + '@pinojs/redact': 0.4.0 + atomic-sleep: 1.0.0 + on-exit-leak-free: 2.1.2 + pino-abstract-transport: 3.0.0 + pino-std-serializers: 7.1.0 + process-warning: 5.1.1 + quick-format-unescaped: 4.0.4 + real-require: 1.0.0 + safe-stable-stringify: 2.5.0 + sonic-boom: 4.2.1 + thread-stream: 4.2.1 + pixelmatch@8.0.0: dependencies: pngjs: 7.0.0 @@ -21349,6 +22094,8 @@ snapshots: process-nextick-args@2.0.1: {} + process-warning@5.1.1: {} + progress@2.0.3: {} promise-limit@2.7.0: @@ -21473,6 +22220,10 @@ snapshots: es-define-property: 1.0.1 side-channel: 1.1.1 + queue-microtask@1.2.3: {} + + quick-format-unescaped@4.0.4: {} + quick-lru@5.1.1: {} radix3@1.1.2: {} @@ -21716,6 +22467,8 @@ snapshots: readdirp@5.0.0: {} + real-require@1.0.0: {} + redis-errors@1.2.0: optional: true @@ -21787,6 +22540,15 @@ snapshots: mdast-util-newline-to-break: 2.0.0 unified: 11.0.5 + remark-frontmatter@5.0.0(supports-color@8.1.1): + dependencies: + '@types/mdast': 4.0.4 + mdast-util-frontmatter: 2.0.1(supports-color@8.1.1) + micromark-extension-frontmatter: 2.0.0 + unified: 11.0.5 + transitivePeerDependencies: + - supports-color + remark-gfm@4.0.1(supports-color@8.1.1): dependencies: '@types/mdast': 4.0.4 @@ -21807,6 +22569,13 @@ snapshots: transitivePeerDependencies: - supports-color + remark-mdx@3.1.1(supports-color@8.1.1): + dependencies: + mdast-util-mdx: 3.0.0(supports-color@8.1.1) + micromark-extension-mdxjs: 3.0.0 + transitivePeerDependencies: + - supports-color + remark-parse@11.0.0(supports-color@8.1.1): dependencies: '@types/mdast': 4.0.4 @@ -21881,6 +22650,8 @@ snapshots: retry@0.12.0: {} + reusify@1.1.0: {} + rimraf@2.6.3: dependencies: glob: 7.2.3 @@ -21950,10 +22721,18 @@ snapshots: transitivePeerDependencies: - supports-color + run-applescript@7.1.0: {} + + run-parallel@1.2.0: + dependencies: + queue-microtask: 1.2.3 + safe-buffer@5.1.2: {} safe-buffer@5.2.1: {} + safe-stable-stringify@2.5.0: {} + safer-buffer@2.1.2: {} sandbox-cli-detector@0.2.0: {} @@ -21994,6 +22773,8 @@ snapshots: ajv-formats: 2.1.1 ajv-keywords: 5.1.0(ajv@8.20.0) + secure-json-parse@4.1.1: {} + semver-compare@1.0.0: optional: true @@ -22212,6 +22993,14 @@ snapshots: smol-toml@1.9.1: {} + sonic-boom@4.2.1: + dependencies: + atomic-sleep: 1.0.0 + + sonic-boom@5.0.2: + dependencies: + atomic-sleep: 1.0.0 + source-map-js@1.2.2: {} source-map-support@0.5.21: @@ -22225,8 +23014,7 @@ snapshots: space-separated-tokens@2.0.2: {} - split2@4.2.0: - optional: true + split2@4.2.0: {} split@0.3.3: dependencies: @@ -22315,6 +23103,8 @@ snapshots: dependencies: ansi-regex: 6.2.2 + strip-bom@3.0.0: {} + strip-json-comments@5.0.3: {} strnum@2.4.2: @@ -22420,6 +23210,10 @@ snapshots: commander: 2.20.3 source-map-support: 0.5.21 + thread-stream@4.2.1: + dependencies: + real-require: 1.0.0 + three@0.180.0: {} throat@5.0.0: {} @@ -22515,6 +23309,12 @@ snapshots: '@ts-morph/common': 0.29.0 code-block-writer: 13.0.3 + tsconfig-paths@4.2.0: + dependencies: + json5: 2.2.3 + minimist: 1.2.8 + strip-bom: 3.0.0 + tslib@2.8.1: {} type-fest@0.13.1: @@ -22600,6 +23400,10 @@ snapshots: dependencies: '@types/unist': 3.0.3 + unist-util-position-from-estree@2.0.0: + dependencies: + '@types/unist': 3.0.3 + unist-util-position@5.0.0: dependencies: '@types/unist': 3.0.3 @@ -22989,6 +23793,8 @@ snapshots: web-namespaces@2.0.1: {} + web-tree-sitter@0.26.13: {} + webcrypto-core@1.9.2: dependencies: '@peculiar/asn1-schema': 2.8.0 @@ -23076,6 +23882,10 @@ snapshots: bufferutil: 4.1.0 utf-8-validate: 6.0.6 + wsl-utils@0.1.0: + dependencies: + is-wsl: 3.1.1 + xcode@4.0.0: dependencies: simple-plist: 1.3.1 From afade9b5623e5be54b464933ae3bf227326992c4 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:03:17 +0000 Subject: [PATCH 002/253] feat(web): add Brazilian Portuguese translation (#33161) --- apps/web/gt.config.json | 2 +- .../src/components/settings/settingsSearch.ts | 4 +- apps/web/src/i18n/locales.ts | 1 + apps/web/src/i18n/translations/pt-BR.json | 74 +++++++++++++++++++ 4 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/i18n/translations/pt-BR.json diff --git a/apps/web/gt.config.json b/apps/web/gt.config.json index 965dec405f56e..64514daaa0987 100644 --- a/apps/web/gt.config.json +++ b/apps/web/gt.config.json @@ -1,6 +1,6 @@ { "defaultLocale": "en", - "locales": ["es", "zh"], + "locales": ["es", "pt-BR", "zh"], "files": { "gt": { "output": "src/i18n/translations/[locale].json" diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 567a5d6e2aba6..37461970624ee 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -683,7 +683,9 @@ export const SETTINGS_SEARCH_ITEMS = [ id: "language", title: msg("Language"), to: "/settings/general", - searchTerms: ["locale translation english español spanish chinese 中文 idioma 语言"], + searchTerms: [ + "locale translation english español spanish português portuguese brasil brazilian chinese 中文 idioma 语言", + ], }, { id: "time-format", diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts index a55d6f86ca946..abd22a04a9988 100644 --- a/apps/web/src/i18n/locales.ts +++ b/apps/web/src/i18n/locales.ts @@ -8,6 +8,7 @@ export const SUPPORTED_LOCALES: ReadonlyArray = [DEFAULT_LOCALE, ...gtCo const NATIVE_LANGUAGE_NAMES: Readonly> = { en: "English", es: "Español", + "pt-BR": "Português (Brasil)", zh: "中文(简体)", }; diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json new file mode 100644 index 0000000000000..bb24a0ee7fa32 --- /dev/null +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -0,0 +1,74 @@ +{ + "0a75e464d833bca8": "Configurações", + "6aa1c88c4fa5be28": "Diagnóstico", + "fb29e435b1219373": "Licenças de código aberto", + "c0b0406e0cafa1d1": "Última mensagem do usuário", + "cb0775162a9b6419": "Data de criação", + "62570d4bfe4ab517": "Manual", + "7eed14b9c7fd7661": "Padrão do sistema", + "7fa9414ef5e9dd6c": "12 horas", + "2f42917064c97f09": "24 horas", + "7e8c995646a967d3": "Imediato", + "51497bd401292062": "Manter pressionado", + "9d6cc6ac23312071": "Pressionar duas vezes", + "e1483914168d6b8e": "Notificações", + "798dc6846ed39fa0": "Notificações no app", + "d9b0fbd680d5f175": "Barra lateral", + "cd5452cc9e13c818": "Agrupamento de projetos", + "6147d6fc04079525": "Ordem dos projetos", + "bdf39fd139a04325": "Seção Working", + "76f3c3e2f8dd0120": "Confirmações", + "859e386f8af841f0": "Confirmar ao desafixar conversas", + "de0d79b74d3e4af6": "Confirmar ao arquivar conversas", + "4ab8a4878cd80c77": "Confirmar ao excluir conversas", + "0c853c878aab1908": "Comportamento do atalho de saída", + "22e745b7db60e52f": "Exibição", + "2c1c93a646bbea6e": "Idioma", + "c7b0bcb64f48db85": "Formato de hora", + "cbf6a6bbc17e75e1": "Mostra um aviso quando outra conversa termina, falha ou precisa de uma resposta ou aprovação enquanto o app está em foco.", + "83ca942c7163904f": "Combina repositórios correspondentes entre ambientes.", + "609da998ca13521e": "Ordem dos projetos no seletor da barra lateral e na paleta de comandos.", + "b4c541137a76b351": "Agrupa as conversas em andamento e em monitoramento em uma seção Working. Elas voltam ao topo da caixa de entrada quando precisam de você. A boring sidebar do Labs não tem seção Working.", + "e815f49e5abedcfd": "Pergunta antes de desafixar uma conversa da seção de fixadas.", + "41210f99adeeba78": "Exige um segundo clique na ação de arquivar antes de arquivar uma conversa.", + "84f3d2cefc8d2a74": "Pergunta antes de excluir uma conversa e o histórico do chat.", + "3fc130f1e8170073": "O modo \"Manter pressionado\" também sai ao pressionar duas vezes rapidamente.", + "72c7fda6ae301e6d": "\"Padrão do sistema\" usa o idioma do navegador ou do sistema operacional.", + "b9ebecdb8db71466": "\"Padrão do sistema\" usa o formato de hora do navegador ou do sistema operacional.", + "425f7ce2f24cb248": "Seções de configurações", + "ee3e8bd8b7918aec": "Pesquisar", + "858561b97fdd72f2": "Pesquisar configurações", + "fed2d32de2b0c566": "Limpar pesquisa de configurações", + "833639e235c97484": "Resultados da pesquisa de configurações", + "be82bbfef472ab44": "Nenhuma configuração encontrada", + "cc84bfe0ee5d0174": "Projetos", + "81d0d1e78b196630": "Geral", + "fa19046edd6cfbd4": "Aparência", + "afda415d2d75a5d3": "Chat", + "4beeab8d1814b251": "Diffs e pull requests", + "3b958faa12d54484": "Atalhos de teclado", + "1a6679bbe62703b2": "SnapShots", + "2f77cc3105ddd7f8": "Provedores", + "6d9bf91f0d4b7ba3": "Conversas", + "795854feef8d2f52": "Navegador", + "9cc48e5c9ee46026": "Dispositivos", + "2ab325baee3ec9a3": "Tarefas agendadas", + "a4380762611c94e4": "Controle de versão", + "4889f7885396c26b": "Worktrees", + "b5adbf54cbefee38": "Ambientes", + "1de0df2b8a4fb96e": "Compartilhamento e acesso", + "4c70e3e7b3e6c493": "Segredos", + "79b768229c9ef672": "Manutenção", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "Sobre", + "af4b7734da1d5ce7": "Voz", + "2a546119bf3879ee": "Arquivadas", + "2632f324dc2d9c48": "Agentes", + "58058320796d28f6": "Código", + "1a07e4d043f5df4e": "Conexões", + "e5144f91364fd9b7": "Formato de hora", + "7e4d81ca21a72019": "Confirmação ao desafixar", + "1d5052cbe70d0b28": "Confirmação ao arquivar", + "d5dd27a4eb853248": "Confirmação ao excluir", + "86b43caa9ff41ea2": "Atalho de saída" +} From 93d502f237ce92a63538040ec2643e49642f5030 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:03:17 +0000 Subject: [PATCH 003/253] feat(web): add French translation (#33162) --- apps/web/gt.config.json | 2 +- .../src/components/settings/settingsSearch.ts | 2 +- apps/web/src/i18n/locales.ts | 1 + apps/web/src/i18n/translations/fr.json | 74 +++++++++++++++++++ 4 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/i18n/translations/fr.json diff --git a/apps/web/gt.config.json b/apps/web/gt.config.json index 64514daaa0987..2fc63e36f7d87 100644 --- a/apps/web/gt.config.json +++ b/apps/web/gt.config.json @@ -1,6 +1,6 @@ { "defaultLocale": "en", - "locales": ["es", "pt-BR", "zh"], + "locales": ["es", "fr", "pt-BR", "zh"], "files": { "gt": { "output": "src/i18n/translations/[locale].json" diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 37461970624ee..35fcba43bfe38 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -684,7 +684,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Language"), to: "/settings/general", searchTerms: [ - "locale translation english español spanish português portuguese brasil brazilian chinese 中文 idioma 语言", + "locale translation english español spanish français french português portuguese brasil brazilian chinese 中文 idioma langue 语言", ], }, { diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts index abd22a04a9988..91ce0769769dd 100644 --- a/apps/web/src/i18n/locales.ts +++ b/apps/web/src/i18n/locales.ts @@ -8,6 +8,7 @@ export const SUPPORTED_LOCALES: ReadonlyArray = [DEFAULT_LOCALE, ...gtCo const NATIVE_LANGUAGE_NAMES: Readonly> = { en: "English", es: "Español", + fr: "Français", "pt-BR": "Português (Brasil)", zh: "中文(简体)", }; diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json new file mode 100644 index 0000000000000..963cf3638e38b --- /dev/null +++ b/apps/web/src/i18n/translations/fr.json @@ -0,0 +1,74 @@ +{ + "0a75e464d833bca8": "Paramètres", + "6aa1c88c4fa5be28": "Diagnostics", + "fb29e435b1219373": "Licences open source", + "c0b0406e0cafa1d1": "Dernier message envoyé", + "cb0775162a9b6419": "Date de création", + "62570d4bfe4ab517": "Manuel", + "7eed14b9c7fd7661": "Système", + "7fa9414ef5e9dd6c": "12 heures", + "2f42917064c97f09": "24 heures", + "7e8c995646a967d3": "Immédiat", + "51497bd401292062": "Appui long", + "9d6cc6ac23312071": "Double appui", + "e1483914168d6b8e": "Notifications", + "798dc6846ed39fa0": "Notifications dans l'app", + "d9b0fbd680d5f175": "Barre latérale", + "cd5452cc9e13c818": "Regroupement des projets", + "6147d6fc04079525": "Ordre des projets", + "bdf39fd139a04325": "Section Working", + "76f3c3e2f8dd0120": "Confirmations", + "859e386f8af841f0": "Confirmer avant de désépingler un fil", + "de0d79b74d3e4af6": "Confirmer l'archivage des fils", + "4ab8a4878cd80c77": "Confirmer la suppression des fils", + "0c853c878aab1908": "Comportement du raccourci Quitter", + "22e745b7db60e52f": "Affichage", + "2c1c93a646bbea6e": "Langue", + "c7b0bcb64f48db85": "Format de l'horodatage", + "cbf6a6bbc17e75e1": "Affiche une notification quand un autre fil se termine, échoue ou attend une réponse ou une approbation pendant que l'app est active.", + "83ca942c7163904f": "Regroupe les dépôts identiques de tous les environnements.", + "609da998ca13521e": "Ordre des projets dans le sélecteur de la barre latérale et dans la palette de commandes.", + "b4c541137a76b351": "Regroupe les fils en cours et en surveillance dans une section Working. Ils reviennent en haut de la boîte de réception quand ils ont besoin de vous. La boring sidebar de Labs n'a pas de section Working.", + "e815f49e5abedcfd": "Demande confirmation avant de désépingler un fil.", + "41210f99adeeba78": "Exige un second clic sur le bouton d'archivage du fil avant de l'archiver.", + "84f3d2cefc8d2a74": "Demande confirmation avant de supprimer un fil et son historique de discussion.", + "3fc130f1e8170073": "En mode Appui long, un double appui rapide quitte aussi l'app.", + "72c7fda6ae301e6d": "L'option Système suit la langue de votre navigateur ou de votre OS.", + "b9ebecdb8db71466": "L'option Système suit le format de l'heure de votre navigateur ou de votre OS.", + "425f7ce2f24cb248": "Sections des paramètres", + "ee3e8bd8b7918aec": "Rechercher", + "858561b97fdd72f2": "Rechercher dans les paramètres", + "fed2d32de2b0c566": "Effacer la recherche dans les paramètres", + "833639e235c97484": "Résultats de la recherche dans les paramètres", + "be82bbfef472ab44": "Aucun paramètre trouvé", + "cc84bfe0ee5d0174": "Projets", + "81d0d1e78b196630": "Général", + "fa19046edd6cfbd4": "Apparence", + "afda415d2d75a5d3": "Chat", + "4beeab8d1814b251": "Diffs et pull requests", + "3b958faa12d54484": "Raccourcis clavier", + "1a6679bbe62703b2": "SnapShots", + "2f77cc3105ddd7f8": "Fournisseurs", + "6d9bf91f0d4b7ba3": "Fils", + "795854feef8d2f52": "Navigateur", + "9cc48e5c9ee46026": "Appareils", + "2ab325baee3ec9a3": "Tâches planifiées", + "a4380762611c94e4": "Gestion de versions", + "4889f7885396c26b": "Worktrees", + "b5adbf54cbefee38": "Environnements", + "1de0df2b8a4fb96e": "Partage et accès", + "4c70e3e7b3e6c493": "Secrets", + "79b768229c9ef672": "Maintenance", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "À propos", + "af4b7734da1d5ce7": "Voix", + "2a546119bf3879ee": "Archives", + "2632f324dc2d9c48": "Agents", + "58058320796d28f6": "Code", + "1a07e4d043f5df4e": "Connexions", + "e5144f91364fd9b7": "Format de l'heure", + "7e4d81ca21a72019": "Confirmation avant de désépingler", + "1d5052cbe70d0b28": "Confirmation de l'archivage", + "d5dd27a4eb853248": "Confirmation de la suppression", + "86b43caa9ff41ea2": "Raccourci Quitter" +} From d8631c8711b2a4f5559d1b44127fa26dcad9b3bf Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:03:18 +0000 Subject: [PATCH 004/253] feat(web): add German translation (#33163) --- apps/web/gt.config.json | 2 +- .../src/components/settings/settingsSearch.ts | 2 +- apps/web/src/i18n/locales.ts | 1 + apps/web/src/i18n/translations/de.json | 74 +++++++++++++++++++ 4 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/i18n/translations/de.json diff --git a/apps/web/gt.config.json b/apps/web/gt.config.json index 2fc63e36f7d87..f8db7f99551b8 100644 --- a/apps/web/gt.config.json +++ b/apps/web/gt.config.json @@ -1,6 +1,6 @@ { "defaultLocale": "en", - "locales": ["es", "fr", "pt-BR", "zh"], + "locales": ["de", "es", "fr", "pt-BR", "zh"], "files": { "gt": { "output": "src/i18n/translations/[locale].json" diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 35fcba43bfe38..cbea14727c86b 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -684,7 +684,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Language"), to: "/settings/general", searchTerms: [ - "locale translation english español spanish français french português portuguese brasil brazilian chinese 中文 idioma langue 语言", + "locale translation english deutsch german español spanish français french português portuguese brasil brazilian chinese 中文 sprache idioma langue 语言", ], }, { diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts index 91ce0769769dd..b25a6de99af06 100644 --- a/apps/web/src/i18n/locales.ts +++ b/apps/web/src/i18n/locales.ts @@ -7,6 +7,7 @@ export const SUPPORTED_LOCALES: ReadonlyArray = [DEFAULT_LOCALE, ...gtCo // Shown in their own language so a user can find theirs from any UI language. const NATIVE_LANGUAGE_NAMES: Readonly> = { en: "English", + de: "Deutsch", es: "Español", fr: "Français", "pt-BR": "Português (Brasil)", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json new file mode 100644 index 0000000000000..47c85a6d32890 --- /dev/null +++ b/apps/web/src/i18n/translations/de.json @@ -0,0 +1,74 @@ +{ + "0a75e464d833bca8": "Einstellungen", + "6aa1c88c4fa5be28": "Diagnose", + "fb29e435b1219373": "Open-Source-Lizenzen", + "c0b0406e0cafa1d1": "Letzte eigene Nachricht", + "cb0775162a9b6419": "Erstellungsdatum", + "62570d4bfe4ab517": "Manuell", + "7eed14b9c7fd7661": "Systemstandard", + "7fa9414ef5e9dd6c": "12-Stunden-Format", + "2f42917064c97f09": "24-Stunden-Format", + "7e8c995646a967d3": "Direkt", + "51497bd401292062": "Gedrückt halten", + "9d6cc6ac23312071": "Doppelt drücken", + "e1483914168d6b8e": "Benachrichtigungen", + "798dc6846ed39fa0": "In-App-Benachrichtigungen", + "d9b0fbd680d5f175": "Seitenleiste", + "cd5452cc9e13c818": "Projektgruppierung", + "6147d6fc04079525": "Projektreihenfolge", + "bdf39fd139a04325": "Working-Bereich", + "76f3c3e2f8dd0120": "Bestätigungen", + "859e386f8af841f0": "Loslösen von Threads bestätigen", + "de0d79b74d3e4af6": "Archivieren von Threads bestätigen", + "4ab8a4878cd80c77": "Löschen von Threads bestätigen", + "0c853c878aab1908": "Beenden per Tastenkürzel", + "22e745b7db60e52f": "Anzeige", + "2c1c93a646bbea6e": "Sprache", + "c7b0bcb64f48db85": "Zeitstempelformat", + "cbf6a6bbc17e75e1": "Einen Hinweis anzeigen, wenn ein anderer Thread fertig ist, fehlschlägt oder auf Eingabe oder Genehmigung wartet, während die App aktiv ist.", + "83ca942c7163904f": "Gleiche Repositorys aus verschiedenen Umgebungen zusammenfassen.", + "609da998ca13521e": "Reihenfolge der Projekte in der Projektauswahl der Seitenleiste und in der Befehlspalette.", + "b4c541137a76b351": "Laufende und überwachende Threads im Working-Bereich bündeln. Sie rücken im Posteingang wieder nach oben, sobald sie dich brauchen. Die boring sidebar unter Labs hat keinen Working-Bereich.", + "e815f49e5abedcfd": "Vor dem Loslösen eines Threads aus dem Bereich „Angeheftet“ nachfragen.", + "41210f99adeeba78": "Einen zweiten Klick auf die Archivieren-Aktion verlangen, bevor ein Thread archiviert wird.", + "84f3d2cefc8d2a74": "Vor dem Löschen eines Threads samt Chatverlauf nachfragen.", + "3fc130f1e8170073": "Bei „Gedrückt halten“ beendet auch zweimaliges schnelles Drücken die App.", + "72c7fda6ae301e6d": "Systemstandard folgt der Sprache deines Browsers oder Betriebssystems.", + "b9ebecdb8db71466": "Systemstandard folgt dem Uhrzeitformat deines Browsers oder Betriebssystems.", + "425f7ce2f24cb248": "Einstellungsbereiche", + "ee3e8bd8b7918aec": "Suchen", + "858561b97fdd72f2": "Einstellungen durchsuchen", + "fed2d32de2b0c566": "Einstellungssuche leeren", + "833639e235c97484": "Suchergebnisse in den Einstellungen", + "be82bbfef472ab44": "Keine Einstellungen gefunden", + "cc84bfe0ee5d0174": "Projekte", + "81d0d1e78b196630": "Allgemein", + "fa19046edd6cfbd4": "Darstellung", + "afda415d2d75a5d3": "Chat", + "4beeab8d1814b251": "Diffs & Pull Requests", + "3b958faa12d54484": "Tastenkürzel", + "1a6679bbe62703b2": "SnapShots", + "2f77cc3105ddd7f8": "Anbieter", + "6d9bf91f0d4b7ba3": "Threads", + "795854feef8d2f52": "Browser", + "9cc48e5c9ee46026": "Geräte", + "2ab325baee3ec9a3": "Geplante Aufgaben", + "a4380762611c94e4": "Versionskontrolle", + "4889f7885396c26b": "Worktrees", + "b5adbf54cbefee38": "Umgebungen", + "1de0df2b8a4fb96e": "Freigabe & Zugriff", + "4c70e3e7b3e6c493": "Secrets", + "79b768229c9ef672": "Wartung", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "Über", + "af4b7734da1d5ce7": "Spracheingabe", + "2a546119bf3879ee": "Archiv", + "2632f324dc2d9c48": "Agenten", + "58058320796d28f6": "Code", + "1a07e4d043f5df4e": "Verbindungen", + "e5144f91364fd9b7": "Uhrzeitformat", + "7e4d81ca21a72019": "Loslösen bestätigen", + "1d5052cbe70d0b28": "Archivieren bestätigen", + "d5dd27a4eb853248": "Löschen bestätigen", + "86b43caa9ff41ea2": "Tastenkürzel zum Beenden" +} From 2718951b9ff74c24bb5cc36d1549a19a272558d9 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:03:18 +0000 Subject: [PATCH 005/253] feat(web): add Japanese translation (#33164) --- apps/web/gt.config.json | 2 +- .../src/components/settings/settingsSearch.ts | 2 +- apps/web/src/i18n/locales.ts | 1 + apps/web/src/i18n/translations/ja.json | 74 +++++++++++++++++++ 4 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/i18n/translations/ja.json diff --git a/apps/web/gt.config.json b/apps/web/gt.config.json index f8db7f99551b8..06a81d4ad626d 100644 --- a/apps/web/gt.config.json +++ b/apps/web/gt.config.json @@ -1,6 +1,6 @@ { "defaultLocale": "en", - "locales": ["de", "es", "fr", "pt-BR", "zh"], + "locales": ["de", "es", "fr", "ja", "pt-BR", "zh"], "files": { "gt": { "output": "src/i18n/translations/[locale].json" diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index cbea14727c86b..82baddbf67441 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -684,7 +684,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Language"), to: "/settings/general", searchTerms: [ - "locale translation english deutsch german español spanish français french português portuguese brasil brazilian chinese 中文 sprache idioma langue 语言", + "locale translation english deutsch german español spanish français french português portuguese brasil brazilian chinese 中文 japanese 日本語 sprache idioma langue 语言 言語", ], }, { diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts index b25a6de99af06..778161ce4737f 100644 --- a/apps/web/src/i18n/locales.ts +++ b/apps/web/src/i18n/locales.ts @@ -10,6 +10,7 @@ const NATIVE_LANGUAGE_NAMES: Readonly> = { de: "Deutsch", es: "Español", fr: "Français", + ja: "日本語", "pt-BR": "Português (Brasil)", zh: "中文(简体)", }; diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json new file mode 100644 index 0000000000000..b11687db7046a --- /dev/null +++ b/apps/web/src/i18n/translations/ja.json @@ -0,0 +1,74 @@ +{ + "0a75e464d833bca8": "設定", + "6aa1c88c4fa5be28": "診断", + "fb29e435b1219373": "オープンソースライセンス", + "c0b0406e0cafa1d1": "ユーザーの最終メッセージ日時", + "cb0775162a9b6419": "作成日時", + "62570d4bfe4ab517": "手動", + "7eed14b9c7fd7661": "システムのデフォルト", + "7fa9414ef5e9dd6c": "12 時間制", + "2f42917064c97f09": "24 時間制", + "7e8c995646a967d3": "即時", + "51497bd401292062": "長押し", + "9d6cc6ac23312071": "2 回押し", + "e1483914168d6b8e": "通知", + "798dc6846ed39fa0": "アプリ内通知", + "d9b0fbd680d5f175": "サイドバー", + "cd5452cc9e13c818": "プロジェクトのグループ化", + "6147d6fc04079525": "プロジェクトの並び順", + "bdf39fd139a04325": "Working セクション", + "76f3c3e2f8dd0120": "確認ダイアログ", + "859e386f8af841f0": "スレッドのピン留め解除を確認", + "de0d79b74d3e4af6": "スレッドのアーカイブを確認", + "4ab8a4878cd80c77": "スレッドの削除を確認", + "0c853c878aab1908": "終了ショートカットの動作", + "22e745b7db60e52f": "表示", + "2c1c93a646bbea6e": "言語", + "c7b0bcb64f48db85": "タイムスタンプの形式", + "cbf6a6bbc17e75e1": "アプリがフォーカスされているときに、別のスレッドの完了・失敗や、入力・承認の要求をトースト通知で表示します。", + "83ca942c7163904f": "環境をまたいで同じリポジトリをまとめて表示します。", + "609da998ca13521e": "サイドバーのプロジェクト選択メニューとコマンドパレットでの表示順です。", + "b4c541137a76b351": "作業中と監視中のスレッドを Working セクションにまとめます。対応が必要になると受信トレイの先頭に戻ります。Labs の boring sidebar には Working セクションはありません。", + "e815f49e5abedcfd": "スレッドのピン留めを解除する前に確認します。", + "41210f99adeeba78": "インラインのアーカイブボタンは、もう一度クリックするまでスレッドをアーカイブしません。", + "84f3d2cefc8d2a74": "スレッドとそのチャット履歴を削除する前に確認します。", + "3fc130f1e8170073": "長押しモードでも、すばやく 2 回押すと終了します。", + "72c7fda6ae301e6d": "「システムのデフォルト」を選ぶと、ブラウザーまたは OS の言語に従います。", + "b9ebecdb8db71466": "「システムのデフォルト」を選ぶと、ブラウザーまたは OS の時刻形式に従います。", + "425f7ce2f24cb248": "設定のセクション", + "ee3e8bd8b7918aec": "検索", + "858561b97fdd72f2": "設定を検索", + "fed2d32de2b0c566": "設定の検索をクリア", + "833639e235c97484": "設定の検索結果", + "be82bbfef472ab44": "一致する設定はありません", + "cc84bfe0ee5d0174": "プロジェクト", + "81d0d1e78b196630": "一般", + "fa19046edd6cfbd4": "外観", + "afda415d2d75a5d3": "チャット", + "4beeab8d1814b251": "差分とプルリクエスト", + "3b958faa12d54484": "キーボードショートカット", + "1a6679bbe62703b2": "SnapShots", + "2f77cc3105ddd7f8": "プロバイダー", + "6d9bf91f0d4b7ba3": "スレッド", + "795854feef8d2f52": "ブラウザー", + "9cc48e5c9ee46026": "デバイス", + "2ab325baee3ec9a3": "スケジュール済みタスク", + "a4380762611c94e4": "ソース管理", + "4889f7885396c26b": "ワークツリー", + "b5adbf54cbefee38": "環境", + "1de0df2b8a4fb96e": "共有とアクセス", + "4c70e3e7b3e6c493": "シークレット", + "79b768229c9ef672": "メンテナンス", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "情報", + "af4b7734da1d5ce7": "音声", + "2a546119bf3879ee": "アーカイブ", + "2632f324dc2d9c48": "エージェント", + "58058320796d28f6": "コード", + "1a07e4d043f5df4e": "接続", + "e5144f91364fd9b7": "時刻の形式", + "7e4d81ca21a72019": "ピン留め解除の確認", + "1d5052cbe70d0b28": "アーカイブの確認", + "d5dd27a4eb853248": "削除の確認", + "86b43caa9ff41ea2": "終了ショートカット" +} From fdefab4df34cd6e245b277289297809ba24065f9 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:03:19 +0000 Subject: [PATCH 006/253] feat(web): add Korean translation (#33165) --- apps/web/gt.config.json | 2 +- .../src/components/settings/settingsSearch.ts | 2 +- apps/web/src/i18n/locales.ts | 1 + apps/web/src/i18n/translations/ko.json | 74 +++++++++++++++++++ 4 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/i18n/translations/ko.json diff --git a/apps/web/gt.config.json b/apps/web/gt.config.json index 06a81d4ad626d..ae61c5349c47c 100644 --- a/apps/web/gt.config.json +++ b/apps/web/gt.config.json @@ -1,6 +1,6 @@ { "defaultLocale": "en", - "locales": ["de", "es", "fr", "ja", "pt-BR", "zh"], + "locales": ["de", "es", "fr", "ja", "ko", "pt-BR", "zh"], "files": { "gt": { "output": "src/i18n/translations/[locale].json" diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 82baddbf67441..2233bdae5ac5b 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -684,7 +684,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Language"), to: "/settings/general", searchTerms: [ - "locale translation english deutsch german español spanish français french português portuguese brasil brazilian chinese 中文 japanese 日本語 sprache idioma langue 语言 言語", + "locale translation english deutsch german español spanish français french português portuguese brasil brazilian chinese 中文 japanese 日本語 korean 한국어 sprache idioma langue 语言 言語 언어", ], }, { diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts index 778161ce4737f..e03e115feb639 100644 --- a/apps/web/src/i18n/locales.ts +++ b/apps/web/src/i18n/locales.ts @@ -11,6 +11,7 @@ const NATIVE_LANGUAGE_NAMES: Readonly> = { es: "Español", fr: "Français", ja: "日本語", + ko: "한국어", "pt-BR": "Português (Brasil)", zh: "中文(简体)", }; diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json new file mode 100644 index 0000000000000..5a0552c2ccb39 --- /dev/null +++ b/apps/web/src/i18n/translations/ko.json @@ -0,0 +1,74 @@ +{ + "0a75e464d833bca8": "설정", + "6aa1c88c4fa5be28": "진단", + "fb29e435b1219373": "오픈 소스 라이선스", + "c0b0406e0cafa1d1": "마지막 사용자 메시지", + "cb0775162a9b6419": "생성일", + "62570d4bfe4ab517": "수동", + "7eed14b9c7fd7661": "시스템 기본값", + "7fa9414ef5e9dd6c": "12시간제", + "2f42917064c97f09": "24시간제", + "7e8c995646a967d3": "바로 종료", + "51497bd401292062": "길게 누르기", + "9d6cc6ac23312071": "두 번 누르기", + "e1483914168d6b8e": "알림", + "798dc6846ed39fa0": "앱 내 알림", + "d9b0fbd680d5f175": "사이드바", + "cd5452cc9e13c818": "프로젝트 그룹화", + "6147d6fc04079525": "프로젝트 순서", + "bdf39fd139a04325": "Working 섹션", + "76f3c3e2f8dd0120": "확인 요청", + "859e386f8af841f0": "스레드 고정 해제 확인", + "de0d79b74d3e4af6": "스레드 보관 확인", + "4ab8a4878cd80c77": "스레드 삭제 확인", + "0c853c878aab1908": "종료 단축키 동작", + "22e745b7db60e52f": "표시", + "2c1c93a646bbea6e": "언어", + "c7b0bcb64f48db85": "타임스탬프 형식", + "cbf6a6bbc17e75e1": "이 앱이 활성 상태일 때 다른 스레드가 완료되거나 실패하거나, 입력 또는 승인이 필요하면 토스트 알림을 표시합니다.", + "83ca942c7163904f": "여러 환경에 있는 같은 저장소를 하나로 묶어 표시합니다.", + "609da998ca13521e": "사이드바 프로젝트 선택기와 명령 팔레트에 표시되는 프로젝트 순서입니다.", + "b4c541137a76b351": "작업 중이거나 모니터링 중인 스레드를 Working 섹션으로 접어 둡니다. 응답이 필요해지면 인박스 맨 위로 다시 올라옵니다. Labs의 boring sidebar에는 Working 섹션이 없습니다.", + "e815f49e5abedcfd": "고정 섹션에서 스레드 고정을 해제하기 전에 확인을 요청합니다.", + "41210f99adeeba78": "인라인 보관 버튼을 한 번 더 클릭해야 스레드가 보관됩니다.", + "84f3d2cefc8d2a74": "스레드와 채팅 기록을 삭제하기 전에 확인을 요청합니다.", + "3fc130f1e8170073": "길게 누르기 모드에서도 빠르게 두 번 누르면 종료됩니다.", + "72c7fda6ae301e6d": "시스템 기본값은 브라우저 또는 OS 언어를 따릅니다.", + "b9ebecdb8db71466": "시스템 기본값은 브라우저 또는 OS의 시간 형식 설정을 따릅니다.", + "425f7ce2f24cb248": "설정 섹션", + "ee3e8bd8b7918aec": "검색", + "858561b97fdd72f2": "설정 검색", + "fed2d32de2b0c566": "설정 검색어 지우기", + "833639e235c97484": "설정 검색 결과", + "be82bbfef472ab44": "일치하는 설정이 없습니다", + "cc84bfe0ee5d0174": "프로젝트", + "81d0d1e78b196630": "일반", + "fa19046edd6cfbd4": "모양", + "afda415d2d75a5d3": "채팅", + "4beeab8d1814b251": "변경 사항 및 풀 리퀘스트", + "3b958faa12d54484": "단축키", + "1a6679bbe62703b2": "SnapShots", + "2f77cc3105ddd7f8": "프로바이더", + "6d9bf91f0d4b7ba3": "스레드", + "795854feef8d2f52": "브라우저", + "9cc48e5c9ee46026": "기기", + "2ab325baee3ec9a3": "예약된 작업", + "a4380762611c94e4": "소스 제어", + "4889f7885396c26b": "워크트리", + "b5adbf54cbefee38": "환경", + "1de0df2b8a4fb96e": "공유 및 액세스", + "4c70e3e7b3e6c493": "시크릿", + "79b768229c9ef672": "유지 관리", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "정보", + "af4b7734da1d5ce7": "음성", + "2a546119bf3879ee": "보관함", + "2632f324dc2d9c48": "에이전트", + "58058320796d28f6": "코드", + "1a07e4d043f5df4e": "연결", + "e5144f91364fd9b7": "시간 형식", + "7e4d81ca21a72019": "고정 해제 확인", + "1d5052cbe70d0b28": "보관 확인", + "d5dd27a4eb853248": "삭제 확인", + "86b43caa9ff41ea2": "종료 단축키" +} From 13eb5c95a69279d5e566ec3cf09b4081b373a11a Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:03:19 +0000 Subject: [PATCH 007/253] feat(web): add Russian translation (#33166) --- apps/web/gt.config.json | 2 +- .../src/components/settings/settingsSearch.ts | 2 +- apps/web/src/i18n/locales.ts | 1 + apps/web/src/i18n/translations/ru.json | 74 +++++++++++++++++++ 4 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 apps/web/src/i18n/translations/ru.json diff --git a/apps/web/gt.config.json b/apps/web/gt.config.json index ae61c5349c47c..f0746dc7d2f38 100644 --- a/apps/web/gt.config.json +++ b/apps/web/gt.config.json @@ -1,6 +1,6 @@ { "defaultLocale": "en", - "locales": ["de", "es", "fr", "ja", "ko", "pt-BR", "zh"], + "locales": ["de", "es", "fr", "ja", "ko", "pt-BR", "ru", "zh"], "files": { "gt": { "output": "src/i18n/translations/[locale].json" diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 2233bdae5ac5b..13f8c9bfc7f72 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -684,7 +684,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Language"), to: "/settings/general", searchTerms: [ - "locale translation english deutsch german español spanish français french português portuguese brasil brazilian chinese 中文 japanese 日本語 korean 한국어 sprache idioma langue 语言 言語 언어", + "locale translation english deutsch german español spanish français french português portuguese brasil brazilian chinese 中文 japanese 日本語 korean 한국어 russian русский sprache idioma langue 语言 言語 언어 язык", ], }, { diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts index e03e115feb639..7c5a25e884161 100644 --- a/apps/web/src/i18n/locales.ts +++ b/apps/web/src/i18n/locales.ts @@ -13,6 +13,7 @@ const NATIVE_LANGUAGE_NAMES: Readonly> = { ja: "日本語", ko: "한국어", "pt-BR": "Português (Brasil)", + ru: "Русский", zh: "中文(简体)", }; diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json new file mode 100644 index 0000000000000..92a0fae70376d --- /dev/null +++ b/apps/web/src/i18n/translations/ru.json @@ -0,0 +1,74 @@ +{ + "0a75e464d833bca8": "Настройки", + "6aa1c88c4fa5be28": "Диагностика", + "fb29e435b1219373": "Лицензии открытого ПО", + "c0b0406e0cafa1d1": "Последнее сообщение", + "cb0775162a9b6419": "Дата создания", + "62570d4bfe4ab517": "Вручную", + "7eed14b9c7fd7661": "Как в системе", + "7fa9414ef5e9dd6c": "12-часовой", + "2f42917064c97f09": "24-часовой", + "7e8c995646a967d3": "Одно нажатие", + "51497bd401292062": "Удержание", + "9d6cc6ac23312071": "Двойное нажатие", + "e1483914168d6b8e": "Уведомления", + "798dc6846ed39fa0": "Уведомления в приложении", + "d9b0fbd680d5f175": "Боковая панель", + "cd5452cc9e13c818": "Группировка проектов", + "6147d6fc04079525": "Порядок проектов", + "bdf39fd139a04325": "Раздел Working", + "76f3c3e2f8dd0120": "Подтверждения", + "859e386f8af841f0": "Подтверждать открепление тредов", + "de0d79b74d3e4af6": "Подтверждать архивацию тредов", + "4ab8a4878cd80c77": "Подтверждать удаление тредов", + "0c853c878aab1908": "Выход по сочетанию клавиш", + "22e745b7db60e52f": "Отображение", + "2c1c93a646bbea6e": "Язык", + "c7b0bcb64f48db85": "Формат времени", + "cbf6a6bbc17e75e1": "Показывает всплывающее уведомление, если другой тред завершился, столкнулся с ошибкой или ждёт ввода либо подтверждения, пока приложение в фокусе.", + "83ca942c7163904f": "Объединяет одинаковые репозитории из разных окружений.", + "609da998ca13521e": "Порядок проектов в меню выбора проекта на боковой панели и в палитре команд.", + "b4c541137a76b351": "Сворачивает выполняющиеся и отслеживающие треды в раздел Working. Они возвращаются наверх списка, когда требуется ваше участие. В boring sidebar из Labs раздела Working нет.", + "e815f49e5abedcfd": "Запрашивает подтверждение перед откреплением треда.", + "41210f99adeeba78": "Требует повторного нажатия на кнопку архивации в строке, прежде чем тред будет архивирован.", + "84f3d2cefc8d2a74": "Запрашивает подтверждение перед удалением треда и его истории.", + "3fc130f1e8170073": "В режиме удержания выход также срабатывает по двойному нажатию.", + "72c7fda6ae301e6d": "«Как в системе» использует язык браузера или ОС.", + "b9ebecdb8db71466": "«Как в системе» использует формат времени браузера или ОС.", + "425f7ce2f24cb248": "Разделы настроек", + "ee3e8bd8b7918aec": "Поиск", + "858561b97fdd72f2": "Поиск по настройкам", + "fed2d32de2b0c566": "Очистить поиск по настройкам", + "833639e235c97484": "Результаты поиска по настройкам", + "be82bbfef472ab44": "Настройки не найдены", + "cc84bfe0ee5d0174": "Проекты", + "81d0d1e78b196630": "Общие", + "fa19046edd6cfbd4": "Внешний вид", + "afda415d2d75a5d3": "Чат", + "4beeab8d1814b251": "Диффы и пул-реквесты", + "3b958faa12d54484": "Сочетания клавиш", + "1a6679bbe62703b2": "SnapShots", + "2f77cc3105ddd7f8": "Провайдеры", + "6d9bf91f0d4b7ba3": "Треды", + "795854feef8d2f52": "Браузер", + "9cc48e5c9ee46026": "Устройства", + "2ab325baee3ec9a3": "Запланированные задачи", + "a4380762611c94e4": "Контроль версий", + "4889f7885396c26b": "Worktrees", + "b5adbf54cbefee38": "Окружения", + "1de0df2b8a4fb96e": "Общий доступ", + "4c70e3e7b3e6c493": "Секреты", + "79b768229c9ef672": "Обслуживание", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "О программе", + "af4b7734da1d5ce7": "Голос", + "2a546119bf3879ee": "Архив", + "2632f324dc2d9c48": "Агенты", + "58058320796d28f6": "Код", + "1a07e4d043f5df4e": "Подключения", + "e5144f91364fd9b7": "Формат времени", + "7e4d81ca21a72019": "Подтверждение открепления", + "1d5052cbe70d0b28": "Подтверждение архивации", + "d5dd27a4eb853248": "Подтверждение удаления", + "86b43caa9ff41ea2": "Сочетание клавиш для выхода" +} From 6eef4accedea3fdc104b62b3050be13cea6fb04e Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:03:20 +0000 Subject: [PATCH 008/253] feat(mobile): switch the settings language (#33169) --- apps/mobile/gt.config.json | 9 ++ apps/mobile/package.json | 7 + apps/mobile/src/Stack.tsx | 6 + .../settings/SettingsLanguageRouteScreen.tsx | 58 +++++++ .../features/settings/SettingsRouteScreen.tsx | 107 +++++++++---- .../components/settings-page-targets.ts | 1 + .../src/features/settings/settings-search.ts | 1 + apps/mobile/src/i18n/I18nProvider.tsx | 76 +++++++++ apps/mobile/src/i18n/intl-polyfills.ts | 6 + apps/mobile/src/i18n/locales.ts | 4 + apps/mobile/src/i18n/translations/de.json | 34 ++++ apps/mobile/src/i18n/translations/en.json | 34 ++++ apps/mobile/src/i18n/translations/es.json | 34 ++++ apps/mobile/src/i18n/translations/fr.json | 34 ++++ apps/mobile/src/i18n/translations/ja.json | 34 ++++ apps/mobile/src/i18n/translations/ko.json | 34 ++++ apps/mobile/src/i18n/translations/pt-BR.json | 34 ++++ apps/mobile/src/i18n/translations/ru.json | 34 ++++ apps/mobile/src/i18n/translations/zh.json | 34 ++++ .../src/persistence/mobile-preferences.ts | 4 + .../components/settings/SettingsPanels.tsx | 3 +- apps/web/src/i18n/locales.ts | 39 ----- apps/web/src/i18n/runtime.ts | 10 +- packages/client-runtime/package.json | 4 + packages/client-runtime/src/locales.ts | 44 ++++++ pnpm-lock.yaml | 146 ++++++++++++++++++ 26 files changed, 755 insertions(+), 76 deletions(-) create mode 100644 apps/mobile/gt.config.json create mode 100644 apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx create mode 100644 apps/mobile/src/i18n/I18nProvider.tsx create mode 100644 apps/mobile/src/i18n/intl-polyfills.ts create mode 100644 apps/mobile/src/i18n/locales.ts create mode 100644 apps/mobile/src/i18n/translations/de.json create mode 100644 apps/mobile/src/i18n/translations/en.json create mode 100644 apps/mobile/src/i18n/translations/es.json create mode 100644 apps/mobile/src/i18n/translations/fr.json create mode 100644 apps/mobile/src/i18n/translations/ja.json create mode 100644 apps/mobile/src/i18n/translations/ko.json create mode 100644 apps/mobile/src/i18n/translations/pt-BR.json create mode 100644 apps/mobile/src/i18n/translations/ru.json create mode 100644 apps/mobile/src/i18n/translations/zh.json create mode 100644 packages/client-runtime/src/locales.ts diff --git a/apps/mobile/gt.config.json b/apps/mobile/gt.config.json new file mode 100644 index 0000000000000..707f56d736cef --- /dev/null +++ b/apps/mobile/gt.config.json @@ -0,0 +1,9 @@ +{ + "defaultLocale": "en", + "locales": ["es", "zh", "pt-BR", "fr", "de", "ja", "ko", "ru"], + "files": { + "gt": { + "output": "src/i18n/translations/[locale].json" + } + } +} diff --git a/apps/mobile/package.json b/apps/mobile/package.json index d5c98d8152083..ca0b86a7a06d7 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -9,6 +9,8 @@ "dev:client:reset": "APP_VARIANT=development expo start --dev-client --scheme t3code-dev --clear --lan", "dev:client:preview-env": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=development expo start --dev-client --scheme t3code-dev --lan --port 0'", "dev:client:preview": "eas env:exec preview 'EXPO_NO_DOTENV=1 APP_VARIANT=preview expo start --dev-client --scheme t3code-preview --lan'", + "i18n:generate": "gt generate", + "i18n:translate": "gt translate", "start": "expo start", "start:dev": "APP_VARIANT=development expo start", "start:preview": "APP_VARIANT=preview expo start", @@ -58,6 +60,9 @@ "@expo-google-fonts/dm-sans": "^0.4.2", "@expo/metro-runtime": "~58.0.17", "@expo/ui": "58.0.27", + "@formatjs/intl-displaynames": "6.8.13", + "@formatjs/intl-getcanonicallocales": "2.5.6", + "@formatjs/intl-locale": "4.2.13", "@legendapp/list": "catalog:", "@material/material-color-utilities": "0.3.0", "@pierre/diffs": "catalog:", @@ -116,6 +121,7 @@ "expo-video": "58.0.13", "expo-web-browser": "~58.0.7", "expo-widgets": "58.0.27", + "gt-react-native": "11.4.18", "pele": "catalog:", "react": "catalog:", "react-dom": "catalog:", @@ -148,6 +154,7 @@ "@types/react-dom": "catalog:", "aws4fetch": "1.0.20", "babel-preset-expo": "~58.0.24", + "gt": "2.27.0", "jsdom": "^30.0.1", "nitrogen": "0.37.2", "tailwindcss": "^4.0.0" diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index b8ab00673db12..d93bf076a78e0 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -96,6 +96,7 @@ import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteSc import { SettingsEnvironmentDetailRouteScreen } from "./features/settings/SettingsEnvironmentDetailRouteScreen"; import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen"; import { SettingsFollowUpRouteScreen } from "./features/settings/SettingsFollowUpRouteScreen"; +import { SettingsLanguageRouteScreen } from "./features/settings/SettingsLanguageRouteScreen"; import { SettingsEnvironmentMaintenanceRouteScreen, SettingsThreadsRouteScreen, @@ -257,6 +258,11 @@ const SETTINGS_SCREENS = { linking: "settings/organization", options: settingsPage("General"), }), + SettingsLanguage: createNativeStackScreen({ + screen: SettingsLanguageRouteScreen, + linking: "settings/language", + options: settingsPage("Language"), + }), SettingsProjectOverview: createNativeStackScreen({ screen: SettingsProjectOverviewRouteScreen, linking: "settings/project", diff --git a/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx new file mode 100644 index 0000000000000..cb0ecbb6d8c01 --- /dev/null +++ b/apps/mobile/src/features/settings/SettingsLanguageRouteScreen.tsx @@ -0,0 +1,58 @@ +import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView"; +import { useAtomSet, useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/reactivity"; +import { useSafeAreaInsets } from "react-native-safe-area-context"; + +import { I18nProvider, useGT, useLanguagePreference } from "../../i18n/I18nProvider"; +import { SYSTEM_LANGUAGE, nativeLanguageName } from "@t3tools/client-runtime/locales"; +import { SUPPORTED_LOCALES } from "../../i18n/locales"; +import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences"; +import { ListChoiceRow as SettingsChoiceRow } from "../../components/ui/ListChoiceRow"; +import { SettingsSection } from "./components/SettingsSection"; +import { SettingsScreen } from "./components/SettingsScreen"; + +export function SettingsLanguageRouteScreen() { + return ( + + + + ); +} + +function LanguageSettings() { + const gt = useGT(); + const insets = useSafeAreaInsets(); + const preferencesResult = useAtomValue(mobilePreferencesAtom); + const savePreferences = useAtomSet(updateMobilePreferencesAtom); + const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting; + const language = useLanguagePreference(); + const options = [ + { language: SYSTEM_LANGUAGE, label: gt("System default") }, + ...SUPPORTED_LOCALES.map((locale) => ({ language: locale, label: nativeLanguageName(locale) })), + ]; + + return ( + + + + {options.map((option, index) => ( + 0} + disabled={!preferencesReady} + onPress={() => savePreferences({ language: option.language })} + /> + ))} + + + + ); +} diff --git a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx index 418e4286502da..50ad81383addc 100644 --- a/apps/mobile/src/features/settings/SettingsRouteScreen.tsx +++ b/apps/mobile/src/features/settings/SettingsRouteScreen.tsx @@ -33,6 +33,9 @@ import { useSettingsEnvironmentMenu } from "./components/SettingsEnvironmentFilt import { useSettingsEnvironmentFilter } from "./settings-environment-filter"; import { filterSettingsSections } from "./settings-search"; import { usePaneRole } from "../../components/ui/Pane"; +import { I18nProvider, useGT, useLanguagePreference } from "../../i18n/I18nProvider"; +import { nativeLanguageName } from "@t3tools/client-runtime/locales"; +import { SUPPORTED_LOCALES } from "../../i18n/locales"; export function SettingsRouteScreen() { const list = useSettingsListPlacement(); @@ -45,7 +48,9 @@ export function WorkspaceSettingsList() { return ( - + + + ); @@ -73,13 +78,25 @@ export function SettingsListScreen(props: { readonly sidebar: boolean; readonly selected: string | null; }) { + return ( + + + + ); +} + +function TranslatedSettingsListScreen(props: { + readonly sidebar: boolean; + readonly selected: string | null; +}) { + const gt = useGT(); const workspace = useWorkspaceTabs(); const environmentMenu = useSettingsEnvironmentMenu(); return ( workspace.dispatch({ type: "query", tab: "settings", query }), - placeholder: "Search settings", + placeholder: gt("Search settings"), } : undefined } @@ -108,15 +125,16 @@ interface SettingsListSection { } function ConfiguredSettingsRouteScreen() { + const gt = useGT(); const navigation = useNavigation(); const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false }); const { user } = useUser(); const { savedConnectionsById } = useSavedRemoteConnections(); const accountLabel = !isLoaded - ? "Checking" + ? gt("Checking") : !isSignedIn - ? "Sign in" - : (user?.primaryEmailAddress?.emailAddress ?? "Signed in"); + ? gt("Sign in") + : (user?.primaryEmailAddress?.emailAddress ?? gt("Signed in")); return ( navigation.navigate("SettingsAuth"), }, - environmentsRow(Object.keys(savedConnectionsById).length), + environmentsRow(gt("Environments"), Object.keys(savedConnectionsById).length), { id: "SettingsNotifications", icon: "bell.badge", - label: "Notifications", + label: gt("Notifications"), target: "SettingsNotifications", }, ]} @@ -142,15 +160,20 @@ function ConfiguredSettingsRouteScreen() { } function LocalSettingsRouteScreen() { + const gt = useGT(); const { savedConnectionsById } = useSavedRemoteConnections(); - return ; + return ( + + ); } -function environmentsRow(count: number): SettingsListRow { +function environmentsRow(label: string, count: number): SettingsListRow { return { id: "SettingsEnvironments", icon: "desktopcomputer", - label: "Environments", + label, value: `${count}`, valuePosition: "trailing", target: "SettingsEnvironments", @@ -158,6 +181,7 @@ function environmentsRow(count: number): SettingsListRow { } function SettingsList(props: { readonly connections: readonly SettingsListRow[] }) { + const gt = useGT(); // UIKit's scroll-edge material takes the scroll view's own color; like the chat list, match // the sidebar's surface so the bar doesn't darken over content at rest. // Grouped cards only lift off the screen surface; the drawer is as dark as they are. @@ -170,7 +194,11 @@ function SettingsList(props: { readonly connections: readonly SettingsListRow[] const overflowRows = useOverflowRows(); const indexSections = useSettingsIndexSections(); const sections = filterSettingsSections( - [{ rows: overflowRows }, { title: "Connections", rows: props.connections }, ...indexSections], + [ + { rows: overflowRows }, + { title: gt("Connections"), rows: props.connections }, + ...indexSections, + ], query, ); @@ -202,8 +230,8 @@ function SettingsList(props: { readonly connections: readonly SettingsListRow[] ) : ( )} @@ -212,6 +240,8 @@ function SettingsList(props: { readonly connections: readonly SettingsListRow[] } function useSettingsIndexSections(): SettingsListSection[] { + const gt = useGT(); + const language = useLanguagePreference(); const { selectedTargets, projectGroups, selectedProjectKey } = useSettingsEnvironmentFilter(); const noServerTargets = selectedTargets.length === 0; const selectedProject = projectGroups.find((group) => group.key === selectedProjectKey); @@ -227,7 +257,7 @@ function useSettingsIndexSections(): SettingsListSection[] { representative: scopedProjectMembers[0]!, members: scopedProjectMembers, }) - : (selectedProject?.label ?? "Unavailable project"); + : (selectedProject?.label ?? gt("Unavailable project")); const page = ( target: SettingsPageTarget, icon: SettingsListRow["icon"], @@ -240,43 +270,52 @@ function useSettingsIndexSections(): SettingsListSection[] { return [ { rows: [ - page("SettingsOrganization", "gearshape", "General"), - page("SettingsAppearance", "paintbrush", "Appearance"), - page("SettingsFollowUp", "bubble.left.and.bubble.right", "Chat"), + page("SettingsOrganization", "gearshape", gt("General")), + page("SettingsAppearance", "paintbrush", gt("Appearance")), + page("SettingsLanguage", "globe", gt("Language"), { + value: SUPPORTED_LOCALES.includes(language) + ? nativeLanguageName(language) + : gt("System default"), + }), + page("SettingsFollowUp", "bubble.left.and.bubble.right", gt("Chat")), ...(navigationCustomizationAvailable() - ? [page("SettingsNavigation", "line.3.horizontal", "Navigation tabs")] + ? [page("SettingsNavigation", "line.3.horizontal", gt("Navigation tabs"))] : []), - page("SettingsKeyboard", "keyboard", "Keyboard"), - page("SettingsVoice", "mic", "Voice"), + page("SettingsKeyboard", "keyboard", gt("Keyboard")), + page("SettingsVoice", "mic", gt("Voice")), ], }, { - title: "Agents", + title: gt("Agents"), rows: [ - serverPage("SettingsProviderAccounts", "person.crop.circle", "Providers"), - serverPage("SettingsThreads", "text.bubble", "Threads"), - page("SettingsScheduledTasks", "clock", "Scheduled tasks"), + serverPage("SettingsProviderAccounts", "person.crop.circle", gt("Providers")), + serverPage("SettingsThreads", "text.bubble", gt("Threads")), + page("SettingsScheduledTasks", "clock", gt("Scheduled tasks")), ], }, { - title: "Code", + title: gt("Code"), rows: [ page( "SettingsProjectOverview", "folder", - "Projects", + gt("Projects"), selectedProjectKey !== null ? { value: projectLabel } : undefined, ), - serverPage("SettingsEnvironmentSourceControl", "arrow.triangle.branch", "Source control"), - serverPage("SettingsWorktrees", "square.on.square", "Worktrees"), + serverPage( + "SettingsEnvironmentSourceControl", + "arrow.triangle.branch", + gt("Source control"), + ), + serverPage("SettingsWorktrees", "square.on.square", gt("Worktrees")), ], }, { rows: [ - serverPage("SettingsEnvironmentMaintenance", "arrow.clockwise", "Maintenance"), - page("SettingsLabs", "flask", "Labs"), - page("SettingsAbout", "info.circle", "About"), - page("SettingsArchive", "archivebox", "Archive"), + serverPage("SettingsEnvironmentMaintenance", "arrow.clockwise", gt("Maintenance")), + page("SettingsLabs", "flask", gt("Labs")), + page("SettingsAbout", "info.circle", gt("About")), + page("SettingsArchive", "archivebox", gt("Archive")), ], }, ]; diff --git a/apps/mobile/src/features/settings/components/settings-page-targets.ts b/apps/mobile/src/features/settings/components/settings-page-targets.ts index eadd9c46fff7b..a92922a66d1e3 100644 --- a/apps/mobile/src/features/settings/components/settings-page-targets.ts +++ b/apps/mobile/src/features/settings/components/settings-page-targets.ts @@ -6,6 +6,7 @@ export const SETTINGS_PAGE_TARGETS = [ "SettingsAbout", "SettingsArchive", "SettingsAppearance", + "SettingsLanguage", "SettingsNavigation", "SettingsOrganization", "SettingsProjectOverview", diff --git a/apps/mobile/src/features/settings/settings-search.ts b/apps/mobile/src/features/settings/settings-search.ts index 4d02bd9789b1d..49e1a8dbe082e 100644 --- a/apps/mobile/src/features/settings/settings-search.ts +++ b/apps/mobile/src/features/settings/settings-search.ts @@ -33,6 +33,7 @@ const SETTINGS_SEARCH_TERMS = { "zen", "final answers only", ], + SettingsLanguage: ["language", "locale", "translation", "english"], SettingsNavigation: ["tabs", "tab order", "reorder", "hide tabs"], SettingsKeyboard: ["return key", "send message", "new line", "hardware keyboard"], SettingsVoice: [ diff --git a/apps/mobile/src/i18n/I18nProvider.tsx b/apps/mobile/src/i18n/I18nProvider.tsx new file mode 100644 index 0000000000000..54077311b340e --- /dev/null +++ b/apps/mobile/src/i18n/I18nProvider.tsx @@ -0,0 +1,76 @@ +import "./intl-polyfills"; +import { resolveLocale } from "@t3tools/client-runtime/locales"; +import { useAtomValue } from "@effect/atom-react"; +import { AsyncResult } from "effect/reactivity"; +import { GTProvider, initializeGT } from "gt-react-native"; +import { useDeferredValue, type ReactNode } from "react"; +import { Platform, TurboModuleRegistry, View, type TurboModule } from "react-native"; + +import { mobilePreferencesAtom } from "../state/preferences"; +import { DEFAULT_LOCALE, SUPPORTED_LOCALES } from "./locales"; +import de from "./translations/de.json"; +import es from "./translations/es.json"; +import fr from "./translations/fr.json"; +import ja from "./translations/ja.json"; +import ko from "./translations/ko.json"; +import ptBR from "./translations/pt-BR.json"; +import ru from "./translations/ru.json"; +import zh from "./translations/zh.json"; + +// Screens import GT from here so the polyfills above always load first. +export { useGT } from "gt-react-native"; + +// Committed catalogs, so forks and offline installs never reach GT's CDN. English is the source. +const TRANSLATIONS: Readonly>> = { + es, + zh, + "pt-BR": ptBR, + fr, + de, + ja, + ko, + ru, +}; + +initializeGT({ + defaultLocale: DEFAULT_LOCALE, + locales: [...SUPPORTED_LOCALES], + loadTranslations: async (locale: string) => TRANSLATIONS[locale] ?? {}, +}); + +// Read the device languages from gt-react-native's own native module: GT's getLocale() prefers +// the last locale passed to GTProvider, which it persists, so it can't express "system". +function readSystemLocales(): ReadonlyArray { + try { + const locales = + TurboModuleRegistry.get<{ getNativeLocales(): string[] } & TurboModule>( + "GtReactNative", + )?.getNativeLocales() ?? []; + // On iOS the first entry is NSLocale.currentLocale, whose language is the app's bundle + // localization (English only), not the user's; preferredLanguages follow it. + return Platform.OS === "ios" ? locales.slice(1) : locales; + } catch { + return []; + } +} + +export function useLanguagePreference(): string { + const preferences = useAtomValue(mobilePreferencesAtom); + return AsyncResult.isSuccess(preferences) + ? (preferences.value.language ?? DEFAULT_LOCALE) + : DEFAULT_LOCALE; +} + +/** Translates the screens inside it into the saved language; "system" follows the device. */ +export function I18nProvider(props: { readonly children: ReactNode }) { + // GT suspends while a locale's catalog loads. Deferring the switch keeps the current language + // on screen until then, instead of GT's full-screen spinner. + const locale = useDeferredValue( + resolveLocale(useLanguagePreference(), readSystemLocales(), SUPPORTED_LOCALES, DEFAULT_LOCALE), + ); + return ( + }> + {props.children} + + ); +} diff --git a/apps/mobile/src/i18n/intl-polyfills.ts b/apps/mobile/src/i18n/intl-polyfills.ts new file mode 100644 index 0000000000000..9097da285cd89 --- /dev/null +++ b/apps/mobile/src/i18n/intl-polyfills.ts @@ -0,0 +1,6 @@ +// GT validates every locale with Intl.Locale and English Intl.DisplayNames, which Hermes lacks. +// gt-react-native's Babel plugin would inject these; plain imports keep the Metro and Babel config unchanged. +import "@formatjs/intl-getcanonicallocales/polyfill"; +import "@formatjs/intl-locale/polyfill"; +import "@formatjs/intl-displaynames/polyfill"; +import "@formatjs/intl-displaynames/locale-data/en"; diff --git a/apps/mobile/src/i18n/locales.ts b/apps/mobile/src/i18n/locales.ts new file mode 100644 index 0000000000000..26ac5721e4915 --- /dev/null +++ b/apps/mobile/src/i18n/locales.ts @@ -0,0 +1,4 @@ +import gtConfig from "../../gt.config.json"; + +export const DEFAULT_LOCALE = gtConfig.defaultLocale; +export const SUPPORTED_LOCALES: ReadonlyArray = [DEFAULT_LOCALE, ...gtConfig.locales]; diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json new file mode 100644 index 0000000000000..425711d56def2 --- /dev/null +++ b/apps/mobile/src/i18n/translations/de.json @@ -0,0 +1,34 @@ +{ + "7eed14b9c7fd7661": "Systemstandard", + "2c1c93a646bbea6e": "Sprache", + "0a75e464d833bca8": "Einstellungen", + "858561b97fdd72f2": "Einstellungen durchsuchen", + "79e4d73c1bc8cf45": "Wird geprüft", + "4681c4c9541539a4": "Anmelden", + "9e8db85a88bbfa4a": "Angemeldet", + "bd7ace2d408d814b": "T3-Konto", + "b5adbf54cbefee38": "Umgebungen", + "e1483914168d6b8e": "Benachrichtigungen", + "1a07e4d043f5df4e": "Verbindungen", + "3d1e7ff5894d00dd": "Keine Ergebnisse", + "1be65659f947b808": "Keine Einstellungen für „{query}“ gefunden.", + "1cf216566c1ee064": "Projekt nicht verfügbar", + "81d0d1e78b196630": "Allgemein", + "fa19046edd6cfbd4": "Darstellung", + "afda415d2d75a5d3": "Chat", + "560997ace98edc9f": "Tableiste", + "0bcc63fce8f612b5": "Tastatur", + "af4b7734da1d5ce7": "Spracheingabe", + "2632f324dc2d9c48": "Agenten", + "2f77cc3105ddd7f8": "Anbieter", + "6d9bf91f0d4b7ba3": "Threads", + "2ab325baee3ec9a3": "Geplante Aufgaben", + "58058320796d28f6": "Code", + "cc84bfe0ee5d0174": "Projekte", + "a4380762611c94e4": "Versionskontrolle", + "4889f7885396c26b": "Worktrees", + "79b768229c9ef672": "Wartung", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "Info", + "2a546119bf3879ee": "Archiv" +} diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json new file mode 100644 index 0000000000000..7b7faaa54b918 --- /dev/null +++ b/apps/mobile/src/i18n/translations/en.json @@ -0,0 +1,34 @@ +{ + "7eed14b9c7fd7661": "System default", + "2c1c93a646bbea6e": "Language", + "0a75e464d833bca8": "Settings", + "858561b97fdd72f2": "Search settings", + "79e4d73c1bc8cf45": "Checking", + "4681c4c9541539a4": "Sign in", + "9e8db85a88bbfa4a": "Signed in", + "bd7ace2d408d814b": "T3 Account", + "b5adbf54cbefee38": "Environments", + "e1483914168d6b8e": "Notifications", + "1a07e4d043f5df4e": "Connections", + "3d1e7ff5894d00dd": "No results", + "1be65659f947b808": "No settings match “{query}”.", + "1cf216566c1ee064": "Unavailable project", + "81d0d1e78b196630": "General", + "fa19046edd6cfbd4": "Appearance", + "afda415d2d75a5d3": "Chat", + "560997ace98edc9f": "Navigation tabs", + "0bcc63fce8f612b5": "Keyboard", + "af4b7734da1d5ce7": "Voice", + "2632f324dc2d9c48": "Agents", + "2f77cc3105ddd7f8": "Providers", + "6d9bf91f0d4b7ba3": "Threads", + "2ab325baee3ec9a3": "Scheduled tasks", + "58058320796d28f6": "Code", + "cc84bfe0ee5d0174": "Projects", + "a4380762611c94e4": "Source control", + "4889f7885396c26b": "Worktrees", + "79b768229c9ef672": "Maintenance", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "About", + "2a546119bf3879ee": "Archive" +} diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json new file mode 100644 index 0000000000000..3e1cbc11fdef9 --- /dev/null +++ b/apps/mobile/src/i18n/translations/es.json @@ -0,0 +1,34 @@ +{ + "7eed14b9c7fd7661": "Del sistema", + "2c1c93a646bbea6e": "Idioma", + "0a75e464d833bca8": "Ajustes", + "858561b97fdd72f2": "Buscar ajustes", + "79e4d73c1bc8cf45": "Comprobando", + "4681c4c9541539a4": "Iniciar sesión", + "9e8db85a88bbfa4a": "Sesión iniciada", + "bd7ace2d408d814b": "Cuenta de T3", + "b5adbf54cbefee38": "Entornos", + "e1483914168d6b8e": "Notificaciones", + "1a07e4d043f5df4e": "Conexiones", + "3d1e7ff5894d00dd": "Sin resultados", + "1be65659f947b808": "Ningún ajuste coincide con «{query}».", + "1cf216566c1ee064": "Proyecto no disponible", + "81d0d1e78b196630": "General", + "fa19046edd6cfbd4": "Apariencia", + "afda415d2d75a5d3": "Chat", + "560997ace98edc9f": "Pestañas de navegación", + "0bcc63fce8f612b5": "Teclado", + "af4b7734da1d5ce7": "Voz", + "2632f324dc2d9c48": "Agentes", + "2f77cc3105ddd7f8": "Proveedores", + "6d9bf91f0d4b7ba3": "Hilos", + "2ab325baee3ec9a3": "Tareas programadas", + "58058320796d28f6": "Código", + "cc84bfe0ee5d0174": "Proyectos", + "a4380762611c94e4": "Control de versiones", + "4889f7885396c26b": "Worktrees", + "79b768229c9ef672": "Mantenimiento", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "Acerca de", + "2a546119bf3879ee": "Archivados" +} diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json new file mode 100644 index 0000000000000..973f96c060fa3 --- /dev/null +++ b/apps/mobile/src/i18n/translations/fr.json @@ -0,0 +1,34 @@ +{ + "7eed14b9c7fd7661": "Langue du système", + "2c1c93a646bbea6e": "Langue", + "0a75e464d833bca8": "Réglages", + "858561b97fdd72f2": "Rechercher dans les réglages", + "79e4d73c1bc8cf45": "Vérification…", + "4681c4c9541539a4": "Se connecter", + "9e8db85a88bbfa4a": "Connecté", + "bd7ace2d408d814b": "Compte T3", + "b5adbf54cbefee38": "Environnements", + "e1483914168d6b8e": "Notifications", + "1a07e4d043f5df4e": "Connexions", + "3d1e7ff5894d00dd": "Aucun résultat", + "1be65659f947b808": "Aucun réglage ne correspond à « {query} ».", + "1cf216566c1ee064": "Projet indisponible", + "81d0d1e78b196630": "Général", + "fa19046edd6cfbd4": "Apparence", + "afda415d2d75a5d3": "Discussion", + "560997ace98edc9f": "Onglets de navigation", + "0bcc63fce8f612b5": "Clavier", + "af4b7734da1d5ce7": "Voix", + "2632f324dc2d9c48": "Agents", + "2f77cc3105ddd7f8": "Fournisseurs", + "6d9bf91f0d4b7ba3": "Conversations", + "2ab325baee3ec9a3": "Tâches planifiées", + "58058320796d28f6": "Code", + "cc84bfe0ee5d0174": "Projets", + "a4380762611c94e4": "Gestion de versions", + "4889f7885396c26b": "Worktrees", + "79b768229c9ef672": "Maintenance", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "À propos", + "2a546119bf3879ee": "Archives" +} diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json new file mode 100644 index 0000000000000..21c5cdebb22e1 --- /dev/null +++ b/apps/mobile/src/i18n/translations/ja.json @@ -0,0 +1,34 @@ +{ + "7eed14b9c7fd7661": "システムのデフォルト", + "2c1c93a646bbea6e": "言語", + "0a75e464d833bca8": "設定", + "858561b97fdd72f2": "設定を検索", + "79e4d73c1bc8cf45": "確認中", + "4681c4c9541539a4": "サインイン", + "9e8db85a88bbfa4a": "サインイン済み", + "bd7ace2d408d814b": "T3 アカウント", + "b5adbf54cbefee38": "環境", + "e1483914168d6b8e": "通知", + "1a07e4d043f5df4e": "接続", + "3d1e7ff5894d00dd": "結果なし", + "1be65659f947b808": "「{query}」に一致する設定はありません。", + "1cf216566c1ee064": "利用できないプロジェクト", + "81d0d1e78b196630": "一般", + "fa19046edd6cfbd4": "外観", + "afda415d2d75a5d3": "チャット", + "560997ace98edc9f": "ナビゲーションタブ", + "0bcc63fce8f612b5": "キーボード", + "af4b7734da1d5ce7": "音声", + "2632f324dc2d9c48": "エージェント", + "2f77cc3105ddd7f8": "プロバイダー", + "6d9bf91f0d4b7ba3": "スレッド", + "2ab325baee3ec9a3": "スケジュールタスク", + "58058320796d28f6": "コード", + "cc84bfe0ee5d0174": "プロジェクト", + "a4380762611c94e4": "ソース管理", + "4889f7885396c26b": "ワークツリー", + "79b768229c9ef672": "メンテナンス", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "情報", + "2a546119bf3879ee": "アーカイブ" +} diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json new file mode 100644 index 0000000000000..2d48fed7591fe --- /dev/null +++ b/apps/mobile/src/i18n/translations/ko.json @@ -0,0 +1,34 @@ +{ + "7eed14b9c7fd7661": "시스템 기본값", + "2c1c93a646bbea6e": "언어", + "0a75e464d833bca8": "설정", + "858561b97fdd72f2": "설정 검색", + "79e4d73c1bc8cf45": "확인 중", + "4681c4c9541539a4": "로그인", + "9e8db85a88bbfa4a": "로그인됨", + "bd7ace2d408d814b": "T3 계정", + "b5adbf54cbefee38": "환경", + "e1483914168d6b8e": "알림", + "1a07e4d043f5df4e": "연결", + "3d1e7ff5894d00dd": "결과 없음", + "1be65659f947b808": "‘{query}’에 해당하는 설정이 없습니다.", + "1cf216566c1ee064": "사용할 수 없는 프로젝트", + "81d0d1e78b196630": "일반", + "fa19046edd6cfbd4": "모양", + "afda415d2d75a5d3": "채팅", + "560997ace98edc9f": "탐색 탭", + "0bcc63fce8f612b5": "키보드", + "af4b7734da1d5ce7": "음성", + "2632f324dc2d9c48": "에이전트", + "2f77cc3105ddd7f8": "제공자", + "6d9bf91f0d4b7ba3": "스레드", + "2ab325baee3ec9a3": "예약된 작업", + "58058320796d28f6": "코드", + "cc84bfe0ee5d0174": "프로젝트", + "a4380762611c94e4": "소스 제어", + "4889f7885396c26b": "워크트리", + "79b768229c9ef672": "유지 관리", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "정보", + "2a546119bf3879ee": "보관함" +} diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json new file mode 100644 index 0000000000000..e2f1ca1360be7 --- /dev/null +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -0,0 +1,34 @@ +{ + "7eed14b9c7fd7661": "Padrão do sistema", + "2c1c93a646bbea6e": "Idioma", + "0a75e464d833bca8": "Configurações", + "858561b97fdd72f2": "Buscar configurações", + "79e4d73c1bc8cf45": "Verificando", + "4681c4c9541539a4": "Entrar", + "9e8db85a88bbfa4a": "Conectado", + "bd7ace2d408d814b": "Conta T3", + "b5adbf54cbefee38": "Ambientes", + "e1483914168d6b8e": "Notificações", + "1a07e4d043f5df4e": "Conexões", + "3d1e7ff5894d00dd": "Nenhum resultado", + "1be65659f947b808": "Nenhuma configuração encontrada para “{query}”.", + "1cf216566c1ee064": "Projeto indisponível", + "81d0d1e78b196630": "Geral", + "fa19046edd6cfbd4": "Aparência", + "afda415d2d75a5d3": "Chat", + "560997ace98edc9f": "Abas de navegação", + "0bcc63fce8f612b5": "Teclado", + "af4b7734da1d5ce7": "Voz", + "2632f324dc2d9c48": "Agentes", + "2f77cc3105ddd7f8": "Provedores", + "6d9bf91f0d4b7ba3": "Threads", + "2ab325baee3ec9a3": "Tarefas agendadas", + "58058320796d28f6": "Código", + "cc84bfe0ee5d0174": "Projetos", + "a4380762611c94e4": "Controle de versão", + "4889f7885396c26b": "Worktrees", + "79b768229c9ef672": "Manutenção", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "Sobre", + "2a546119bf3879ee": "Arquivados" +} diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json new file mode 100644 index 0000000000000..305cc823edaf5 --- /dev/null +++ b/apps/mobile/src/i18n/translations/ru.json @@ -0,0 +1,34 @@ +{ + "7eed14b9c7fd7661": "Как в системе", + "2c1c93a646bbea6e": "Язык", + "0a75e464d833bca8": "Настройки", + "858561b97fdd72f2": "Поиск настроек", + "79e4d73c1bc8cf45": "Проверка…", + "4681c4c9541539a4": "Войти", + "9e8db85a88bbfa4a": "Вход выполнен", + "bd7ace2d408d814b": "Аккаунт T3", + "b5adbf54cbefee38": "Окружения", + "e1483914168d6b8e": "Уведомления", + "1a07e4d043f5df4e": "Подключения", + "3d1e7ff5894d00dd": "Ничего не найдено", + "1be65659f947b808": "Нет настроек по запросу «{query}».", + "1cf216566c1ee064": "Проект недоступен", + "81d0d1e78b196630": "Основные", + "fa19046edd6cfbd4": "Оформление", + "afda415d2d75a5d3": "Чат", + "560997ace98edc9f": "Панель вкладок", + "0bcc63fce8f612b5": "Клавиатура", + "af4b7734da1d5ce7": "Голос", + "2632f324dc2d9c48": "Агенты", + "2f77cc3105ddd7f8": "Провайдеры", + "6d9bf91f0d4b7ba3": "Треды", + "2ab325baee3ec9a3": "Запланированные задачи", + "58058320796d28f6": "Код", + "cc84bfe0ee5d0174": "Проекты", + "a4380762611c94e4": "Контроль версий", + "4889f7885396c26b": "Рабочие деревья", + "79b768229c9ef672": "Обслуживание", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "О приложении", + "2a546119bf3879ee": "Архив" +} diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json new file mode 100644 index 0000000000000..2927acda50b46 --- /dev/null +++ b/apps/mobile/src/i18n/translations/zh.json @@ -0,0 +1,34 @@ +{ + "7eed14b9c7fd7661": "系统默认", + "2c1c93a646bbea6e": "语言", + "0a75e464d833bca8": "设置", + "858561b97fdd72f2": "搜索设置", + "79e4d73c1bc8cf45": "正在检查", + "4681c4c9541539a4": "登录", + "9e8db85a88bbfa4a": "已登录", + "bd7ace2d408d814b": "T3 账户", + "b5adbf54cbefee38": "环境", + "e1483914168d6b8e": "通知", + "1a07e4d043f5df4e": "连接", + "3d1e7ff5894d00dd": "无结果", + "1be65659f947b808": "没有与“{query}”匹配的设置。", + "1cf216566c1ee064": "项目不可用", + "81d0d1e78b196630": "通用", + "fa19046edd6cfbd4": "外观", + "afda415d2d75a5d3": "聊天", + "560997ace98edc9f": "标签栏", + "0bcc63fce8f612b5": "键盘", + "af4b7734da1d5ce7": "语音", + "2632f324dc2d9c48": "代理", + "2f77cc3105ddd7f8": "提供方", + "6d9bf91f0d4b7ba3": "线程", + "2ab325baee3ec9a3": "定时任务", + "58058320796d28f6": "代码", + "cc84bfe0ee5d0174": "项目", + "a4380762611c94e4": "源代码管理", + "4889f7885396c26b": "工作树", + "79b768229c9ef672": "维护", + "54b188d65247e42f": "Labs", + "f41ea186c275b56e": "关于", + "2a546119bf3879ee": "已归档" +} diff --git a/apps/mobile/src/persistence/mobile-preferences.ts b/apps/mobile/src/persistence/mobile-preferences.ts index ed2d0b063c767..852d96c608520 100644 --- a/apps/mobile/src/persistence/mobile-preferences.ts +++ b/apps/mobile/src/persistence/mobile-preferences.ts @@ -113,6 +113,8 @@ export interface Preferences { /** Hardware-keyboard Return behavior in the composer. */ readonly composerEnterBehavior?: ComposerEnterBehavior; readonly followUpBehavior?: FollowUpBehavior; + /** The client `language` setting: a locale code or "system". Unset means English. */ + readonly language?: string; readonly microphones?: ReadonlyArray; readonly projectGroupingEnabled?: boolean; readonly projectGroupingMode?: SidebarProjectGroupingMode; @@ -197,6 +199,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { dismissedDatabaseStorageNotices?: readonly string[]; composerEnterBehavior?: ComposerEnterBehavior; followUpBehavior?: FollowUpBehavior; + language?: string; microphones?: ReadonlyArray; projectGroupingEnabled?: boolean; projectGroupingMode?: SidebarProjectGroupingMode; @@ -305,6 +308,7 @@ function sanitizePreferences(parsed: Preferences): Preferences { if (parsed.followUpBehavior === "queue" || parsed.followUpBehavior === "steer") { preferences.followUpBehavior = parsed.followUpBehavior; } + if (typeof parsed.language === "string") preferences.language = parsed.language; if (Array.isArray(parsed.microphones)) { preferences.microphones = parsed.microphones.flatMap((entry): MicrophoneEntry[] => { if (typeof entry !== "object" || entry === null || !isMicrophoneKind(entry.kind)) return []; diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index c5548175fd1e7..d46c1875876f4 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -105,7 +105,8 @@ import { SettingsSection, } from "./settingsLayout"; import { searchableSetting, type SettingsSearchItemId } from "./settingsSearch"; -import { nativeLanguageName, SUPPORTED_LOCALES, SYSTEM_LANGUAGE } from "../../i18n/locales"; +import { nativeLanguageName, SYSTEM_LANGUAGE } from "@t3tools/client-runtime/locales"; +import { SUPPORTED_LOCALES } from "../../i18n/locales"; import { BackgroundActivitySettingsRow } from "./BackgroundActivitySettings"; import { AdvancedSettings } from "./AdvancedSettings"; import { PullRequestLinksOpenInAppSetting } from "./IntegrationsSettings"; diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts index 7c5a25e884161..26ac5721e4915 100644 --- a/apps/web/src/i18n/locales.ts +++ b/apps/web/src/i18n/locales.ts @@ -1,43 +1,4 @@ import gtConfig from "../../gt.config.json"; -export const SYSTEM_LANGUAGE = "system"; export const DEFAULT_LOCALE = gtConfig.defaultLocale; export const SUPPORTED_LOCALES: ReadonlyArray = [DEFAULT_LOCALE, ...gtConfig.locales]; - -// Shown in their own language so a user can find theirs from any UI language. -const NATIVE_LANGUAGE_NAMES: Readonly> = { - en: "English", - de: "Deutsch", - es: "Español", - fr: "Français", - ja: "日本語", - ko: "한국어", - "pt-BR": "Português (Brasil)", - ru: "Русский", - zh: "中文(简体)", -}; - -export function nativeLanguageName(locale: string): string { - return NATIVE_LANGUAGE_NAMES[locale] ?? locale; -} - -// Our `zh` is Simplified, so Traditional tags only match an exact locale. -const TRADITIONAL_CHINESE = /^zh[-_](hant|tw|hk|mo)\b/; - -function matchSupportedLocale(tag: string): string | undefined { - const normalized = tag.trim().toLowerCase(); - const language = normalized.split(/[-_]/)[0]; - const exact = SUPPORTED_LOCALES.find((locale) => locale.toLowerCase() === normalized); - if (exact || TRADITIONAL_CHINESE.test(normalized)) return exact; - return SUPPORTED_LOCALES.find((locale) => locale.toLowerCase() === language); -} - -/** Saved setting to active locale; "system" and unknown values follow the host's languages. */ -export function resolveLocale(language: string, systemLocales: ReadonlyArray): string { - if (SUPPORTED_LOCALES.includes(language)) return language; - for (const tag of systemLocales) { - const match = matchSupportedLocale(tag); - if (match) return match; - } - return DEFAULT_LOCALE; -} diff --git a/apps/web/src/i18n/runtime.ts b/apps/web/src/i18n/runtime.ts index 82b3f8d6ceb8d..4fac3aec2a344 100644 --- a/apps/web/src/i18n/runtime.ts +++ b/apps/web/src/i18n/runtime.ts @@ -1,3 +1,4 @@ +import { resolveLocale } from "@t3tools/client-runtime/locales"; import { getTranslationsSnapshot } from "gt-react"; import { @@ -6,7 +7,7 @@ import { updateClientSettings, } from "../hooks/useSettings"; import { initializeI18n } from "./initializeI18n"; -import { DEFAULT_LOCALE, resolveLocale } from "./locales"; +import { DEFAULT_LOCALE, SUPPORTED_LOCALES } from "./locales"; type LocaleTranslations = Awaited>; @@ -51,7 +52,12 @@ function activateLocale(locale: string): void { function applyLanguageSetting(): void { // Not desktopBridge.getSystemLocale(): that is the regional/time locale, not the UI language. - requestedLocale = resolveLocale(getClientSettings().language, navigator.languages); + requestedLocale = resolveLocale( + getClientSettings().language, + navigator.languages, + SUPPORTED_LOCALES, + DEFAULT_LOCALE, + ); void whenLocaleReady(); } diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 920fad80e4d17..7c5b8ef1cb27b 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -27,6 +27,10 @@ "types": "./src/composerModelMentions.ts", "default": "./src/composerModelMentions.ts" }, + "./locales": { + "types": "./src/locales.ts", + "default": "./src/locales.ts" + }, "./model-search": { "types": "./src/modelSearch.ts", "default": "./src/modelSearch.ts" diff --git a/packages/client-runtime/src/locales.ts b/packages/client-runtime/src/locales.ts new file mode 100644 index 0000000000000..74a0f0ff4fa0a --- /dev/null +++ b/packages/client-runtime/src/locales.ts @@ -0,0 +1,44 @@ +export const SYSTEM_LANGUAGE = "system"; + +// Shown in their own language so a user can find theirs from any UI language. +const NATIVE_LANGUAGE_NAMES: Readonly> = { + en: "English", + de: "Deutsch", + es: "Español", + fr: "Français", + ja: "日本語", + ko: "한국어", + "pt-BR": "Português (Brasil)", + ru: "Русский", + zh: "中文(简体)", +}; + +export function nativeLanguageName(locale: string): string { + return NATIVE_LANGUAGE_NAMES[locale] ?? locale; +} + +// Our `zh` is Simplified, so Traditional tags only match an exact locale. +const TRADITIONAL_CHINESE = /^zh[-_](hant|tw|hk|mo)\b/; + +function matchSupportedLocale(tag: string, supported: ReadonlyArray): string | undefined { + const normalized = tag.trim().toLowerCase(); + const language = normalized.split(/[-_]/)[0]; + const exact = supported.find((locale) => locale.toLowerCase() === normalized); + if (exact || TRADITIONAL_CHINESE.test(normalized)) return exact; + return supported.find((locale) => locale.toLowerCase() === language); +} + +/** Saved setting to active locale; "system" and unknown values follow the host's languages. */ +export function resolveLocale( + language: string, + systemLocales: ReadonlyArray, + supported: ReadonlyArray, + fallback: string, +): string { + if (supported.includes(language)) return language; + for (const tag of systemLocales) { + const match = matchSupportedLocale(tag, supported); + if (match) return match; + } + return fallback; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 35e9c290c86f7..671ee766f6aa5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -546,6 +546,15 @@ importers: '@expo/ui': specifier: 58.0.27 version: 58.0.27(@babel/core@7.29.7(supports-color@8.1.1))(expo@58.0.23)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + '@formatjs/intl-displaynames': + specifier: 6.8.13 + version: 6.8.13 + '@formatjs/intl-getcanonicallocales': + specifier: 2.5.6 + version: 2.5.6 + '@formatjs/intl-locale': + specifier: 4.2.13 + version: 4.2.13 '@legendapp/list': specifier: 3.7.2 version: 3.7.2(patch_hash=3c68607b8bb7a531873bcbe0b197d163ef1fdb4d4cf52a4ddf9d2b3804671658)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) @@ -720,6 +729,9 @@ importers: expo-widgets: specifier: 58.0.27 version: 58.0.27(patch_hash=8bf49067f93742855e15f29559ac75c8b50230b47069060993c9ea01dac11171)(@babel/core@7.29.7(supports-color@8.1.1))(expo@58.0.23)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)(supports-color@8.1.1))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + gt-react-native: + specifier: 11.4.18 + version: 11.4.18(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) pele: specifier: 'catalog:' version: 1.8.0 @@ -811,6 +823,9 @@ importers: babel-preset-expo: specifier: ~58.0.24 version: 58.0.24(@babel/core@7.29.7(supports-color@8.1.1))(@babel/runtime@7.29.7)(expo-widgets@58.0.27)(expo@58.0.23)(react-refresh@0.14.2)(supports-color@8.1.1) + gt: + specifier: 2.27.0 + version: 2.27.0(@babel/core@7.29.7(supports-color@8.1.1))(supports-color@8.1.1) jsdom: specifier: ^30.0.1 version: 30.1.0(@noble/hashes@1.8.0) @@ -4471,6 +4486,43 @@ packages: '@fontsource-variable/inter@5.3.0': resolution: {integrity: sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==} + '@formatjs/ecma402-abstract@2.3.6': + resolution: {integrity: sha512-HJnTFeRM2kVFVr5gr5kH1XP6K0JcJtE7Lzvtr3FS/so5f1kpsqqqxy5JF+FRaO6H2qmcMfAUIox7AJteieRtVw==} + + '@formatjs/fast-memoize@2.2.7': + resolution: {integrity: sha512-Yabmi9nSvyOMrlSeGGWDiH7rf3a7sIwplbvo/dlz9WCIjzIQAfy1RMf4S0X3yG724n5Ghu2GmEl5NJIV6O9sZQ==} + + '@formatjs/intl-datetimeformat@6.18.2': + resolution: {integrity: sha512-XXGJVOi/vmB+eLtYDs+ggDIvba/+VNmNrDZOtMyol5D0zl+zzuPps6W3TgDflpKfzg4memAEbLnA1wC6/TBSjQ==} + + '@formatjs/intl-displaynames@6.8.13': + resolution: {integrity: sha512-VbY7BdYJX5eURVKLk2grndUQtnbCLNbcJId/Sb/PsX7fWXiqWvg7qt/mecVHRzqoSEoGCQToKDxzpJj8RC0s3g==} + + '@formatjs/intl-enumerator@1.8.12': + resolution: {integrity: sha512-rT2hnyQ0q6RDG1jISMH+MP6wlHQLUC81C0BeYEzabJb48S4tU2HGCPUxsOqMa3vDAUmpnz9Kw5vYTD5hTkOVgg==} + deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. + + '@formatjs/intl-getcanonicallocales@2.5.6': + resolution: {integrity: sha512-CnBbc4St61RL06gDXlCZG08Gt41uiySgsdZNBExh8/c0FBONJCrAlQ9FsyalUdq9ze0nCeknJtMmO8JnB9xHgQ==} + + '@formatjs/intl-listformat@7.7.13': + resolution: {integrity: sha512-e1jk2w1H6VLy4kKoYyfBjvkw6IXE48AczF+7FIzWr5zB7VjdWQyrvs858t2WeQzHD8dRIxvIyX+qmeGql4jvng==} + + '@formatjs/intl-locale@4.2.13': + resolution: {integrity: sha512-Qcs0mP9JhEPCinPfpZ5JKzOa+VYDg94TQSFZozYuqG8R+hEGUTKyoyMqB5xi5QZT/hlB0CSgeNc/0fWMGtTFXA==} + + '@formatjs/intl-localematcher@0.6.2': + resolution: {integrity: sha512-XOMO2Hupl0wdd172Y06h6kLpBz6Dv+J4okPLl4LPtzbr8f66WbIoy4ev98EBuZ6ZK4h5ydTN6XneT4QVpD7cdA==} + + '@formatjs/intl-numberformat@8.15.6': + resolution: {integrity: sha512-htynTNKm5WOnbR521tNSMkWzX3yO6Z77qjOxvRujh5/A/UBKeoNElyuKCJltizdx3X33QNWQZC4aWjLKcccyeQ==} + + '@formatjs/intl-pluralrules@5.4.6': + resolution: {integrity: sha512-2HlOq+c7KsSps829SJ3B5987coX5mzKx9NbPcNwQ07eq8FBHgB3HfMoxt5HvLsdk4oQwCjAEnocbtd+wVwZ2Kg==} + + '@formatjs/intl-relativetimeformat@11.4.13': + resolution: {integrity: sha512-fNs6cpz9zIUEgTlE3kPSEyRfslxeMG19dT7sLz2C6U7Jxkx8xK/IH1ImZzCeqd6JlqE81O7uNW4oZTb1pz8lUw==} + '@generaltranslation/api@0.5.6': resolution: {integrity: sha512-rPcqH7BomEIRQKX6oyOagfqrfHddi3EcOkgWC/dgs2qSRhkoZYcpn68RWCr3ZFnmCMib7uDtSR9v8BjUI7AZLQ==} @@ -9706,6 +9758,12 @@ packages: gt-i18n@1.0.40: resolution: {integrity: sha512-EbDhYhtyUrZI4iBSWpe1AMRoYrmEn52/hnVG6NAqVhVvY85t15JCJWMdVOkDoB1TRVH9nbSzAttaYwcv0LF3KQ==} + gt-react-native@11.4.18: + resolution: {integrity: sha512-juASbGUn0R4fFZdr8qR7wovAXliH5RD3djZwkGL5x4ALp8/1J6fR1t8q0uF1Iq0GrsIcuE4oKjVgROCyMiXudA==} + peerDependencies: + react: '>=19.0.0' + react-native: '>=0.78.0' + gt-react@11.4.18: resolution: {integrity: sha512-c6T+oqvXdT2DSW6kXDc3HYj4MA9fR4B1VgSXaIVG8emAWhZ9Dih4npJBjRWBJNr1D3KrG0nU/+1FPxJ1Zzkhnw==} peerDependencies: @@ -15123,6 +15181,76 @@ snapshots: '@fontsource-variable/inter@5.3.0': {} + '@formatjs/ecma402-abstract@2.3.6': + dependencies: + '@formatjs/fast-memoize': 2.2.7 + '@formatjs/intl-localematcher': 0.6.2 + decimal.js: 10.6.0 + tslib: 2.8.1 + + '@formatjs/fast-memoize@2.2.7': + dependencies: + tslib: 2.8.1 + + '@formatjs/intl-datetimeformat@6.18.2': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + '@formatjs/intl-localematcher': 0.6.2 + decimal.js: 10.6.0 + tslib: 2.8.1 + + '@formatjs/intl-displaynames@6.8.13': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + '@formatjs/intl-localematcher': 0.6.2 + tslib: 2.8.1 + + '@formatjs/intl-enumerator@1.8.12': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + tslib: 2.8.1 + + '@formatjs/intl-getcanonicallocales@2.5.6': + dependencies: + tslib: 2.8.1 + + '@formatjs/intl-listformat@7.7.13': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + '@formatjs/intl-localematcher': 0.6.2 + tslib: 2.8.1 + + '@formatjs/intl-locale@4.2.13': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + '@formatjs/intl-enumerator': 1.8.12 + '@formatjs/intl-getcanonicallocales': 2.5.6 + tslib: 2.8.1 + + '@formatjs/intl-localematcher@0.6.2': + dependencies: + tslib: 2.8.1 + + '@formatjs/intl-numberformat@8.15.6': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + '@formatjs/intl-localematcher': 0.6.2 + decimal.js: 10.6.0 + tslib: 2.8.1 + + '@formatjs/intl-pluralrules@5.4.6': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + '@formatjs/intl-localematcher': 0.6.2 + decimal.js: 10.6.0 + tslib: 2.8.1 + + '@formatjs/intl-relativetimeformat@11.4.13': + dependencies: + '@formatjs/ecma402-abstract': 2.3.6 + '@formatjs/intl-localematcher': 0.6.2 + tslib: 2.8.1 + '@generaltranslation/api@0.5.6': {} '@generaltranslation/format@0.1.9': @@ -19863,6 +19991,24 @@ snapshots: '@generaltranslation/format': 0.1.9 generaltranslation: 9.5.9 + gt-react-native@11.4.18(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0): + dependencies: + '@formatjs/intl-datetimeformat': 6.18.2 + '@formatjs/intl-displaynames': 6.8.13 + '@formatjs/intl-getcanonicallocales': 2.5.6 + '@formatjs/intl-listformat': 7.7.13 + '@formatjs/intl-locale': 4.2.13 + '@formatjs/intl-numberformat': 8.15.6 + '@formatjs/intl-pluralrules': 5.4.6 + '@formatjs/intl-relativetimeformat': 11.4.13 + '@generaltranslation/format': 0.1.9 + '@generaltranslation/react-core': 11.4.18(react@19.3.0) + '@generaltranslation/supported-locales': 2.1.45 + generaltranslation: 9.5.9 + gt-i18n: 1.0.40 + react: 19.3.0 + react-native: 0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6) + gt-react@11.4.18(react-dom@19.3.0(react@19.3.0))(react@19.3.0): dependencies: '@generaltranslation/react-core': 11.4.18(react@19.3.0) From 9411a71ec0fab7fdedb4799b78402ec8a46e0d0e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:04:43 -0800 Subject: [PATCH 009/253] fix(web): dismissing the pull request checkout toast stops the handoff (#34509) --- .../usePullRequestActions.browser.test.tsx | 79 ++++++++++++++++++- .../pullRequest/usePullRequestActions.ts | 19 +++++ 2 files changed, 95 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx index 48e1f7412702a..018a5012fbf30 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx +++ b/apps/web/src/components/pullRequest/usePullRequestActions.browser.test.tsx @@ -1,15 +1,27 @@ -import { EnvironmentId, ProjectId, type PullRequestRef } from "@t3tools/contracts"; +import { EnvironmentId, ProjectId, ThreadId, type PullRequestRef } from "@t3tools/contracts"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; import { act, render } from "../../../test/render"; -import { usePullRequestActionRunner } from "./usePullRequestActions"; +import { useComposerDraftStore } from "~/composerDraftStore"; +import { ToastProvider } from "../ui/toast"; +import { usePullRequestActionRunner, usePullRequestHandoffs } from "./usePullRequestActions"; -const state = vi.hoisted(() => ({ runAction: vi.fn() })); +const state = vi.hoisted(() => ({ + runAction: vi.fn(), + newThread: vi.fn(), + prepareThread: vi.fn(), +})); vi.mock(import("~/state/use-atom-command"), () => ({ useAtomCommand: (() => state.runAction) as never, })); +vi.mock(import("~/hooks/useHandleNewThread"), () => ({ + useNewThreadHandler: (() => state.newThread) as never, +})); +vi.mock(import("~/state/sourceControlActions"), () => ({ + usePreparePullRequestThreadAction: (() => ({ run: state.prepareThread })) as never, +})); function deferred() { let resolve!: (value: T) => void; @@ -72,3 +84,64 @@ it("keeps pending merges with their pull request when navigating between threads }); await expect.element(button).toHaveTextContent("Merge"); }); + +function FixChecksButton() { + const { startHandoff } = usePullRequestHandoffs({ + environmentId: EnvironmentId.make("environment"), + detail: { + projectId: ProjectId.make("project"), + workspaceRoot: "/repo", + url: "https://github.com/owner/repo/pull/1", + }, + }); + return ( + + ); +} + +it("stops a pull request handoff when its loading toast is dismissed", async () => { + const prepared = deferred<{ + _tag: "Success"; + value: { + branch: string; + worktreePath: string; + isOnPullRequestHead: boolean; + pullRequest: { url: string }; + }; + }>(); + state.newThread + .mockReset() + .mockResolvedValueOnce({ draftId: "draft-1", threadId: ThreadId.make("thread-1") }) + .mockResolvedValueOnce({ draftId: "draft-2", threadId: ThreadId.make("thread-1") }); + state.prepareThread.mockReset().mockReturnValueOnce(prepared.promise); + await using screen = await render( + + + , + ); + + await userEvent.click(screen.getByRole("button", { name: "Fix" })); + const toast = screen.getByRole("dialog", { name: "Preparing the pull request checkout..." }); + await expect.element(toast).toBeVisible(); + await userEvent.click(toast.getByRole("button", { name: "Dismiss notification" })); + await expect.element(toast).not.toBeInTheDocument(); + await act(async () => { + prepared.resolve({ + _tag: "Success", + value: { + branch: "pr-1", + worktreePath: "/repo-worktrees/pr-1", + isOnPullRequestHead: true, + pullRequest: { url: "https://github.com/owner/repo/pull/1" }, + }, + }); + await prepared.promise; + }); + + expect(state.newThread).toHaveBeenCalledTimes(1); + expect(useComposerDraftStore.getState().getComposerDraft("draft-2" as never)?.prompt ?? "").toBe( + "", + ); +}); diff --git a/apps/web/src/components/pullRequest/usePullRequestActions.ts b/apps/web/src/components/pullRequest/usePullRequestActions.ts index 2cc81c4885364..63681b4cf2167 100644 --- a/apps/web/src/components/pullRequest/usePullRequestActions.ts +++ b/apps/web/src/components/pullRequest/usePullRequestActions.ts @@ -332,10 +332,17 @@ export function usePullRequestHandoffs({ ) => { if (!detail || handoff !== null) return; setHandoff(kind); + // Dismissing the loading toast cancels the handoff before it touches a draft. + let cancelled = false; // Explicit timeouts survive toast updates and would pin the result after loading. const toastId = toastManager.add({ type: "loading", title: `Preparing the ${terminology.singular} checkout...`, + data: { + onClose: () => { + cancelled = true; + }, + }, }); const projectRef = scopeProjectRef(environmentId, detail.projectId); // Checkout setup requires the thread to exist first. @@ -343,6 +350,10 @@ export function usePullRequestHandoffs({ (session) => session, () => null, ); + if (cancelled) { + setHandoff(null); + return; + } if (opened === null) { setHandoff(null); toastManager.update(toastId, { @@ -357,6 +368,10 @@ export function usePullRequestHandoffs({ mode, threadId: opened.threadId, }); + if (cancelled) { + setHandoff(null); + return; + } if (prepared._tag === "Failure") { setHandoff(null); toastManager.update(toastId, { @@ -376,6 +391,10 @@ export function usePullRequestHandoffs({ (session) => session, () => null, ); + if (cancelled) { + setHandoff(null); + return; + } if (pointed === null) { setHandoff(null); toastManager.update(toastId, { From f28dc8ee9486853733462a5589c61591ecb87279 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:05:23 -0800 Subject: [PATCH 010/253] fix(cursor): unified usage plans show one meter (#34506) --- .../src/server/usageLimits.test.ts | 15 +++++++++++++++ .../provider-cursor/src/server/usageLimits.ts | 15 +++++++++++++-- packages/shared/src/usageLimits.ts | 4 ++-- 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/packages/provider-cursor/src/server/usageLimits.test.ts b/packages/provider-cursor/src/server/usageLimits.test.ts index 0b54c7b5acefe..1d5b869f55b42 100644 --- a/packages/provider-cursor/src/server/usageLimits.test.ts +++ b/packages/provider-cursor/src/server/usageLimits.test.ts @@ -76,6 +76,21 @@ describe("Cursor usage limits", () => { } }); + it("shows a unified allowance once, not as a total plus a pool", () => { + // A unified plan reports only the total and the auto bucket, at the same value. + const windows = cursorUsageResponseToLimits( + { planUsage: { totalPercentUsed: 1.77, autoPercentUsed: 1.77 } }, + checkedAt, + ).windows; + expect(windows.map((window) => window.id)).toEqual(["autoPercentUsed"]); + expect( + cursorUsageResponseToLimits( + { planUsage: { totalPercentUsed: 100, apiPercentUsed: 100 } }, + checkedAt, + ).windows.map((window) => window.id), + ).toEqual(["apiPercentUsed", "totalPercentUsed"]); + }); + it("does not invent unused allowance for absent buckets", () => { expect(cursorUsageResponseToLimits({ planUsage: {} }, checkedAt).unavailable?.reason).toBe( "unsupported", diff --git a/packages/provider-cursor/src/server/usageLimits.ts b/packages/provider-cursor/src/server/usageLimits.ts index 48ab708554206..f663601f99b78 100644 --- a/packages/provider-cursor/src/server/usageLimits.ts +++ b/packages/provider-cursor/src/server/usageLimits.ts @@ -57,8 +57,19 @@ export function cursorUsageResponseToLimits( }); } } - return windows.length > 0 - ? makeUsageLimits({ checkedAt, windows }) + const total = windows.find((window) => window.id === "totalPercentUsed"); + const pools = windows.filter((window) => window !== total); + // Unified plans report their one allowance as both the total and the auto pool. Keep the pool: + // it pools with split-plan accounts, and exhaustedUsageWindow reads the pools. + const visibleWindows = + total && + pools.length === 1 && + pools[0]?.id === "autoPercentUsed" && + pools[0].usedPercent === total.usedPercent + ? pools + : windows; + return visibleWindows.length > 0 + ? makeUsageLimits({ checkedAt, windows: visibleWindows }) : makeUnavailableUsageLimits({ checkedAt, reason: "unsupported" }); } diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index a75d1fc88a4d5..1e7cac40b5f9c 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -127,12 +127,12 @@ export const CURSOR_USAGE_WINDOWS = [ { id: "totalPercentUsed", label: "Overall", - description: "Combined usage across both allowances, not a third quota.", + description: "All usage on your plan this billing cycle.", }, { id: "autoPercentUsed", label: "Cursor Models", - description: "Grok and Composer use this first. Auto can use either pool.", + description: "Grok, Composer, and Auto use this allowance.", }, { id: "apiPercentUsed", From 7271ea06a26af0c2ee64bba4f18c7fb3b7f22d5a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:05:29 -0800 Subject: [PATCH 011/253] fix(web): editing a queued message keeps its thread mention chips (#30889) --- .../components/chat/queuedMessageEdit.test.ts | 13 ++++ .../src/components/chat/queuedMessageEdit.ts | 3 +- .../chat/useQueuedRunEdit.browser.test.tsx | 77 +++++++++++++++++-- .../src/components/chat/useQueuedRunEdit.ts | 27 ++++++- 4 files changed, 108 insertions(+), 12 deletions(-) diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts index f7aed151f2fcc..c22b3983c8a6a 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.test.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { threadContextRecord } from "@t3tools/shared/composerContextReferences"; import { beforeEach, describe, expect, it } from "vite-plus/test"; import { DraftId, @@ -86,6 +87,18 @@ describe("queued message file edits", () => { expect(store.getComposerDraft(editTarget)).toBeNull(); }); + it("removes a kept edit draft that held a thread mention", () => { + const store = useComposerDraftStore.getState(); + store.setPrompt(editTarget, "Edited message"); + store.setThreadContexts(editTarget, [ + threadContextRecord(scopeThreadRef(environmentId, ThreadId.make("thread:other")), "Other"), + ]); + expect( + recoverQueuedMessageEdit({ editTarget, threadTarget, originalText: "Original message" }), + ).toBe("kept"); + expect(store.getComposerDraft(editTarget)).toBeNull(); + }); + it("reports a removed queued attachment as an edit when the run leaves", () => { const store = useComposerDraftStore.getState(); store.setPrompt(editTarget, "Original message"); diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts index 40a222a9f383a..ee7d954d3b4a4 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.ts @@ -28,9 +28,8 @@ export function recoverQueuedMessageEdit(input: { }); if (recovery === "kept") { store.moveComposerPromptAndImages(input.editTarget, input.threadTarget); - } else { - store.clearComposerContent(input.editTarget); } + store.clearComposerContent(input.editTarget); return recovery; } diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index 4a58d25e48757..0320dd6d6bb18 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -9,11 +9,20 @@ import { } from "@t3tools/contracts"; import { useImperativeHandle, type RefObject } from "react"; import { describe, expect, it, vi } from "vite-plus/test"; -import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences"; +import { + ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, + threadContextRecord, +} from "@t3tools/shared/composerContextReferences"; import { toastManager } from "../ui/toast"; import { act, render } from "../../../test/render"; import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore"; +import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { + environmentContextRecord, + environmentContextReference, + threadContextReference, +} from "../../lib/composerContextRecords"; import { deriveComposerSendState } from "../ChatView.logic"; import { ComposerPrimaryActions } from "./ComposerPrimaryActions"; import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry"; @@ -74,8 +83,8 @@ const RUN = RunId.make("run-1"); type HookResult = ReturnType; -function projection(runs: ReadonlyArray) { - return { runs, messages: [] } as unknown as ThreadStructure; +function projection(runs: ReadonlyArray, messages: ReadonlyArray) { + return { runs, messages } as unknown as ThreadStructure; } function setRuns(ref: ScopedThreadRef, status: string) { @@ -86,13 +95,14 @@ function Harness(props: { readonly threadRef: ScopedThreadRef; readonly runStatus: string; readonly hookRef: RefObject; + readonly messages: ReadonlyArray; }) { const result = useQueuedRunEdit({ environmentId: ENV, routeThreadRef: props.threadRef, threadDraftTarget: props.threadRef, activeThreadId: props.threadRef.threadId, - serverProjection: projection([{ id: RUN, status: props.runStatus }]), + serverProjection: projection([{ id: RUN, status: props.runStatus }], props.messages), promptRef: { current: "" }, composerRef: { current: null }, }); @@ -124,10 +134,15 @@ function Harness(props: { ) : null; } -function view(threadRef: ScopedThreadRef, runStatus: string, hook: { current: HookResult | null }) { +function view( + threadRef: ScopedThreadRef, + runStatus: string, + hook: { current: HookResult | null }, + messages: ReadonlyArray = [], +) { return ( - + ); } @@ -262,6 +277,56 @@ describe("useQueuedRunEdit", () => { ); }); + it("opens an edit with only the thread and machine records its text still mentions", async () => { + const { hook } = setup(); + const thread = threadContextRecord(THREAD_B, "Support Any File Uploads"); + const machine = environmentContextRecord(ENV, "Build box"); + const unreferenced = threadContextRecord(THREAD_A, "Removed earlier"); + const messageId = MessageId.make("message-1"); + const text = `wait for ${formatInlineContextReference(threadContextReference(thread))} on ${formatInlineContextReference(environmentContextReference(machine))}`; + const messages = [ + { id: messageId, text, context: { version: 1, records: [thread, machine, unreferenced] } }, + ]; + await using _screen = await render(view(THREAD_A, "queued", hook, messages)); + + await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] })); + + const draft = useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget); + expect(draft?.prompt).toBe(text); + expect(draft?.threadContexts).toEqual([thread]); + expect(draft?.environmentContexts).toEqual([machine]); + }); + + it("saves only the thread mentions still in the edited message", async () => { + const { hook } = setup(); + mocks.editQueuedRun.mockResolvedValue({ _tag: "Success" }); + const kept = threadContextRecord(THREAD_B, "Kept"); + const removed = threadContextRecord(THREAD_A, "Removed"); + const messageId = MessageId.make("message-1"); + const text = [kept, removed] + .map((record) => formatInlineContextReference(threadContextReference(record))) + .join(" and "); + const messages = [{ id: messageId, text, context: { version: 1, records: [kept, removed] } }]; + await using _screen = await render(view(THREAD_A, "queued", hook, messages)); + await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] })); + const target = requireHook(hook).draftTarget; + await act(() => useComposerDraftStore.getState().setThreadContexts(target, [kept])); + + const draft = useComposerDraftStore.getState().getComposerDraft(target); + await requireHook(hook).saveEdit( + { ...savedContent(draft?.prompt ?? ""), threadContexts: draft?.threadContexts ?? [] }, + () => {}, + ); + + expect(mocks.editQueuedRun).toHaveBeenCalledWith( + expect.objectContaining({ + input: expect.objectContaining({ + edit: expect.objectContaining({ context: { version: 1, records: [kept] } }), + }), + }), + ); + }); + it("keeps an open edit when the user leaves the thread and comes back", async () => { const { hook } = setup(); await using screen = await render(view(THREAD_A, "queued", hook)); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index 8feb302dc6aae..f8f968487fc75 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -7,6 +7,7 @@ import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, type ChatAttachment, + type ComposerContextRecord, type EnvironmentContextRecord, type EnvironmentId, type MessageId, @@ -40,6 +41,7 @@ import { startAttachmentUpload, } from "../../lib/attachmentUploadQueue"; import { buildMessageContext } from "../../lib/composerContextRecords"; +import { collectInlineContextIds } from "../../lib/composerContextReferences"; import { readFileAsDataUrl } from "../../lib/imageCompression"; import type { TerminalContextDraft } from "../../lib/terminalContext"; import type { ReviewCommentContext } from "../../reviewCommentContext"; @@ -85,6 +87,9 @@ interface QueuedRunEditContent { readonly environmentContexts: ReadonlyArray; } +const isDraftOwnedRecord = (record: ComposerContextRecord) => + record.kind === "thread" || record.kind === "environment"; + function queuedEditDraftTarget(routeThreadRef: ScopedThreadRef, runId: RunId) { return DraftId.make(`queued-edit:${scopedThreadKey(routeThreadRef)}:${runId}`); } @@ -127,10 +132,12 @@ async function submitQueuedRunEdit(input: { readImage: readFileAsDataUrl, uploadFiles, }); + // The edit draft owns thread and machine mentions, so a chip removed while editing is dropped. const keptRecords = (editing.context?.records ?? []).filter( (record) => - !("attachmentId" in record) || - editing.existingAttachments.some((attachment) => attachment.id === record.attachmentId), + !isDraftOwnedRecord(record) && + (!("attachmentId" in record) || + editing.existingAttachments.some((attachment) => attachment.id === record.attachmentId)), ); const newRecords = buildMessageContext({ @@ -233,9 +240,22 @@ export function useQueuedRunEdit(input: { if (editing !== null && editing.runId !== request.runId) clearEditDraft(editing.runId); const target = queuedEditDraftTarget(routeThreadRef, request.runId); const text = stripAttachmentOnlyBootstrapPrompt(request.text); + const context = serverProjection?.messages.find( + (message) => message.id === request.messageId, + )?.context; + const referenced = new Set(collectInlineContextIds(text)); + const records = (context?.records ?? []).filter((record) => referenced.has(record.contextId)); const store = useComposerDraftStore.getState(); store.clearComposerContent(target); store.setPrompt(target, text); + store.setThreadContexts( + target, + records.filter((record): record is ThreadContextRecord => record.kind === "thread"), + ); + store.setEnvironmentContexts( + target, + records.filter((record): record is EnvironmentContextRecord => record.kind === "environment"), + ); const threadRef = { environmentId, threadId: activeThreadId }; queuedRunEdits.begin( editKey, @@ -245,8 +265,7 @@ export function useQueuedRunEdit(input: { messageId: request.messageId, originalText: text, existingAttachments: request.attachments, - context: serverProjection?.messages.find((message) => message.id === request.messageId) - ?.context, + context, }, { runs: makeQueuedRunsAtom({ From 2ed69de64e25e1599cf1653096cc15719c8c3645 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:05:37 -0800 Subject: [PATCH 012/253] fix(desktop): browser snapshots work after relay reconnects (#24829) --- apps/desktop/src/preview/CdpRelay.test.ts | 46 ++++++++++++++++++- apps/desktop/src/preview/CdpRelay.ts | 10 ++++ .../src/preview/DesktopBrowserHost.test.ts | 3 ++ 3 files changed, 58 insertions(+), 1 deletion(-) diff --git a/apps/desktop/src/preview/CdpRelay.test.ts b/apps/desktop/src/preview/CdpRelay.test.ts index d409ad8b42e09..6e657ba5fc4d7 100644 --- a/apps/desktop/src/preview/CdpRelay.test.ts +++ b/apps/desktop/src/preview/CdpRelay.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it, vi } from "vite-plus/test"; -import { createCdpRelayConnection, type CdpRelayTarget } from "./CdpRelay.ts"; +import { + createCdpRelayConnection, + type CdpRelayConnection, + type CdpRelayTarget, +} from "./CdpRelay.ts"; const makeTarget = ( send: CdpRelayTarget["send"], @@ -354,3 +358,43 @@ describe("CDP relay payload budget", () => { expect(written.map((message) => message["method"])).toEqual([]); }); }); + +describe("CDP relay reconnects", () => { + it("reports the page's default execution context to every connection", async () => { + // Electron keeps one debugger attached, so Runtime stays enabled after a client drops, + // and the native Runtime.enable announces contexts again only after Runtime.disable. + let runtimeEnabled = false; + let current: CdpRelayConnection | undefined; + const context = { + context: { id: 1, origin: "null", name: "", auxData: { isDefault: true, frameId: "F" } }, + }; + const send = vi.fn(async (method: string) => { + if (method === "Runtime.disable") runtimeEnabled = false; + if (method === "Runtime.enable" && !runtimeEnabled) { + runtimeEnabled = true; + current!.event("Runtime.executionContextCreated", context, ""); + } + return {}; + }); + const connect = async () => { + const written: Array> = []; + current = makeRelay(makeTarget(send), (raw) => written.push(JSON.parse(raw))); + current.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} })); + await settle(); + current.receive( + JSON.stringify({ id: 2, method: "Runtime.enable", sessionId: "t3-preview-page" }), + ); + await settle(); + return written.filter((m) => m["method"] === "Runtime.executionContextCreated"); + }; + const expected = [ + { + method: "Runtime.executionContextCreated", + params: context, + sessionId: "t3-preview-page", + }, + ]; + expect(await connect()).toEqual(expected); + expect(await connect()).toEqual(expected); + }); +}); diff --git a/apps/desktop/src/preview/CdpRelay.ts b/apps/desktop/src/preview/CdpRelay.ts index 9a8e4e4c68346..94a78f47db686 100644 --- a/apps/desktop/src/preview/CdpRelay.ts +++ b/apps/desktop/src/preview/CdpRelay.ts @@ -188,6 +188,8 @@ export function createCdpRelayConnection( } }; + let runtimeReset: Promise | undefined; + const pageCommand = (command: CdpCommand): Promise => { const child = sessions.get(command.sessionId!) === "page" ? undefined : command.sessionId; const owner = @@ -198,6 +200,14 @@ export function createCdpRelayConnection( } // Playwright asks for this on every page; the host emulates focus only while it is in use. if (command.method === "Emulation.setFocusEmulationEnabled") return Promise.resolve({}); + // The shared debugger keeps Runtime enabled after an earlier connection, and a repeated + // enable reports no existing contexts; Playwright waits for them, so reset once per connection. + if (command.method === "Runtime.enable" && child === undefined) { + runtimeReset ??= target.send("Runtime.disable", {}, undefined, owner).catch(() => undefined); + return runtimeReset.then(() => + target.send(command.method, command.params ?? {}, undefined, owner), + ); + } return target.send(command.method, command.params ?? {}, child, owner); }; diff --git a/apps/desktop/src/preview/DesktopBrowserHost.test.ts b/apps/desktop/src/preview/DesktopBrowserHost.test.ts index a40450643215f..94809f0d10cfa 100644 --- a/apps/desktop/src/preview/DesktopBrowserHost.test.ts +++ b/apps/desktop/src/preview/DesktopBrowserHost.test.ts @@ -491,6 +491,9 @@ describe("DesktopBrowserHost", () => { // Playwright re-enabling a domain after a reload is not the agent using the tab. yield* command(host, 1, "Runtime.enable"); yield* settle; + // The relay resets Runtime before a connection's first enable: answer the disable, then the enable. + debuggee.release(); + yield* settle; debuggee.release(); yield* settle; yield* TestClock.adjust("1 minute"); From d749cfd8192e9b98dd9e764e00709d20049b40b5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:07:21 -0800 Subject: [PATCH 013/253] fix(server): skip Claude interrupts after session teardown (#25159) --- .../Adapters/ClaudeAdapterV2.test.ts | 75 ++++++++++++++++++- .../Adapters/ClaudeAdapterV2.ts | 17 ++++- 2 files changed, 89 insertions(+), 3 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 8048046a5927b..d2330829b096d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3333,7 +3333,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { const makeWakeHarnessWithOptions = (options?: { readonly close?: (sdkMessages: Queue.Queue) => Effect.Effect; - readonly interrupt?: Effect.Effect; + readonly interrupt?: Effect.Effect; readonly setPermissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["setPermissionMode"]; readonly applyFlagSettings?: ClaudeAdapterV2.ClaudeAgentSdkQuerySession["applyFlagSettings"]; readonly stopTask?: ( @@ -12031,6 +12031,79 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect.each([ + { teardown: "before Stop" as const }, + { teardown: "during Stop's interrupt write" as const }, + ])("Stop with session teardown $teardown does not fail on the closed CLI", ({ teardown }) => + Effect.gen(function* () { + const sessionScope = yield* Scope.make(); + let queryClosed = false; + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => + Effect.sync(() => { + queryClosed = true; + }).pipe(Effect.andThen(Queue.shutdown(sdkMessages))), + interrupt: Effect.suspend(() => + teardown === "before Stop" ? Effect.void : Scope.close(sessionScope, Exit.void), + ).pipe( + Effect.andThen( + Effect.suspend(() => + queryClosed + ? Effect.fail( + new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ + method: "interrupt", + cause: new Error("ProcessTransport is not ready for writing"), + }), + ) + : Effect.void, + ), + ), + ), + }).pipe(Scope.provide(sessionScope)); + const now = yield* DateTime.now; + const attemptId = RunAttemptId.make("attempt-claude-closed-scope-stop"); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId, + text: "Hand this thread off to a worktree.", + attachments: [], + }), + ); + // A workspace handoff detaches the session, closing its scope while the turn streams. + if (teardown === "before Stop") { + yield* Scope.close(sessionScope, Exit.void); + assert.isTrue(queryClosed); + } + + const interrupted = yield* Effect.exit( + harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + requestRuntimeRestart: true, + }), + ); + + assert.isTrue(Exit.isSuccess(interrupted), String(interrupted)); + assert.isTrue(queryClosed); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("a settled Stop leaves a turn that replaced the closing process alone", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index c0e456d603c01..7bdd80435a281 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -12063,8 +12063,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( next.add(turnInput.providerTurnId); return next; }); - yield* existing.query.interrupt.pipe(Effect.timeoutOption("10 seconds")); - yield* existing.query.close.pipe(Effect.ignore); + if (!(yield* Deferred.isDone(existing.closed))) { + yield* existing.query.interrupt.pipe( + Effect.timeoutOption("10 seconds"), + // Teardown can close the CLI between the check and the write. + Effect.catch((error) => + Deferred.isDone(existing.closed).pipe( + Effect.flatMap((closed) => (closed ? Effect.void : Effect.fail(error))), + ), + ), + ); + yield* existing.query.close.pipe(Effect.ignore); + } const closed = yield* Deferred.await(existing.closed).pipe( Effect.timeoutOption(CLAUDE_STOP_CONFIRM_TIMEOUT_MS), ); @@ -12307,6 +12317,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const closeSession = Effect.fnUntraced(function* () { const existing = yield* Ref.get(queryContext); if (existing !== null) { + // Marked first so a concurrent Stop skips or tolerates writes to the closing CLI; + // the scope interrupts the stream fiber, so it may never mark its query closed. + yield* Deferred.succeed(existing.closed, undefined); yield* existing.query.close.pipe(Effect.ignore); } yield* Effect.yieldNow; From cacdbb216316ab7cc91cb81c7ce1198f3a52e3d2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:07:28 -0800 Subject: [PATCH 014/253] fix(desktop): a maximized window reopens on the display it was last used on (#25833) --- apps/desktop/src/window/DesktopWindow.test.ts | 143 +++++++++++++++++- apps/desktop/src/window/DesktopWindow.ts | 104 ++++++++++--- 2 files changed, 225 insertions(+), 22 deletions(-) diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index bafcb4edab3f0..497b315ef5225 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -1023,11 +1023,75 @@ describe("DesktopWindow", () => { assert.deepEqual(mainWindowBoundsUpdates, [{ x: 220, y: 140, width: 1380, height: 920 }]); assert.deepEqual(mainWindowMaximizedUpdates, [true]); assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1); - assert.equal(fakeWindow.getBounds.mock.calls.length, 0); }).pipe(Effect.provide(layer)); }), ); + it.effect.each([ + { normal: "on display 1", width: 1920, height: 1080, x: 220 }, + { normal: "on display 1", width: 1280, height: 720, x: 220 }, + { normal: "straddling both displays", width: 1920, height: 1080, x: 1800 }, + ])( + "persists bounds on the display a maximized window was moved to ($width x $height, normal $normal)", + ({ width, height, x }) => + Effect.gen(function* () { + const displayOne = { x: 0, y: 0, width: 1920, height: 1080 }; + const displayTwo = { x: 1920, y: 0, width, height }; + const getAllDisplays = vi.mocked(Electron.screen.getAllDisplays); + getAllDisplays.mockReturnValue([ + { bounds: displayOne, workArea: displayOne }, + { bounds: displayTwo, workArea: displayTwo }, + ] as unknown as Electron.Display[]); + const fakeWindow = makeFakeBrowserWindow(); + fakeWindow.isMaximized.mockReturnValue(true); + fakeWindow.getBounds.mockReturnValue(displayTwo); + fakeWindow.getNormalBounds.mockReturnValue({ x, y: 140, width: 1380, height: 920 }); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; + const mainWindowMaximizedUpdates: boolean[] = []; + const layer = layerTest({ + window: fakeWindow.window, + createCount, + mainWindow, + mainWindowBoundsUpdates, + mainWindowMaximizedUpdates, + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const move = fakeWindow.windowListeners.get("move"); + if (!move) { + return yield* Effect.die("window move listener was not registered"); + } + move(); + yield* TestClock.adjust(500); + yield* Effect.promise(() => Promise.resolve()); + + const persisted = mainWindowBoundsUpdates.at(-1); + assert.isDefined(persisted, "maximized window bounds were not persisted"); + const persistedDisplay = [displayOne, displayTwo].findIndex( + (display) => + persisted.x >= display.x && + persisted.y >= display.y && + persisted.x + persisted.width <= display.x + display.width && + persisted.y + persisted.height <= display.y + display.height, + ); + assert.equal( + persistedDisplay, + 1, + `window maximized on display 2 persisted bounds ${JSON.stringify(persisted)}, which restore on display ${persistedDisplay + 1}`, + ); + assert.deepEqual(mainWindowMaximizedUpdates, [true]); + }).pipe( + Effect.provide(layer), + Effect.ensuring(Effect.sync(() => getAllDisplays.mockReset())), + ); + }), + ); + it.effect("preserves unrestorable bounds until the user changes the window", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); @@ -1071,8 +1135,7 @@ describe("DesktopWindow", () => { it.effect("flushes normal bounds when minimized before the debounce completes", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); - fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 }); - fakeWindow.getNormalBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 }); + fakeWindow.getBounds.mockReturnValue({ x: 180, y: 120, width: 1440, height: 960 }); const createCount = yield* Ref.make(0); const mainWindow = yield* Ref.make>(Option.none()); const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; @@ -1093,17 +1156,87 @@ describe("DesktopWindow", () => { } resize(); yield* TestClock.adjust(250); + // Windows reports a minimized window at -32000. fakeWindow.isMinimized.mockReturnValue(true); + fakeWindow.getBounds.mockReturnValue({ x: -32_000, y: -32_000, width: 160, height: 28 }); yield* desktopWindow.flushMainWindowBounds; + resize(); + yield* TestClock.adjust(500); + yield* Effect.promise(() => Promise.resolve()); assert.deepEqual(mainWindowBoundsUpdates, [{ x: 180, y: 120, width: 1440, height: 960 }]); - assert.equal(fakeWindow.getBounds.mock.calls.length, 0); - assert.equal(fakeWindow.getNormalBounds.mock.calls.length, 1); }).pipe(Effect.provide(layer)); }), ); + it.effect.each([ + { window: "normal", write: "flush" }, + { window: "normal", write: "debounce" }, + { window: "maximized", write: "flush" }, + { window: "maximized", write: "debounce" }, + ] as const)("persists a $window window change minimized before its $write", (input) => + Effect.gen(function* () { + const displayOne = { x: 0, y: 0, width: 1920, height: 1080 }; + const displayTwo = { x: 1920, y: 0, width: 1920, height: 1080 }; + const getAllDisplays = vi.mocked(Electron.screen.getAllDisplays); + getAllDisplays.mockReturnValue([ + { bounds: displayOne, workArea: displayOne }, + { bounds: displayTwo, workArea: displayTwo }, + ] as unknown as Electron.Display[]); + const maximized = input.window === "maximized"; + const fakeWindow = makeFakeBrowserWindow(); + fakeWindow.isMaximized.mockReturnValue(maximized); + fakeWindow.getBounds.mockReturnValue( + maximized ? displayTwo : { x: 220, y: 140, width: 1380, height: 920 }, + ); + fakeWindow.getNormalBounds.mockReturnValue({ x: 220, y: 140, width: 1380, height: 920 }); + const createCount = yield* Ref.make(0); + const mainWindow = yield* Ref.make>(Option.none()); + const mainWindowBoundsUpdates: DesktopAppSettings.DesktopWindowBounds[] = []; + const mainWindowMaximizedUpdates: boolean[] = []; + const layer = layerTest({ + window: fakeWindow.window, + createCount, + mainWindow, + mainWindowBoundsUpdates, + mainWindowMaximizedUpdates, + }); + + yield* Effect.gen(function* () { + const desktopWindow = yield* DesktopWindow.DesktopWindow; + yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773")); + + const move = fakeWindow.windowListeners.get("move"); + if (!move) { + return yield* Effect.die("window move listener was not registered"); + } + move(); + yield* TestClock.adjust(250); + // Minimized windows report stale state: macOS unmaximized at the pre-move frame. + fakeWindow.isMinimized.mockReturnValue(true); + fakeWindow.isMaximized.mockReturnValue(false); + fakeWindow.getBounds.mockReturnValue({ x: 100, y: 100, width: 1100, height: 780 }); + fakeWindow.getNormalBounds.mockReturnValue({ x: 100, y: 100, width: 1100, height: 780 }); + if (input.write === "debounce") { + yield* TestClock.adjust(250); + yield* Effect.promise(() => Promise.resolve()); + } + yield* desktopWindow.flushMainWindowBounds; + + assert.deepEqual(mainWindowBoundsUpdates, [ + maximized + ? { x: 2140, y: 140, width: 1380, height: 920 } + : { x: 220, y: 140, width: 1380, height: 920 }, + ]); + assert.deepEqual(mainWindowMaximizedUpdates, [maximized]); + }).pipe( + Effect.provide(layer), + Effect.ensuring(Effect.sync(() => getAllDisplays.mockReset())), + ); + }), + ); + it.effect("maps macOS horizontal swipes to available history navigation", () => Effect.gen(function* () { const fakeWindow = makeFakeBrowserWindow(); diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 1dfc758c052bc..43404e2d6cfb9 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -183,6 +183,58 @@ function windowFitsWithinDisplay( ); } +function overlapArea(left: DisplayBounds, right: DisplayBounds): number { + const width = Math.min(left.x + left.width, right.x + right.width) - Math.max(left.x, right.x); + const height = Math.min(left.y + left.height, right.y + right.height) - Math.max(left.y, right.y); + return width > 0 && height > 0 ? width * height : 0; +} + +function displayMatching( + bounds: DisplayBounds, + displays: readonly DisplayBounds[], +): DisplayBounds | undefined { + let match: DisplayBounds | undefined; + let matchArea = 0; + for (const display of displays) { + const area = overlapArea(bounds, display); + if (area > matchArea) { + match = display; + matchArea = area; + } + } + return match; +} + +// Normal bounds of a maximized window can sit on, or straddle into, another display than the window. +function normalBoundsOnWindowDisplay( + normalBounds: DisplayBounds, + windowBounds: DisplayBounds, + displays: readonly DisplayBounds[], +): DisplayBounds { + const target = displayMatching(windowBounds, displays); + if (target === undefined || windowFitsWithinDisplay(normalBounds, target)) { + return normalBounds; + } + const source = displayMatching(normalBounds, displays) ?? target; + const width = Math.min(normalBounds.width, target.width); + const height = Math.min(normalBounds.height, target.height); + const clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max); + return { + x: clamp(target.x + normalBounds.x - source.x, target.x, target.x + target.width - width), + y: clamp(target.y + normalBounds.y - source.y, target.y, target.y + target.height - height), + width, + height, + }; +} + +function readDisplayBoundsOrEmpty(): readonly DisplayBounds[] { + try { + return Electron.screen.getAllDisplays().map((display) => display.bounds); + } catch { + return []; + } +} + function windowBoundsEqual( left: DesktopAppSettings.DesktopWindowBounds, right: DesktopAppSettings.DesktopWindowBounds, @@ -458,33 +510,52 @@ export const make = Effect.gen(function* () { let boundsPersistFiber: Fiber.Fiber | undefined; let pendingBoundsPersistFiber: Fiber.Fiber | undefined; let boundsPersistenceEnabled = persistedBounds === null || restoredPersistedBounds; - const readPersistableBounds = (): DesktopAppSettings.DesktopWindowBounds | null => { + let lastPersistableState: { + readonly bounds: DesktopAppSettings.DesktopWindowBounds; + readonly isMaximized: boolean; + } | null = null; + const readPersistableState = () => { if (window.isDestroyed()) { return null; } + // Minimized windows report stale state on some platforms (macOS: not maximized, the + // pre-move normal frame; Windows: -32000), so they keep the state seen before minimizing. + if (window.isMinimized()) { + return lastPersistableState; + } + const isMaximized = window.isMaximized(); const bounds = - window.isFullScreen() || window.isMaximized() || window.isMinimized() - ? window.getNormalBounds() + window.isFullScreen() || isMaximized + ? normalBoundsOnWindowDisplay( + window.getNormalBounds(), + window.getBounds(), + readDisplayBoundsOrEmpty(), + ) : window.getBounds(); - return DesktopAppSettings.normalizeMainWindowBounds({ + const persistableBounds = DesktopAppSettings.normalizeMainWindowBounds({ x: Math.round(bounds.x), y: Math.round(bounds.y), width: Math.round(bounds.width), height: Math.round(bounds.height), }); + lastPersistableState = + persistableBounds === null ? null : { bounds: persistableBounds, isMaximized }; + return lastPersistableState; }; - const fallbackWindowBounds = boundsPersistenceEnabled ? null : readPersistableBounds(); + const fallbackWindowBounds = boundsPersistenceEnabled + ? null + : (readPersistableState()?.bounds ?? null); const fallbackWindowMaximized = persistedSettings.mainWindowMaximized; const persistCurrentBounds = (): Fiber.Fiber | undefined => { if (!boundsPersistenceEnabled) { return pendingBoundsPersistFiber; } - const bounds = readPersistableBounds(); - if (bounds === null) { + const state = readPersistableState(); + if (state === null) { return pendingBoundsPersistFiber; } pendingBoundsPersistFiber = runFork( - desktopSettings.setMainWindowBounds(bounds, window.isMaximized()).pipe( + desktopSettings.setMainWindowBounds(state.bounds, state.isMaximized).pipe( Effect.asVoid, Effect.catch((error) => logWindowWarning("failed to persist main window bounds", { @@ -496,16 +567,15 @@ export const make = Effect.gen(function* () { return pendingBoundsPersistFiber; }; const scheduleBoundsPersist = () => { - if (!boundsPersistenceEnabled) { - const currentBounds = readPersistableBounds(); - if ( - currentBounds === null || + const state = readPersistableState(); + if ( + !boundsPersistenceEnabled && + (state === null || (fallbackWindowBounds !== null && - windowBoundsEqual(currentBounds, fallbackWindowBounds) && - window.isMaximized() === fallbackWindowMaximized) - ) { - return; - } + windowBoundsEqual(state.bounds, fallbackWindowBounds) && + state.isMaximized === fallbackWindowMaximized)) + ) { + return; } boundsPersistenceEnabled = true; if (boundsPersistFiber !== undefined) { From 67d7de8aa232135bfedd6adee789598bdd76cf59 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:08:39 -0800 Subject: [PATCH 015/253] fix(provider-core): bun-global updates only offer versions bun will install (#30641) --- .../src/server/maintenanceResolver.test.ts | 77 +++++++++++++++++++ .../src/server/maintenanceResolver.ts | 35 +++++++++ 2 files changed, 112 insertions(+) diff --git a/packages/provider-core/src/server/maintenanceResolver.test.ts b/packages/provider-core/src/server/maintenanceResolver.test.ts index 72374ef18dba0..556f5ce318f16 100644 --- a/packages/provider-core/src/server/maintenanceResolver.test.ts +++ b/packages/provider-core/src/server/maintenanceResolver.test.ts @@ -66,6 +66,14 @@ const nativePackageToolUpdate = makePackageManagedProviderMaintenanceResolver({ isCommandPath: isNativeTestCommandPath("/.local/bin/native-package-tool"), }, }); +const bunOutdatedTable = (row: string) => [ + "|-------------------------------------------------------|", + "| Package | Current | Update | Latest |", + "|-----------------------|---------|--------|----------|", + row, + "|-------------------------------------------------------|", + "Note: The * indicates that version isn't true latest due to minimum release age", +]; const miseToolUpdate = makePackageManagedProviderMaintenanceResolver({ provider: driver("packageTool"), npmPackageName: "@example/package-tool", @@ -1267,6 +1275,75 @@ it.layer( { skip: !symlinksSupported || windowsHost }, ); + it.effect.each([ + { + case: "the eligible release under minimumReleaseAge", + row: "| @example/package-tool | 1.0.0 | 1.0.0 | 1.1.0 * |", + expected: "1.1.0", + }, + { + case: "no update when the installed version is the eligible release", + row: "| @example/package-tool | 1.0.0 | 1.0.0 * | 1.0.0 * |", + expected: "1.0.0", + }, + { + // bun prints only its banner both when nothing is outdated and when the registry fails. + case: "the npm fallback when bun reports no row", + row: null, + expected: "1.2.0", + }, + ])( + "advertises $case for bun-global installs", + (fixture) => + Effect.gen(function* () { + const tempDir = yield* makeTempDir("t3-bun-latest"); + const bunBinDir = NodePath.join(tempDir, ".bun", "bin"); + writeExecutable(NodePath.join(bunBinDir, "bun")); + writeExecutable(NodePath.join(bunBinDir, "package-tool")); + const outdated = [ + "bun outdated v1.3.3 (274e01c7)", + ...(fixture.row === null ? [] : bunOutdatedTable(fixture.row)), + "", + ].join("\n"); + + const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect( + packageToolUpdate, + { binaryPath: "package-tool", env: { PATH: bunBinDir } }, + ).pipe( + Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Environment, { PATH: "" }), + Effect.provideService( + ChildProcessSpawner.ChildProcessSpawner, + stdoutSpawner((_command, args) => + args[0] === "outdated" + ? outdated + : `${tempDir} node_modules (1)\n└── @example/package-tool@1.0.0\n`, + ), + ), + ); + + const provider = yield* enrichProviderSnapshotWithVersionAdvisory( + installedPackageToolProvider, + capabilities, + ).pipe( + Effect.provideServiceEffect( + ProviderLatestVersions.ProviderLatestVersions, + ProviderLatestVersions.make([["@example/package-tool", "1.2.0"]]), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("the npm version is already cached")), + ), + ); + expect(provider.versionAdvisory).toMatchObject({ + status: fixture.expected === "1.0.0" ? "current" : "behind_latest", + currentVersion: "1.0.0", + latestVersion: fixture.expected, + }); + }), + { skip: windowsHost }, + ); + it.effect.skipIf(windowsHost)( "switches to bun updates when the resolved binary lives in bun's global bin", () => diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts index da97fb26d28c6..69251a299cf44 100644 --- a/packages/provider-core/src/server/maintenanceResolver.ts +++ b/packages/provider-core/src/server/maintenanceResolver.ts @@ -482,6 +482,37 @@ const resolvePnpmGlobalLatestVersion = Effect.fn("resolvePnpmGlobalLatestVersion return nonEmptyString(listedEntries?.[0]?.dependencies?.[packageName]?.version); }); +// `bun outdated` has no JSON output; its `Latest` column is what `@latest` installs +// under minimumReleaseAge (marked `*`). `Update` is only the global package.json range. +function parseBunOutdatedLatestVersion(output: string, packageName: string): string | null { + for (const line of output.split("\n")) { + const cells = line.split("|").map((cell) => cell.trim()); + if (cells.length === 6 && cells[1] === packageName) { + return nonEmptyString(cells[4]?.replace(/ \*$/, "")); + } + } + return null; +} + +// bun rejects an exact pin to a release inside minimumReleaseAge, so the update stays `@latest`. +const resolveBunGlobalLatestVersion = Effect.fn("resolveBunGlobalLatestVersion")(function* ( + packageName: string, + env: NodeJS.ProcessEnv, +) { + // Match the updater's bun and environment. + const bunPath = yield* resolveCommandPath("bun", { + env: { ...(yield* HostProcess.Environment), ...env }, + }); + if (!bunPath) return null; + // FORCE_COLOR=1 draws the table with box characters and splits versions with ANSI codes. + const outdated = yield* runProbe(bunPath, ["outdated", "-g", packageName], { + ...env, + FORCE_COLOR: "0", + }); + // A missing row reads the same whether bun is current or its registry failed, so npm decides. + return outdated ? parseBunOutdatedLatestVersion(outdated, packageName) : null; +}); + const MiseInstall = Schema.Struct({ install_path: Schema.String, requested_version: Schema.optional(Schema.NullOr(Schema.String)), @@ -723,6 +754,7 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( }); } if (commandPaths.some(isBunGlobalCommandPath)) { + const services = yield* Effect.context(); return makeProviderMaintenanceCapabilities({ provider: definition.provider, packageName, @@ -730,6 +762,9 @@ export const resolvePackageManagedProviderMaintenance = Effect.fn( updateArgs: ["i", "-g", `${packageName}@latest`], updateLockKey: "bun-global", env: context.env, + lookupLatestVersion: resolveBunGlobalLatestVersion(packageName, context.env).pipe( + Effect.provideContext(services), + ), }); } if (commandPaths.some(isPnpmGlobalCommandPath)) { From d21daa78e043c14cf70b6a8e93e21104b1a2470c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:09:14 -0800 Subject: [PATCH 016/253] fix(cli): t3 thread finds the project from inside its git worktrees (#30802) --- apps/server/src/cli/thread.test.ts | 68 ++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 85 +++++++++++++++++++++++++----- docs/user/outside-agents.md | 10 ++-- 3 files changed, 145 insertions(+), 18 deletions(-) diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index f182f708c4cfa..42a4a3e5c8455 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -10,6 +10,7 @@ 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 { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as TestConsole from "effect/testing/TestConsole"; import { Command } from "effect/cli"; import { vi } from "vite-plus/test"; @@ -21,6 +22,7 @@ import { } from "../serverRuntimeState.ts"; import { readLatestMessages, + resolveProject, threadCommand, type ThreadTools, titleFromMessage, @@ -292,3 +294,69 @@ it("titles from a long first line without splitting an emoji", () => { const title = titleFromMessage(`${"a".repeat(78)}😀 and the rest of a long first line`); assert.strictEqual(title, `${"a".repeat(78)}…`); }); + +const git = Effect.fn("test.git")(function* (cwd: string, args: ReadonlyArray) { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const exitCode = yield* spawner.exitCode(ChildProcess.make("git", args, { cwd })); + assert.strictEqual(Number(exitCode), 0, `git ${args.join(" ")}`); +}); + +const commitAll = (cwd: string) => + Effect.andThen( + git(cwd, ["add", "."]), + git(cwd, [ + "-c", + "user.name=Test", + "-c", + "user.email=test@example.test", + "commit", + "--quiet", + "-m", + "initial", + ]), + ); + +it.live("resolves a path inside a git worktree of the project's repository to that project", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-thread-worktree-" }); + const repo = path.join(root, "sample"); + const worktree = path.join(root, "worktrees", "sample", "t3-8ff64c24"); + const feature = path.join(root, "wt", "feature"); + const featureWorktree = path.join(root, "worktrees", "feature", "t3-1a2b3c4d"); + yield* fileSystem.makeDirectory(path.join(repo, "pkg"), { recursive: true }); + yield* fileSystem.writeFileString(path.join(repo, "pkg", "index.ts"), "export {};\n"); + yield* git(repo, ["init", "--quiet", "-b", "main"]); + yield* commitAll(repo); + yield* git(repo, ["worktree", "add", "--quiet", "-b", "t3/8ff64c24", worktree]); + yield* git(repo, ["worktree", "add", "--quiet", "-b", "feature", feature]); + yield* git(feature, ["worktree", "add", "--quiet", "-b", "t3/1a2b3c4d", featureWorktree]); + + const project = (id: string, workspaceRoot: string) => ({ + id: ProjectId.make(id), + title: path.basename(workspaceRoot), + workspaceRoot, + }); + const sample = project("project-sample", repo); + const featureProject = project("project-feature", feature); + const resolveFrom = ( + projects: ReadonlyArray>, + workingDirectory: string, + identifier = ".", + ) => + resolveProject( + scriptedTools({ t3_project_list: [{ projects, nextCursor: null }] }).tools, + identifier, + ).pipe(Effect.provideService(HostProcess.WorkingDirectory, workingDirectory)); + + assert.deepStrictEqual(yield* resolveFrom([sample], worktree), sample); + assert.deepStrictEqual(yield* resolveFrom([sample], path.join(worktree, "pkg")), sample); + assert.deepStrictEqual(yield* resolveFrom([sample], worktree, "pkg/index.ts"), sample); + assert.deepStrictEqual(yield* resolveFrom([featureProject], featureWorktree), featureProject); + const ambiguous = yield* Effect.flip(resolveFrom([sample, featureProject], featureWorktree)); + assert.strictEqual(ambiguous._tag, "ThreadUsageError"); + assert.include(ambiguous.message, "sample (project-sample)"); + assert.include(ambiguous.message, "feature (project-feature)"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 80dfad018e158..b71d65058301f 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -30,6 +30,7 @@ import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts"; import * as ServerConfig from "../config.ts"; import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts"; import { expandHomePath } from "../os-jank.ts"; +import * as ProcessRunner from "../processRunner.ts"; import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; @@ -273,8 +274,34 @@ const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools return projects; }); -/** A project id, or a path inside a project's folder (deepest project wins). */ -const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( +/** The checkouts of the git repository at `directory`, or none outside a repository. */ +const listGitCheckouts = Effect.fn("cli.thread.listGitCheckouts")(function* (directory: string) { + const processRunner = yield* ProcessRunner.ProcessRunner; + const list = (args: ReadonlyArray) => + processRunner + .run({ command: "git", args: ["worktree", "list", "--porcelain", ...args], cwd: directory }) + .pipe( + Effect.option, + Effect.map((result) => + Option.isSome(result) && result.value.code === 0 ? result.value.stdout : undefined, + ), + ); + // Pre-2.36 Git rejects worktree list -z; normalize its line output to NUL records. + const stdout = (yield* list(["-z"])) ?? (yield* list([]))?.replaceAll("\n", "\0") ?? ""; + return stdout.split("\0\0").flatMap((record) => { + const [first = "", ...attributes] = record.split("\0"); + return first.startsWith("worktree ") && !attributes.includes("bare") + ? [first.slice("worktree ".length)] + : []; + }); +}); + +/** + * A project id, or a path inside a project's folder (deepest project wins). + * A path inside a git worktree resolves as the same path in the repository's + * other checkouts. + */ +export const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( tools: ThreadTools, identifier: string, ) { @@ -294,19 +321,51 @@ const resolveProject = Effect.fn("cli.thread.resolveProject")(function* ( const roots = yield* Effect.forEach(projects, (project) => Effect.map(realPath(project.workspaceRoot), (root) => ({ project, root })), ); - const containing = roots - .filter(({ root }) => { - const relative = path.relative(root, target); - return ( - relative === "" || - (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) - ); - }) - .toSorted((left, right) => right.root.length - left.root.length)[0]; - if (containing === undefined) { + const contains = (root: string, candidate: string) => { + const relative = path.relative(root, candidate); + return ( + relative === "" || + (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) + ); + }; + const deepestContaining = (candidate: string) => + roots + .filter(({ root }) => contains(root, candidate)) + .toSorted((left, right) => right.root.length - left.root.length)[0]?.project; + + const containing = deepestContaining(target); + if (containing !== undefined) return containing; + const targetInfo = yield* fileSystem.stat(target).pipe(Effect.option); + const gitDirectory = + Option.isSome(targetInfo) && targetInfo.value.type === "File" ? path.dirname(target) : target; + const listed = yield* listGitCheckouts(gitDirectory).pipe( + Effect.flatMap((paths) => Effect.forEach(paths, realPath)), + Effect.provide(ProcessRunner.layer), + ); + const ownCheckout = listed + .filter((checkout) => contains(checkout, target)) + .toSorted((left, right) => right.length - left.length)[0]; + if (ownCheckout === undefined) { + return yield* new ThreadProjectNotFoundError({ identifier }); + } + const relative = path.relative(ownCheckout, target); + const matches = new Map(); + for (const checkout of listed) { + if (checkout === ownCheckout) continue; + const project = deepestContaining(path.join(checkout, relative)); + if (project !== undefined) matches.set(project.id, project); + } + const [match, ...others] = matches.values(); + if (match === undefined) { return yield* new ThreadProjectNotFoundError({ identifier }); } - return containing.project; + if (others.length > 0) { + const names = [match, ...others].map((project) => `${project.title} (${project.id})`); + return yield* new ThreadUsageError({ + detail: `'${identifier}' is in a git worktree shared by several projects: ${names.join(", ")}. Pass a project id instead.`, + }); + } + return match; }); /** Every item on a timeline view, oldest first. */ diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index dc9af3ad5167c..84d00cc98b16c 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -147,11 +147,11 @@ t3 thread show "$id" t3 thread list ``` -`.` means the project that contains the current folder; a project id also -works. A new thread uses the project's default model and permission mode, and -runs in the project folder unless you pass `--worktree `. `send` -never interrupts: a busy thread gets the message as its next turn. Pass `-` as -the message to read it from stdin. +`.` means the project that contains the current folder, or a git worktree of +its repository; a project id also works. A new thread uses the project's +default model and permission mode, and runs in the project folder unless you +pass `--worktree `. `send` never interrupts: a busy thread gets +the message as its next turn. Pass `-` as the message to read it from stdin. `--wait` prints the agent's reply. It exits 1 when the run fails or stops, and 2 when the agent waits for an answer you give in the app. Add `--json` for a From 8af1fc110e909a13a26a7c31b6f91e2a1f421a46 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:09:20 -0800 Subject: [PATCH 017/253] fix(dev): import seed snapshots with peer preview migrations (#25058) --- apps/server/scripts/migrate-dev-db.test.ts | 77 ++++++++++++++++++++-- apps/server/scripts/migrate-dev-db.ts | 28 ++++++++ 2 files changed, 100 insertions(+), 5 deletions(-) diff --git a/apps/server/scripts/migrate-dev-db.test.ts b/apps/server/scripts/migrate-dev-db.test.ts index b944bfcb42ef1..6898eff9ccbf0 100644 --- a/apps/server/scripts/migrate-dev-db.test.ts +++ b/apps/server/scripts/migrate-dev-db.test.ts @@ -14,8 +14,14 @@ const withDatabase = ( effect: Effect.Effect, ) => effect.pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath }))); +const insertPeerLink = (sql: SqlClient.SqlClient) => sql`INSERT INTO peer_environment_links + (environment_id, secret_name, label, urls_json, access, linked_at, expires_at) + VALUES ('environment-box', 'peer-link-box', 'Box', '["https://box.example"]', 'auto', + '2026-08-01', '2027-08-01')`; + const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(function* ( baseDir: string, + toMigrationInclusive?: number, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -26,7 +32,7 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio databasePath, Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; - yield* runMigrations(); + yield* runMigrations({ toMigrationInclusive }); yield* sql`INSERT INTO projection_projects (project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at) @@ -120,10 +126,7 @@ const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(functio VALUES ('delivery-1', 'task-1', 'key-1', 1900000000000, '{}', '{}', '[]')`; yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at) VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`; - yield* sql`INSERT INTO peer_environment_links - (environment_id, secret_name, label, urls_json, access, linked_at, expires_at) - VALUES ('environment-box', 'peer-link-box', 'Box', '["https://box.example"]', 'auto', - '2026-08-01', '2027-08-01')`; + if (toMigrationInclusive === undefined) yield* insertPeerLink(sql); }), ); return databasePath; @@ -355,6 +358,70 @@ it.layer(NodeServices.layer)("migrate-dev-db", (it) => { }), ); + it.effect("imports a dev seed whose ids after 67 came from the peer links branch", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-peer-" }); + const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-peer-dest-" }); + const source = yield* createFixtureSource(sourceDir, 67); + // Mirrors a real ~/.t3 seed written by a build whose 68-70 differ from main's. + yield* withDatabase( + source, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE peer_environment_links ( + environment_id TEXT PRIMARY KEY, + secret_name TEXT NOT NULL, + label TEXT NOT NULL, + urls_json TEXT NOT NULL, + access TEXT NOT NULL, + linked_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + last_reached_at TEXT, + last_error TEXT, + fenced INTEGER NOT NULL DEFAULT 0)`; + yield* sql`CREATE INDEX orchestration_v2_projection_turn_items_waiting_link_idx + ON orchestration_v2_projection_turn_items(thread_id, updated_at DESC, turn_item_id DESC) + WHERE type = 'link_request' AND status = 'waiting'`; + yield* insertPeerLink(sql); + yield* sql`INSERT INTO effect_sql_migrations (migration_id, name) VALUES + (68, 'PeerLinks'), (69, 'PeerLinkFence'), (70, 'WaitingLinkRequestIndex')`; + }), + ); + + const result = yield* runMigrateDevDb( + { baseDir: destDir, source, projects: 5, threadsPerProject: 2 }, + { sharedHome: sourceDir }, + ); + + const imported = yield* withDatabase( + result.databasePath, + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const threads = yield* sql<{ thread_id: string }>` + SELECT thread_id FROM orchestration_v2_projection_threads ORDER BY thread_id`; + const schema = yield* sql<{ name: string }>` + SELECT name FROM sqlite_master WHERE name IN ( + 'orchestration_v2_projection_turn_items_stop_request_idx', + 'orchestration_v2_message_search') + ORDER BY name`; + return { threads, schema }; + }), + ); + assert.deepStrictEqual( + imported.threads.map((row) => row.thread_id), + ["fork-thread", "settled-thread", "stopped-thread"], + ); + assert.deepStrictEqual( + imported.schema.map((row) => row.name), + [ + "orchestration_v2_message_search", + "orchestration_v2_projection_turn_items_stop_request_idx", + ], + ); + }), + ); + it.effect("refuses while a dev server holds the destination", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/scripts/migrate-dev-db.ts b/apps/server/scripts/migrate-dev-db.ts index f05120ddaf181..afec0c9458b81 100644 --- a/apps/server/scripts/migrate-dev-db.ts +++ b/apps/server/scripts/migrate-dev-db.ts @@ -410,6 +410,33 @@ const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigra }; }); +// Peer links preview builds recorded 68-70 before main took those slots for other migrations. +// A snapshot with exactly that history drops the preview's schema so main's 68+ can run. +const PEER_LINKS_PREVIEW_HISTORY = [ + "68:PeerLinks", + "69:PeerLinkFence", + "70:WaitingLinkRequestIndex", +]; + +const forgetPeerLinksPreviewHistory = Effect.fn("forgetPeerLinksPreviewHistory")(function* () { + const sql = yield* SqlClient.SqlClient; + const tables = yield* sql` + SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'effect_sql_migrations'`; + if (tables.length === 0) return; + const tail = yield* sql<{ migration_id: number; name: string }>` + SELECT migration_id, name FROM effect_sql_migrations WHERE migration_id >= 68 + ORDER BY migration_id`; + const history = tail.map((row) => `${row.migration_id}:${row.name}`); + if (history.join() !== PEER_LINKS_PREVIEW_HISTORY.join()) return; + yield* sql.withTransaction( + Effect.gen(function* () { + yield* sql`DROP INDEX IF EXISTS orchestration_v2_projection_turn_items_waiting_link_idx`; + yield* sql`DROP TABLE IF EXISTS peer_environment_links`; + yield* sql`DELETE FROM effect_sql_migrations WHERE migration_id >= 68`; + }), + ); +}); + export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* ( input: RunMigrateDevDbInput, options: RunMigrateDevDbOptions = {}, @@ -485,6 +512,7 @@ export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* ( const executed = yield* Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; yield* sql.unsafe("PRAGMA foreign_keys = ON").unprepared; + yield* forgetPeerLinksPreviewHistory(); return yield* runMigrations(); }).pipe( Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })), From 98fd5f2fe2967fb54286ad402fdb3182394dfb20 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:09:28 -0800 Subject: [PATCH 018/253] fix(desktop): AppImage updates no longer leave old runtimes and mounts running (#29672) --- .../src/electron/ElectronUpdater.test.ts | 118 ++++++++++++++++++ apps/desktop/src/electron/ElectronUpdater.ts | 23 +++- 2 files changed, 140 insertions(+), 1 deletion(-) create mode 100644 apps/desktop/src/electron/ElectronUpdater.test.ts diff --git a/apps/desktop/src/electron/ElectronUpdater.test.ts b/apps/desktop/src/electron/ElectronUpdater.test.ts new file mode 100644 index 0000000000000..e47c741bf3bd8 --- /dev/null +++ b/apps/desktop/src/electron/ElectronUpdater.test.ts @@ -0,0 +1,118 @@ +// @effect-diagnostics nodeBuiltinImport:off -- Intercepts the spawn electron-updater requires natively. +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { autoUpdater } from "electron-updater"; +import type * as NodeChildProcess from "node:child_process"; +import * as NodeModule from "node:module"; +import { vi } from "vite-plus/test"; + +// electron-updater requires Electron natively, outside vi.mock's reach, and builds its +// autoUpdater singleton as soon as it is imported. +vi.hoisted(() => { + const NodeModule = process.getBuiltinModule("node:module"); + const NodeEvents = process.getBuiltinModule("node:events"); + const require = NodeModule.createRequire(import.meta.url); + const electronPath = NodeModule.createRequire(require.resolve("electron-updater")).resolve( + "electron", + ); + const electronModule = new NodeModule.Module(electronPath); + electronModule.filename = electronPath; + electronModule.loaded = true; + electronModule.exports = { + app: { + getVersion: () => "1.0.0", + getName: () => "T3 Code", + isPackaged: true, + quit: () => undefined, + once: () => undefined, + }, + autoUpdater: new NodeEvents.EventEmitter(), + }; + require.cache[electronPath] = electronModule; +}); + +import * as ElectronUpdater from "./ElectronUpdater.ts"; + +const childProcess = NodeModule.createRequire(import.meta.url)("node:child_process") as { + spawn: ( + command: string, + args: ReadonlyArray, + options: NodeChildProcess.SpawnOptions, + ) => NodeChildProcess.ChildProcess; +}; + +describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "ElectronUpdater AppImage install", + () => { + it.live("relaunches the installed AppImage without the updating process's descriptors", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-appimage-install-" }); + const appImagePath = path.join(dir, "T3-Code.AppImage"); + const stagedPath = path.join(dir, "T3-Code-1.0.1.AppImage"); + const fdReportPath = path.join(dir, "relaunched-fds.txt"); + yield* fileSystem.writeFileString(appImagePath, "old AppImage"); + yield* fileSystem.writeFileString( + stagedPath, + `#!/bin/sh\nls /proc/self/fd > '${fdReportPath}'\n`, + ); + yield* fileSystem.chmod(stagedPath, 0o755); + + yield* Effect.acquireRelease( + Effect.sync(() => vi.stubEnv("APPIMAGE", appImagePath)), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + + autoUpdater.logger = null; + Object.assign(autoUpdater, { + downloadedUpdateHelper: { + file: stagedPath, + downloadedFileInfo: { isAdminRightsRequired: false }, + }, + }); + + // Electron's main process holds the AppImage runtime's keepalive pipe and some + // Chromium files without O_CLOEXEC. Node cannot hold such a descriptor, so the + // relaunch runs with fd 7 opened that way to stand in for them. + const relaunched = yield* Deferred.make(); + const realSpawn = childProcess.spawn; + yield* Effect.acquireRelease( + Effect.sync(() => { + childProcess.spawn = (command, args, options) => { + const child = realSpawn( + "bash", + ["-c", 'exec 7 Deferred.doneUnsafe(relaunched, Effect.void)); + return child; + }; + NodeModule.syncBuiltinESMExports(); + }), + () => + Effect.sync(() => { + childProcess.spawn = realSpawn; + NodeModule.syncBuiltinESMExports(); + }), + ); + + const electronUpdater = yield* ElectronUpdater.ElectronUpdater; + yield* electronUpdater.quitAndInstall({ isSilent: true, isForceRunAfter: true }); + yield* Deferred.await(relaunched); + + const descriptors = (yield* fileSystem.readFileString(fdReportPath)).trim().split("\n"); + assert.notInclude( + descriptors, + "7", + `relaunched AppImage inherited the updating process's fd 7 (open fds: ${descriptors.join(" ")})`, + ); + }).pipe(Effect.provide([ElectronUpdater.layer, NodeServices.layer])), + ); + }, +); diff --git a/apps/desktop/src/electron/ElectronUpdater.ts b/apps/desktop/src/electron/ElectronUpdater.ts index c71b42040db29..0cc22bb4b1633 100644 --- a/apps/desktop/src/electron/ElectronUpdater.ts +++ b/apps/desktop/src/electron/ElectronUpdater.ts @@ -4,9 +4,29 @@ import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; -import { autoUpdater } from "electron-updater"; +import { AppImageUpdater, autoUpdater } from "electron-updater"; type AutoUpdater = typeof autoUpdater; +type SpawnLog = (cmd: string, args?: Array, ...rest: Array) => Promise; + +// Electron holds the AppImage runtime's keepalive pipe and some files without O_CLOEXEC; a +// relaunched AppImage inherits them, so old runtimes and FUSE mounts never exit. bash (AppRun +// already needs it; dash cannot close multi-digit fds) closes them before exec'ing the AppImage. +// -p skips BASH_ENV and exported functions in the helper only; the AppImage still receives both. +const CLOSE_INHERITED_FDS_THEN_EXEC = + 'for fd in /proc/self/fd/*; do fd=${fd##*/}; case $fd in *[!0-9]*|[012]) ;; *) eval "exec $fd>&-" ;; esac; done; exec "$@"'; + +const relaunchWithoutInheritedDescriptors = (updater: AppImageUpdater) => { + const spawnLog = (AppImageUpdater.prototype as unknown as { spawnLog: SpawnLog }).spawnLog; + (updater as unknown as { spawnLog: SpawnLog }).spawnLog = function (cmd, args = [], ...rest) { + return spawnLog.call( + this, + "bash", + ["-p", "-c", CLOSE_INHERITED_FDS_THEN_EXEC, cmd, cmd, ...args], + ...rest, + ); + }; +}; export type ElectronUpdaterFeedUrl = Parameters[0]; @@ -153,6 +173,7 @@ export const make = ElectronUpdater.of({ }) { return Effect.suspend(() => { const channel = autoUpdater.channel; + if (autoUpdater instanceof AppImageUpdater) relaunchWithoutInheritedDescriptors(autoUpdater); return Effect.try({ try: () => autoUpdater.quitAndInstall(isSilent, isForceRunAfter), catch: (cause) => From 6d35d09060a901d15e31ab7ccdeedfe6696c23c5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:11:20 -0800 Subject: [PATCH 019/253] fix(cli): t3 triage points at the prompt when the agent fails to start (#28192) --- apps/server/src/cli/triage.test.ts | 75 ++++++++++++++++++++++++++++++ apps/server/src/cli/triage.ts | 55 +++++++++++++++++++--- 2 files changed, 123 insertions(+), 7 deletions(-) create mode 100644 apps/server/src/cli/triage.test.ts diff --git a/apps/server/src/cli/triage.test.ts b/apps/server/src/cli/triage.test.ts new file mode 100644 index 0000000000000..05eaf04e1f014 --- /dev/null +++ b/apps/server/src/cli/triage.test.ts @@ -0,0 +1,75 @@ +// @effect-diagnostics nodeBuiltinImport:off - CLI integration spawns a fake agent from PATH. +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; + +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { TRIAGE_PROMPT_FILE_NAME } from "@t3tools/contracts"; +import * as NetService from "@t3tools/shared/Net"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as TestConsole from "effect/testing/TestConsole"; +import { Command } from "effect/cli"; +import { vi } from "vite-plus/test"; + +import { cli } from "../binCli.ts"; +import { buildTriageLaunchPrompt } from "../triage/triagePrompt.ts"; + +const FAILING_AGENT_POSIX = `#!/bin/sh +echo "Error: There is not enough space on the disk. (os error 112)" >&2 +exit 1 +`; +const FAILING_AGENT_WINDOWS = `@echo Error: There is not enough space on the disk. (os error 112) 1>&2 +@exit /b 1 +`; + +it.live("a failed agent launch points at the prompt it could not run", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-cli-" }); + const binDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-triage-bin-" }); + const codexHome = NodePath.join(baseDir, "codex-home"); + NodeFS.writeFileSync(NodePath.join(binDir, "codex"), FAILING_AGENT_POSIX, { mode: 0o755 }); + NodeFS.writeFileSync(NodePath.join(binDir, "codex.cmd"), FAILING_AGENT_WINDOWS); + yield* Effect.acquireRelease( + // PATH holds only the fake agent, so a broken fixture can never fall through to a real codex. + Effect.sync(() => { + vi.stubEnv("PATH", binDir); + vi.stubEnv("CODEX_HOME", codexHome); + }), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + const previousExitCode = process.exitCode; + yield* Effect.addFinalizer(() => + Effect.sync(() => { + process.exitCode = previousExitCode; + }), + ); + + yield* Command.runWith(cli, { version: "0.0.0" })([ + "triage", + "--agent", + "codex", + "--base-dir", + baseDir, + ]); + const output = (yield* TestConsole.logLines).join("\n"); + + assert.equal(process.exitCode, 1); + const promptFilePath = NodeFS.readdirSync(baseDir, { recursive: true, encoding: "utf8" }) + .filter((entry) => NodePath.basename(entry) === TRIAGE_PROMPT_FILE_NAME) + .map((entry) => NodePath.join(baseDir, entry))[0]; + assert.isDefined(promptFilePath); + assert.include(output, promptFilePath); + assert.include(output, buildTriageLaunchPrompt(promptFilePath)); + assert.include(output, NodePath.join(NodePath.dirname(promptFilePath), "context.md")); + assert.include(output, `Codex keeps its state in ${codexHome}.`); + assert.include(output, "set CODEX_HOME to a folder on another drive"); + }).pipe( + Effect.provide( + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer, TestConsole.layer), + ), + ), +); diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.ts index b040054748ca7..c9173a3d46889 100644 --- a/apps/server/src/cli/triage.ts +++ b/apps/server/src/cli/triage.ts @@ -1,5 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeChildProcess from "node:child_process"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; import * as NodeReadlinePromises from "node:readline/promises"; import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell"; @@ -23,13 +25,30 @@ interface TriageAgent { readonly id: "claude" | "codex"; readonly command: string; readonly label: string; + readonly stateDirEnv: string; + readonly defaultStateDir: string; } const TRIAGE_AGENTS: ReadonlyArray = [ - { id: "claude", command: "claude", label: "Claude Code" }, - { id: "codex", command: "codex", label: "Codex" }, + { + id: "claude", + command: "claude", + label: "Claude Code", + stateDirEnv: "CLAUDE_CONFIG_DIR", + defaultStateDir: ".claude", + }, + { + id: "codex", + command: "codex", + label: "Codex", + stateDirEnv: "CODEX_HOME", + defaultStateDir: ".codex", + }, ]; +const resolveAgentStateDir = (agent: TriageAgent) => + process.env[agent.stateDirEnv]?.trim() || NodePath.join(NodeOS.homedir(), agent.defaultStateDir); + export class TriageAgentUnavailableError extends Schema.TaggedError()( "TriageAgentUnavailableError", { agent: Schema.String }, @@ -102,6 +121,15 @@ const runInteractiveSession = (input: { child.once("exit", (code, signal) => resume(Effect.succeed(code ?? (signal === null ? 0 : 1)))); }); +const describeTriageFiles = (session: { + readonly promptFilePath: string; + readonly contextFilePath: string; +}) => [ + "The triage prompt and machine context were written to:", + ` ${session.promptFilePath}`, + ` ${session.contextFilePath}`, +]; + const agentFlag = Flag.Literals("agent", ["claude", "codex"]).pipe( Flag.withDescription("Agent CLI to use. Default: ask when both are installed."), Flag.optional, @@ -164,16 +192,14 @@ export const triageCommand = Command.make("triage", { } // Windows .cmd shims cannot carry multiline argv; the prompt file also serves as the paste fallback. - const { sessionDir, promptFilePath, contextFilePath } = session; + const { sessionDir, promptFilePath } = session; if (selected === undefined) { yield* Console.log( [ "No supported agent CLI (claude, codex) was found on this machine.", "", - "The triage prompt and machine context were written to:", - ` ${promptFilePath}`, - ` ${contextFilePath}`, + ...describeTriageFiles(session), "", "Paste the prompt file into any coding agent to run triage by hand.", ].join("\n"), @@ -182,14 +208,29 @@ export const triageCommand = Command.make("triage", { } const model = Option.getOrUndefined(flags.model); + const launchPrompt = buildTriageLaunchPrompt(promptFilePath); const spawnSpec = yield* resolveSpawnCommand(selected.command, [ ...(model === undefined ? [] : ["--model", model]), - buildTriageLaunchPrompt(promptFilePath), + launchPrompt, ]); yield* Console.log(`Starting ${selected.label}. It will ask what went wrong.\n`); const exitCode = yield* runInteractiveSession({ ...spawnSpec, cwd: sessionDir }); if (exitCode !== 0) { process.exitCode = exitCode; + yield* Console.log( + [ + "", + `${selected.label} exited with code ${String(exitCode)}.`, + "", + `${selected.label} keeps its state in ${resolveAgentStateDir(selected)}.`, + `If that drive is out of space, free some up or set ${selected.stateDirEnv} to a folder on another drive.`, + "", + ...describeTriageFiles(session), + "", + `To retry, start \`${selected.command}\` yourself with any flags it suggested, or use any coding agent, and give it this prompt:`, + launchPrompt, + ].join("\n"), + ); } }), ), From cc624432ac9b137f27f1d718a4cefb0a46d6a0c0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:13:23 -0800 Subject: [PATCH 020/253] fix(web): formatted link labels wrap inside table cells (#27781) --- .../components/ChatMarkdown.browser.test.tsx | 17 +++++++++++++++++ .../components/chat/MarkdownExternalLink.tsx | 3 ++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index 59460d83a0332..40fb836fd7b0f 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -296,6 +296,23 @@ describe("ChatMarkdown favicon privacy", () => { }); }); +describe("ChatMarkdown external link labels", () => { + it("keeps a leading emoji whole", async () => { + setup(); + await using screen = await render( + , + ); + await vi.waitFor(() => { + const link = screen.container.querySelector("a"); + expect(link?.textContent).toContain("😀 Read"); + const walker = document.createTreeWalker(link!, NodeFilter.SHOW_TEXT); + const textNodes: string[] = []; + while (walker.nextNode()) textNodes.push(walker.currentNode.nodeValue ?? ""); + expect(textNodes.filter((node) => /\p{Surrogate}/u.test(node))).toEqual([]); + }); + }); +}); + describe("ChatMarkdown streaming", () => { it("runs only a complete single-line shell block after a click", async () => { setup(); diff --git a/apps/web/src/components/chat/MarkdownExternalLink.tsx b/apps/web/src/components/chat/MarkdownExternalLink.tsx index d462799564463..e1d8f0a06bb57 100644 --- a/apps/web/src/components/chat/MarkdownExternalLink.tsx +++ b/apps/web/src/components/chat/MarkdownExternalLink.tsx @@ -51,7 +51,8 @@ const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: function leadingExternalLinkTextLength(text: string): number { const protocol = /^(?:https?:\/\/)/i.exec(text)?.[0]; if (protocol) return protocol.length; - return Math.min(text.length, 1); + // A whole code point, so a surrogate pair is not split across elements. + return Array.from(text.slice(0, 2))[0]?.length ?? 0; } // Keep short labels such as PR numbers intact in narrow table columns. From 2904fea7d593c687393b7ad2434de03d590871cd Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:17:13 -0800 Subject: [PATCH 021/253] fix(web): Mod+B toggles bold at a collapsed cursor when the sidebar toggle is remapped (#29445) --- ...rPromptEditorTiptap.input.browser.test.tsx | 51 +++++++++++++++++-- .../components/ComposerPromptEditorTiptap.tsx | 2 - apps/web/src/composer-markdown-source.ts | 18 +++++-- apps/web/src/composer-rich-text-doc.ts | 15 ------ apps/web/src/keybindings.ts | 2 +- 5 files changed, 61 insertions(+), 27 deletions(-) diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 925319680d40d..0e29db4f2dd77 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -151,6 +151,51 @@ it.each([ expect(textWithMark(editor, "code")).toEqual(code); }); +it.each([ + { mark: "bold", key: "b", marker: "**" }, + { mark: "italic", key: "i", marker: "*" }, +])("toggles $mark with Mod+$key at a collapsed cursor", async ({ mark, key, marker }) => { + await using screen = await mountEditor("ship it"); + const { editor } = screen; + const mod = isMacPlatform(navigator.platform) ? "Meta" : "Control"; + const chord = `{${mod}>}${key}{/${mod}}`; + await act(async () => { + editor.commands.focus("end"); + }); + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom)); + await userEvent.keyboard(" "); + await userEvent.keyboard(chord); + await userEvent.keyboard("now"); + await userEvent.keyboard(chord); + await userEvent.keyboard(" done"); + await vi.waitFor(() => + expect(serializeEditorDoc(editor.state.doc).value).toBe(`ship it ${marker}now${marker} done`), + ); + expect(textWithMark(editor, mark)).toEqual(["now"]); +}); + +it.each([ + { key: "i", caret: 10, expected: "ship it **n*X*ow** done" }, + { key: "i", caret: 9, expected: "ship it *X***now** done" }, + { key: "e", caret: "{ArrowLeft>5/}", expected: "ship it **now**`X` done" }, +])( + "Mod+$key at $caret in a bold word styles the next typed text", + async ({ key, caret, expected }) => { + await using screen = await mountEditor("ship it **now** done"); + const { editor } = screen; + const mod = isMacPlatform(navigator.platform) ? "Meta" : "Control"; + await act(async () => { + if (typeof caret === "number") editor.commands.focus(caret); + else editor.commands.focus("end"); + }); + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom)); + if (typeof caret === "string") await userEvent.keyboard(caret); + await userEvent.keyboard(`{${mod}>}${key}{/${mod}}`); + await userEvent.keyboard("X"); + await vi.waitFor(() => expect(serializeEditorDoc(editor.state.doc).value).toBe(expected)); + }, +); + it.each([ { word: "ship", prefix: "", source: ["**ship**"] }, { word: "path\\", prefix: "", source: [] }, @@ -169,7 +214,7 @@ it.each([ code: ["path\\"], }, ])( - "bolds $word after '$prefix' with Mod+B only when text is selected", + "bolds $word after '$prefix' with Mod+B over a selection", async ({ word, prefix, prefixText = prefix, source, code = [] }) => { const value = `${prefix}${word} it`; await using screen = await mountEditor(value); @@ -179,10 +224,6 @@ it.each([ editor.commands.focus("end"); }); await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom)); - await userEvent.keyboard(modB); - // Without the guard, Tiptap stores bold for the next typed text. - expect(editor.state.storedMarks).toBeNull(); - await act(async () => { editor.commands.setTextSelection({ from: prefixText.length + 1, diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index c443825dffd5c..474b2f1f181c6 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -76,7 +76,6 @@ import { ComposerCodeBlockExtension, ComposerListExtensions, buildTiptapContent, - ComposerBoldSelectionOnlyExtension, convertBulletItemToTask, ComposerCodeExtension, ComposerBoldExtension, @@ -834,7 +833,6 @@ function createComposerExtensions(richText: boolean) { ...(richText ? [ ComposerMarkdownSourceExtension, - ComposerBoldSelectionOnlyExtension, ComposerItalicExtension, ComposerBoldExtension, ComposerStrikeExtension, diff --git a/apps/web/src/composer-markdown-source.ts b/apps/web/src/composer-markdown-source.ts index 11ac9fdb95bc3..c4119b981b18c 100644 --- a/apps/web/src/composer-markdown-source.ts +++ b/apps/web/src/composer-markdown-source.ts @@ -550,10 +550,20 @@ export const ComposerMarkdownSourceExtension = TiptapMark.create({ // in another style. Parse the source first and toggle the result. const toggle = (name: RichTextMark) => () => { const { state } = this.editor; - if (state.selection.empty) return false; - const touched = sourceRegions(state.doc, this.type).some((region) => - touches(state.selection, region), - ); + const { selection } = state; + const touched = sourceRegions(state.doc, this.type).some((region) => { + if (!touches(selection, region)) return false; + if (!selection.empty) return true; + // Turning a style off just inside its own markers would type into them. + // Everywhere else Tiptap's own toggle styles the typed text correctly. + const { units } = regionUnits(state.doc, region); + const offset = selection.from - region.from; + const [before, after] = [units[offset - 1], units[offset]]; + return ( + (before === null && after?.includes(name) === true) || + (after === null && before?.includes(name) === true) + ); + }); if (!touched) return false; return this.editor.chain().command(collapseShownMarkdownSource).toggleMark(name).run(); }; diff --git a/apps/web/src/composer-rich-text-doc.ts b/apps/web/src/composer-rich-text-doc.ts index 1712fc0f5c98b..ef796384aa10b 100644 --- a/apps/web/src/composer-rich-text-doc.ts +++ b/apps/web/src/composer-rich-text-doc.ts @@ -22,7 +22,6 @@ import { getChangedRanges, type Command, type Editor, - Extension, InputRule, markInputRule, markPasteRule, @@ -372,20 +371,6 @@ export const ComposerStrikeExtension = Strike.extend({ }, }); -/** - * Mod+B bolds selected text only. Without a selection Tiptap would toggle bold - * for the next typed text, which users hit by accident when they mean the - * sidebar toggle. Runs ahead of the Bold extension and swallows the chord. - */ -export const ComposerBoldSelectionOnlyExtension = Extension.create({ - name: "composerBoldSelectionOnly", - priority: 1000, - addKeyboardShortcuts() { - const ignoreWithoutSelection = () => this.editor.state.selection.empty; - return { "Mod-b": ignoreWithoutSelection, "Mod-B": ignoreWithoutSelection }; - }, -}); - /** * Tiptap's block chords can nest blocks inside quotes that the serializer cannot write, * silently dropping their text from stored drafts. diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index fc96aa1f85896..cf2be46dcbdcc 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -379,7 +379,7 @@ export function isOpenFavoriteEditorShortcut( * Whether the keypress should bold text in the rich-text composer: Mod+B * without extra modifiers, with text selected. Tiptap binds the same chord, so * app shortcuts captured ahead of the editor yield only in that case. With no - * selection the chord stays with the app (the sidebar toggle by default). + * selection an app binding on the chord wins (the sidebar toggle by default). */ export function isRichTextBoldShortcut( event: ShortcutEventLike, From 42d645ae9e03a0d9035d5b89eda60d4ab13c497e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:21:10 -0800 Subject: [PATCH 022/253] fix(web): update Retry stops re-sending servers already on the target version (#32924) --- .../sidebar/updateEverythingRun.test.ts | 73 ++++++++++++++++++- .../sidebar/updateEverythingRun.tsx | 36 ++++++--- 2 files changed, 98 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/sidebar/updateEverythingRun.test.ts b/apps/web/src/components/sidebar/updateEverythingRun.test.ts index ec6e5b79b7c0d..f451eadc13b2d 100644 --- a/apps/web/src/components/sidebar/updateEverythingRun.test.ts +++ b/apps/web/src/components/sidebar/updateEverythingRun.test.ts @@ -1,9 +1,16 @@ -import { EnvironmentId } from "@t3tools/contracts"; +import { EnvironmentId, type ServerConfig } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; import { appAtomRegistry } from "~/rpc/atomRegistry"; import { serverEnvironment } from "~/state/server"; -import { startDesktopUpdateLaunchNotice } from "./updateEverythingRun"; +import type { ServerUpdateOutcome, ServerUpdateTarget } from "../ServerUpdateAction"; +import type { UpdateEverythingRun } from "./updateEverything.logic"; +import { + retryFailedUpdateRunServers, + setUpdateEverythingRun, + startDesktopUpdateLaunchNotice, +} from "./updateEverythingRun"; function relaunchWhileRestarting(environmentId: EnvironmentId) { const now = 1_800_000_000_000; @@ -68,3 +75,65 @@ describe("startDesktopUpdateLaunchNotice", () => { } }); }); + +describe("retryFailedUpdateRunServers", () => { + it("settles a failed server that already restarted on the target and retries only the others", () => { + const targetVersion = "9.9.9"; + const serverVersions = new Map([ + [EnvironmentId.make("already-updated"), targetVersion], + [EnvironmentId.make("behind"), "9.9.8"], + ]); + using _config = vi + .spyOn(serverEnvironment, "configValueAtom") + .mockImplementation((environmentId) => + Atom.make({ + environment: { serverVersion: serverVersions.get(environmentId!) }, + } as unknown as ServerConfig), + ); + const rejection = "Remote updates must select a newer server version."; + const failedMachine = (environmentId: EnvironmentId) => ({ + environmentId, + label: environmentId, + updatesProviders: false, + server: { + environmentId, + serverLabel: environmentId, + selfUpdate: "boot-service" as const, + targetVersion, + }, + handedOffVersion: null, + startedAt: 0, + result: "failed" as const, + failure: rejection, + providerFailure: null, + }); + setUpdateEverythingRun(() => ({ + localVersion: null, + phase: "servers", + restartAt: null, + machines: [...serverVersions.keys()].map(failedMachine), + })); + const update = vi.fn( + (_target: ServerUpdateTarget) => new Promise(() => {}), + ); + + retryFailedUpdateRunServers(update); + + let run: UpdateEverythingRun | null = null; + setUpdateEverythingRun((current) => { + run = current; + return null; + }); + expect(update.mock.calls.map(([target]) => target.environmentId)).toEqual(["behind"]); + expect( + (run as UpdateEverythingRun | null)?.machines.map(({ environmentId, result, server }) => ({ + environmentId, + result, + retryable: server !== null, + })), + ).toEqual([ + { environmentId: "already-updated", result: "done", retryable: false }, + { environmentId: "behind", result: null, retryable: true }, + ]); + }); +}); diff --git a/apps/web/src/components/sidebar/updateEverythingRun.tsx b/apps/web/src/components/sidebar/updateEverythingRun.tsx index 0422fffe6a9fc..ff12f9093571e 100644 --- a/apps/web/src/components/sidebar/updateEverythingRun.tsx +++ b/apps/web/src/components/sidebar/updateEverythingRun.tsx @@ -1,6 +1,6 @@ import { useAtomValue } from "@effect/atom-react"; import { serverUpdateStateAtom } from "@t3tools/client-runtime/state/server"; -import { EnvironmentId } from "@t3tools/contracts"; +import { EnvironmentId, type ServerConfig } from "@t3tools/contracts"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; @@ -63,6 +63,13 @@ export function settleUpdateRunMachine( ); } +function runsVersion(config: ServerConfig | null, targetVersion: string): boolean { + return ( + config !== null && + resolveVersionMismatch(config.environment.serverVersion, targetVersion) === null + ); +} + export function retryFailedUpdateRunServers( update: ( target: ServerUpdateTarget, @@ -75,7 +82,23 @@ export function retryFailedUpdateRunServers( ? [{ target: machine.server, providerFailure: machine.providerFailure }] : [], ); - const targets = failed.map(({ target }) => target); + const pending: typeof failed = []; + for (const entry of failed) { + // The host rejects a same-version update; a server that came back on the target is done. + if ( + runsVersion( + appAtomRegistry.get(serverEnvironment.configValueAtom(entry.target.environmentId)), + entry.target.targetVersion, + ) + ) { + settleUpdateRunMachine(entry.target.environmentId, entry.providerFailure, { + serverUpdated: true, + }); + } else { + pending.push(entry); + } + } + const targets = pending.map(({ target }) => target); const retried = new Set(targets.map((target) => target.environmentId)); const startedAt = Date.now(); updateRunMachines((machine) => @@ -83,7 +106,7 @@ export function retryFailedUpdateRunServers( ? { ...machine, result: null, failure: null, startedAt } : machine, ); - for (const { target, providerFailure } of failed) { + for (const { target, providerFailure } of pending) { void update(target, { quiet: true }).then((outcome) => settleUpdateRunMachine( target.environmentId, @@ -309,12 +332,7 @@ function followHandedOffServers(servers: ReadonlyArray): void { const unsubscribe = appAtomRegistry.subscribe( serverEnvironment.configValueAtom(server.environmentId), (config) => { - if ( - config !== null && - resolveVersionMismatch(config.environment.serverVersion, server.targetVersion) === null - ) { - settle(null); - } + if (runsVersion(config, server.targetVersion)) settle(null); }, { immediate: true }, ); From b18fefde725c1fec715f2771586a0df94d75d749 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:21:22 -0800 Subject: [PATCH 023/253] fix(web): switching a cold Claude thread to Codex no longer compacts first (#25986) --- ...hatView.handoffCompaction.browser.test.tsx | 125 ++++++++++++++++++ apps/web/src/components/ChatView.tsx | 2 + apps/web/test/fakeEnvironment.ts | 94 ++++++++----- 3 files changed, 190 insertions(+), 31 deletions(-) create mode 100644 apps/web/src/components/ChatView.handoffCompaction.browser.test.tsx diff --git a/apps/web/src/components/ChatView.handoffCompaction.browser.test.tsx b/apps/web/src/components/ChatView.handoffCompaction.browser.test.tsx new file mode 100644 index 0000000000000..ca6cc6ab95c00 --- /dev/null +++ b/apps/web/src/components/ChatView.handoffCompaction.browser.test.tsx @@ -0,0 +1,125 @@ +import { createMemoryHistory } from "@tanstack/react-router"; +import { + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + type OrchestrationV2ProviderThread, +} from "@t3tools/contracts"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; +import type * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { AppRoot } from "~/AppRoot"; +// The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines) +// takes 6-11s; importing it here keeps that out of the test's timeout. +import "~/components/ChatView"; +import { __setClientSettingsForTests } from "~/hooks/useSettings"; +import { getRouter } from "~/router"; +import { + CLAUDE_PROVIDER, + CODEX_PROVIDER, + ENVIRONMENT_ID, + dispatchedCommands, + installFakeEnvironment, + threadWithHistory, + type FakeDriver, +} from "../../test/fakeEnvironment"; +import { render } from "../../test/render"; + +// The socket is the only fake layer; see test/appScenarios.renders.tsx. +vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => { + const [actual, { fakeDriver }, Layer] = await Promise.all([ + importOriginal<{ readonly ConnectionDriver: Context.Key }>(), + import("../../test/fakeEnvironment"), + import("effect/Layer"), + ]); + return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; +}); + +vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ + ...(await original()), + trackRpcRequestSent: () => {}, +})); + +const CLAUDE = ProviderInstanceId.make("claudeAgent"); +const CLAUDE_DRIVER = ProviderDriverKind.make("claudeAgent"); + +/** A Claude thread whose 250k-token context went cold long ago, with its native thread kept for handoff. */ +function coldClaudeThread() { + const thread = threadWithHistory("thread-claude", 3, { + instanceId: CLAUDE, + model: "claude-opus-4-6", + }); + const at = DateTime.makeUnsafe("2026-03-17T19:12:28.000Z"); + const providerThread: OrchestrationV2ProviderThread = { + id: ProviderThreadId.make("provider-thread-claude"), + driver: CLAUDE_DRIVER, + providerInstanceId: CLAUDE, + providerSessionId: null, + appThreadId: thread.id, + ownerNodeId: null, + nativeThreadRef: { driver: CLAUDE_DRIVER, nativeId: "native-claude", strength: "strong" }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: 1, + lastRunOrdinal: 3, + handoffIds: [], + forkedFrom: null, + pendingBackgroundTasks: [], + contextUsage: { usedTokens: 250_000, maxTokens: 1_000_000 }, + nativeMetadata: null, + goal: null, + createdAt: at, + updatedAt: at, + }; + return { ...thread, providerThreads: [providerThread] }; +} + +it("sends a Codex follow-up on a cold Claude thread without compacting first", async () => { + const thread = coldClaudeThread(); + using _environment = installFakeEnvironment([thread], { + acceptCommands: true, + providers: [CLAUDE_PROVIDER, CODEX_PROVIDER], + }); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + await expect.element(page.getByText(`Answer 2 for ${thread.id}.`)).toBeVisible(); + const compactAndSend = page.getByRole("button", { name: "Compact and send" }); + await expect.element(compactAndSend).toBeVisible(); + + await page.getByRole("button", { name: "Claude Opus 4.6", exact: true }).click(); + // The picker lists only the active provider's models until you search. + await userEvent.type(page.getByPlaceholder("Search models..."), "GPT-5.4"); + await page.getByRole("option", { name: "GPT-5.4", exact: false }).click(); + await expect.element(page.getByRole("button", { name: "GPT-5.4", exact: true })).toBeVisible(); + await expect.element(compactAndSend).not.toBeInTheDocument(); + // Picking a model leaves the composer's settings menu open. + await userEvent.keyboard("{Escape}"); + + const editor = page.getByTestId("composer-editor"); + await userEvent.click(editor); + await userEvent.type(editor, "keep going"); + await userEvent.keyboard("{Enter}"); + + const messages = () => + dispatchedCommands().flatMap((command) => + command.type === "message.dispatch" + ? [{ text: command.text, instanceId: command.modelSelection?.instanceId }] + : [], + ); + const sent = { text: "keep going", instanceId: CODEX_PROVIDER.instanceId }; + await vi.waitFor(() => expect(messages()).toContainEqual(sent)); + expect(messages()).toEqual([sent]); +}); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index f1fcdf2d77a4a..829c1155af668 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2462,8 +2462,10 @@ export default function ChatView(props: ChatViewProps) { pendingApprovals.length > 0 || pendingUserInputs.length > 0; const compactDisabled = compactThreadUnavailable; + // The context window is the current conversation's, so a handoff destination never inherits it. const resumeCompactionTokens = activeContextWindow && + pendingHandoff === null && resolveIdleCompaction( settings, activeProviderInstanceId ?? ProviderInstanceId.make("claudeAgent"), diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index e878a39653432..455a705192b8e 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -18,9 +18,11 @@ import { WS_METHODS, WsRpcGroup, type VcsStatusStreamEvent, + type ModelSelection, type OrchestrationProjectShell, type OrchestrationV2Command, type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2ProviderThread, type OrchestrationV2Run, type OrchestrationV2ShellStreamItem, type OrchestrationV2ThreadProjection, @@ -68,30 +70,42 @@ const auth = { sessionCookieName: "t3_session", }; -const baseServerConfig: ServerConfig = { - ...Schema.decodeUnknownSync(ServerConfig)({ +const readyProvider = ( + instanceId: string, + driver: string, + models: ReadonlyArray<{ readonly slug: string; readonly name: string }>, +) => ({ + instanceId, + driver, + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-03-17T19:12:28.000Z", + models: models.map((model) => ({ ...model, isCustom: false, capabilities: null })), +}); +export const CODEX_PROVIDER = readyProvider(CODEX, "codex", [ + { slug: "gpt-5.4", name: "GPT-5.4" }, + { slug: "gpt-5.5", name: "GPT-5.5" }, +]); +export const CLAUDE_PROVIDER = { + ...readyProvider("claudeAgent", "claudeAgent", [ + { slug: "claude-opus-4-6", name: "Claude Opus 4.6" }, + ]), + slashCommands: [{ name: "compact" }], +}; + +const decodeServerConfig = Schema.decodeUnknownSync(ServerConfig); +const makeServerConfig = (providers: ReadonlyArray): ServerConfig => ({ + ...decodeServerConfig({ environment: descriptor, auth, cwd: "/workspace/render", keybindingsConfigPath: "/workspace/.t3/keybindings.json", keybindings: [], issues: [], - providers: [ - { - instanceId: CODEX, - driver: "codex", - enabled: true, - installed: true, - version: "1.0.0", - status: "ready", - auth: { status: "authenticated" }, - checkedAt: "2026-03-17T19:12:28.000Z", - models: [ - { slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: null }, - { slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null }, - ], - }, - ], + providers, availableEditors: [], observability: { logsDirectoryPath: "/workspace/.t3/logs", @@ -105,7 +119,8 @@ const baseServerConfig: ServerConfig = { shellResumeCompletionMarker: true, }), keybindings: DEFAULT_RESOLVED_KEYBINDINGS, -}; +}); +let baseServerConfig = makeServerConfig([CODEX_PROVIDER]); // A server only leaves threads out of the shell when it serves their families. const serverConfig = (): ServerConfig => threads.some((thread) => thread.olderSettled) @@ -171,13 +186,19 @@ export function assistantItem( } satisfies OrchestrationV2TurnItem; } -function run(threadId: ThreadId, id: RunId, ordinal: number, userMessageId: string) { +function run( + threadId: ThreadId, + id: RunId, + ordinal: number, + userMessageId: string, + modelSelection: ModelSelection = MODEL, +) { return { id, threadId, ordinal, - providerInstanceId: CODEX, - modelSelection: MODEL, + providerInstanceId: modelSelection.instanceId, + modelSelection, providerThreadId: null, userMessageId: MessageId.make(userMessageId), rootNodeId: null, @@ -198,18 +219,26 @@ export interface FakeThread { readonly olderSettled?: true; readonly id: ThreadId; readonly title: string; + /** Defaults to GPT-5.4 on Codex. */ + readonly modelSelection?: ModelSelection; + /** The first is the thread's active provider thread. */ + readonly providerThreads?: ReadonlyArray; readonly runs: ReadonlyArray; readonly items: ReadonlyArray; } /** A thread of `turns` user prompts, each answered in markdown with a list and inline code. */ -export function threadWithHistory(name: string, turns: number): FakeThread { +export function threadWithHistory( + name: string, + turns: number, + modelSelection: ModelSelection = MODEL, +): FakeThread { const id = ThreadId.make(name); const runs: OrchestrationV2Run[] = []; const items: OrchestrationV2TurnItem[] = []; for (let turn = 0; turn < turns; turn++) { const runId = RunId.make(`${name}-run-${turn}`); - runs.push(run(id, runId, turn + 1, `${name}-user-${turn}`)); + runs.push(run(id, runId, turn + 1, `${name}-user-${turn}`, modelSelection)); items.push( userItem(id, runId, `${name}-user-${turn}`, turn * 2, `${name}: question ${turn}`), assistantItem( @@ -222,22 +251,23 @@ export function threadWithHistory(name: string, turns: number): FakeThread { ), ); } - return { id, title: `Thread ${name}`, runs, items }; + return { id, title: `Thread ${name}`, modelSelection, runs, items }; } function shellOf(thread: FakeThread): OrchestrationV2ThreadShell { const latest = thread.runs.at(-1); + const modelSelection = thread.modelSelection ?? MODEL; return { id: thread.id, projectId: PROJECT_ID, title: thread.title, - providerInstanceId: CODEX, - modelSelection: MODEL, + providerInstanceId: modelSelection.instanceId, + modelSelection, runtimeMode: "full-access", interactionMode: "default", branch: "main", worktreePath: null, - activeProviderThreadId: null, + activeProviderThreadId: thread.providerThreads?.[0]?.id ?? null, lineage: { rootThreadId: thread.sideChatOf ?? thread.id, parentThreadId: thread.sideChatOf ?? null, @@ -289,7 +319,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection { interactionMode: shell.interactionMode, branch: shell.branch, worktreePath: shell.worktreePath, - activeProviderThreadId: null, + activeProviderThreadId: shell.activeProviderThreadId, lineage: shell.lineage, forkedFrom: null, createdBy: "user", @@ -307,7 +337,7 @@ function projectionOf(thread: FakeThread): OrchestrationV2ThreadProjection { nodes: [], subagents: [], providerSessions: [], - providerThreads: [], + providerThreads: [...(thread.providerThreads ?? [])], providerTurns: [], runtimeRequests: [], messages: [], @@ -465,9 +495,10 @@ const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)( /** Serves the environment's HTTP API and these threads until disposed. */ export function installFakeEnvironment( fixtures: ReadonlyArray, - options?: { readonly acceptCommands?: boolean }, + options?: { readonly acceptCommands?: boolean; readonly providers?: ReadonlyArray }, ): Disposable { threads = fixtures; + baseServerConfig = makeServerConfig(options?.providers ?? [CODEX_PROVIDER]); dispatched = []; acceptCommands = options?.acceptCommands === true; globalThis.fetch = async (input, init) => { @@ -491,6 +522,7 @@ export function installFakeEnvironment( [Symbol.dispose]: () => { globalThis.fetch = realFetch; threads = []; + baseServerConfig = makeServerConfig([CODEX_PROVIDER]); dispatched = []; acceptCommands = false; }, From a24f7a115000012c7f867a53eda4b21f945b5d72 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:21:56 +0000 Subject: [PATCH 024/253] fix(web): code blocks always show their own highlighted source (#34527) Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- .../src/components/ChatMarkdown.browser.test.tsx | 15 +++++++++++++++ .../components/chat/MarkdownCodeBlock.logic.ts | 11 +++++++---- .../web/src/components/chat/MarkdownCodeBlock.tsx | 2 +- 3 files changed, 23 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/ChatMarkdown.browser.test.tsx b/apps/web/src/components/ChatMarkdown.browser.test.tsx index 40fb836fd7b0f..24e0b6655ff7c 100644 --- a/apps/web/src/components/ChatMarkdown.browser.test.tsx +++ b/apps/web/src/components/ChatMarkdown.browser.test.tsx @@ -275,6 +275,21 @@ it("reuses the parse of a remounted message that has stable extra plugins", asyn expect(parsed).toHaveBeenCalledTimes(1); }); +it("highlights a code block's own source when an earlier block of the same length was cached", async () => { + setup(); + const highlightedText = (container: HTMLElement) => + container.querySelector(".chat-markdown-shiki")?.textContent?.trim(); + // These two lines share a 32-bit FNV-1a hash and a length. + const first = 'const commitSha = "f36a6d8fe0aa";'; + const second = 'const commitSha = "cb06f8d135b3";'; + { + await using screen = await renderText(`\`\`\`ts\n${first}\n\`\`\``); + await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(first)); + } + await using screen = await renderText(`\`\`\`ts\n${second}\n\`\`\``); + await vi.waitFor(() => expect(highlightedText(screen.container)).toBe(second)); +}); + describe("ChatMarkdown favicon privacy", () => { it("suppresses private link images while preserving public links across updates", async () => { setup(); diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts index f053a05e9739e..328b3fef11b6b 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts +++ b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts @@ -1,7 +1,7 @@ import { Children, isValidElement, type ReactNode } from "react"; import type { ExtraProps as ReactMarkdownExtraProps } from "react-markdown"; -import { fnv1a32, type DiffThemeName } from "../../lib/diffRendering"; +import type { DiffThemeName } from "../../lib/diffRendering"; const CODE_FENCE_LANGUAGE_REGEX = /(?:^|\s)language-([^\s]+)/; @@ -106,14 +106,17 @@ export function extractCodeBlock( }; } +// The key holds the code itself: a hash would let two different blocks share +// highlighted HTML. The length prefix keeps a language with ":" unambiguous. export function createHighlightCacheKey( code: string, language: string, themeName: DiffThemeName, ): string { - return `${fnv1a32(code).toString(36)}:${code.length}:${language}:${themeName}`; + return `${language.length}:${language}:${themeName}:${code}`; } -export function estimateHighlightedSize(html: string, code: string): number { - return Math.max(html.length * 2, code.length * 3); +/** Approximate UTF-16 bytes for a cache entry, counting its key, which holds the code. */ +export function estimateHighlightedSize(html: string, cacheKey: string): number { + return (cacheKey.length + html.length) * 2; } diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.tsx index 67ad47e426ea3..7992ce2e6f76b 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.tsx +++ b/apps/web/src/components/chat/MarkdownCodeBlock.tsx @@ -354,7 +354,7 @@ function UncachedShikiCodeBlock({ highlightedCodeCache.set( cacheKey, highlightedHtml, - estimateHighlightedSize(highlightedHtml, code), + estimateHighlightedSize(highlightedHtml, cacheKey), ); } return result; From 26f0a62f73418d8a31ba1115dd3fb69c77ddf917 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:23:21 +0000 Subject: [PATCH 025/253] fix(acp): only approved execute requests let the agent open client terminals (#34526) Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- .../Adapters/AcpAdapterV2.test.ts | 33 ++++++++++++++++--- packages/provider-acp/src/server/adapter.ts | 7 ++-- .../src/server/clientPolicy.test.ts | 15 +++++---- .../provider-acp/src/server/clientPolicy.ts | 10 +++--- 4 files changed, 45 insertions(+), 20 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 05bed3c120263..fb51465629018 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -4708,7 +4708,25 @@ describe("AcpAdapterV2", () => { kind: "other", granted: false, }, - ] as const)("$label", ({ kind, granted }) => + { + label: "grants an explicit execute approval", + kind: "execute", + requestKind: "execute", + granted: true, + }, + { + label: "does not grant execution to an approved mode switch", + kind: "execute", + requestKind: "switch_mode", + granted: false, + }, + { + label: "does not grant execution to an approved explicit other tool", + kind: "other", + requestKind: "other", + granted: false, + }, + ] as const)("$label", ({ kind, granted, ...testCase }) => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -4795,7 +4813,10 @@ describe("AcpAdapterV2", () => { const permissionFiber = yield* requestPermission( { sessionId: "mock-session-1", - toolCall: { toolCallId: "tracked-tool-call" }, + toolCall: { + toolCallId: "tracked-tool-call", + ...("requestKind" in testCase ? { kind: testCase.requestKind } : {}), + }, options: [{ optionId: "allow-once", name: "Allow once", kind: "allow_once" }], }, { requestId: "id-only-permission-request", method: "session/request_permission" }, @@ -4837,8 +4858,12 @@ describe("AcpAdapterV2", () => { { requestId: "id-only-permission-terminal", method: "terminal/create" }, ).pipe(Effect.exit); assert.deepEqual( - { prompt: approval.prompt, terminalCreated: Exit.isSuccess(terminalExit) }, - { prompt: "git status", terminalCreated: granted }, + { + prompt: approval.prompt, + requestKind: approval.requestKind, + terminalCreated: Exit.isSuccess(terminalExit), + }, + { prompt: "git status", requestKind: "command", terminalCreated: granted }, ); yield* runtime.interruptTurn({ providerThread, providerTurnId }); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 2409c222f9ec9..8e33e346b479d 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -6660,12 +6660,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( !offeredOptions.some((option) => option.decision === "acceptForSession") ? "accept" : answered; - if ( - parsedPermission.kind !== "unknown" && - (decision === "accept" || decision === "acceptForSession") - ) { + if (decision === "accept" || decision === "acceptForSession") { clientPolicyGrants.recordApproval({ - kind: providerRequestKind(parsedPermission.kind), + toolKind: parsedPermission.kind, scope: decision === "acceptForSession" ? "session" : "turn", turnKey: String(context.providerTurnId), }); diff --git a/packages/provider-acp/src/server/clientPolicy.test.ts b/packages/provider-acp/src/server/clientPolicy.test.ts index 630ebc979e753..d093b3c85200d 100644 --- a/packages/provider-acp/src/server/clientPolicy.test.ts +++ b/packages/provider-acp/src/server/clientPolicy.test.ts @@ -319,12 +319,13 @@ describe("client terminal disposition", () => { }); describe("makeAcpClientPolicyGrants", () => { - it("grants terminals only from commands, never from an approved read or edit", () => { + it("grants terminals only from execute approvals, never from any other approved kind", () => { const grants = makeAcpClientPolicyGrants(); - grants.recordApproval({ kind: "file-read", scope: "turn", turnKey: "turn-1" }); - grants.recordApproval({ kind: "file-change", scope: "session", turnKey: "turn-1" }); + for (const toolKind of ["read", "edit", "switch_mode", "other", "unknown", "browse"]) { + grants.recordApproval({ toolKind, scope: "session", turnKey: "turn-1" }); + } assert.isFalse(grants.allowsExecute("turn-1")); - grants.recordApproval({ kind: "command", scope: "turn", turnKey: "turn-1" }); + grants.recordApproval({ toolKind: "execute", scope: "turn", turnKey: "turn-1" }); assert.isTrue(grants.allowsExecute("turn-1")); assert.isFalse(grants.allowsExecute("turn-2")); assert.isFalse(grants.allowsExecute(null)); @@ -332,15 +333,15 @@ describe("makeAcpClientPolicyGrants", () => { it("keeps accept-for-session command grants across turns", () => { const grants = makeAcpClientPolicyGrants(); - grants.recordApproval({ kind: "command", scope: "session", turnKey: "turn-1" }); + grants.recordApproval({ toolKind: "execute", scope: "session", turnKey: "turn-1" }); assert.isTrue(grants.allowsExecute("turn-9")); assert.isTrue(grants.allowsExecute(null)); }); it("drops a turn's command grant when a later turn approves one", () => { const grants = makeAcpClientPolicyGrants(); - grants.recordApproval({ kind: "command", scope: "turn", turnKey: "turn-1" }); - grants.recordApproval({ kind: "command", scope: "turn", turnKey: "turn-2" }); + grants.recordApproval({ toolKind: "execute", scope: "turn", turnKey: "turn-1" }); + grants.recordApproval({ toolKind: "execute", scope: "turn", turnKey: "turn-2" }); assert.isFalse(grants.allowsExecute("turn-1")); assert.isTrue(grants.allowsExecute("turn-2")); }); diff --git a/packages/provider-acp/src/server/clientPolicy.ts b/packages/provider-acp/src/server/clientPolicy.ts index 346936f193966..2add9197de2eb 100644 --- a/packages/provider-acp/src/server/clientPolicy.ts +++ b/packages/provider-acp/src/server/clientPolicy.ts @@ -1,5 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off -import type { ProviderRequestKind, RuntimeMode } from "@t3tools/contracts"; +import type { RuntimeMode } from "@t3tools/contracts"; import type * as EffectAcpSchema from "effect-acp/compat"; import * as NodeFS from "node:fs"; import * as NodePath from "node:path"; @@ -222,7 +222,8 @@ export function acpClientExecuteDisposition( } export interface AcpApprovalGrantInput { - readonly kind: ProviderRequestKind; + /** The approved request's ACP tool kind, after ID-only requests take their tracked call's kind. */ + readonly toolKind: string; readonly scope: "session" | "turn"; readonly turnKey: string; } @@ -232,13 +233,14 @@ export interface AcpClientPolicyGrants { readonly allowsExecute: (turnKey: string | null) => boolean; } -/** ACP cannot link commands to terminals; command approvals grant execution for the turn or accepted session. */ +/** ACP cannot link commands to terminals; approved execute requests grant execution for the turn or accepted session. */ export function makeAcpClientPolicyGrants(): AcpClientPolicyGrants { let sessionExecute = false; let turnExecute: string | null = null; return { recordApproval: (input) => { - if (input.kind !== "command") return; + // Other kinds also show as command cards, but approving them must not open terminals. + if (input.toolKind !== "execute") return; if (input.scope === "session") { sessionExecute = true; } else { From b9d9aab2349eff1a974294c4a259c8312721af78 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:23:59 +0000 Subject: [PATCH 026/253] fix(pi): long tool calls no longer share a session approval with different calls (#34528) Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- .../src/server/mcpBridge.testkit.ts | 2 ++ .../src/server/mcpExtensionSource.test.ts | 26 +++++++++++++++++++ .../src/server/mcpExtensionSource.ts | 12 +++++++-- 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/packages/provider-pi/src/server/mcpBridge.testkit.ts b/packages/provider-pi/src/server/mcpBridge.testkit.ts index 505abd4735ff9..98ef74bb862cc 100644 --- a/packages/provider-pi/src/server/mcpBridge.testkit.ts +++ b/packages/provider-pi/src/server/mcpBridge.testkit.ts @@ -1,4 +1,5 @@ // @effect-diagnostics nodeBuiltinImport:off -- Executes the shipped Pi extension at its native JavaScript boundary. +import * as NodeCrypto from "node:crypto"; import * as NodeModule from "node:module"; import * as NodePath from "node:path"; import * as NodeVM from "node:vm"; @@ -95,6 +96,7 @@ export async function loadMcpBridge( }, }, AbortSignal, + NodeCrypto, NodePath, Type: { Unsafe: (schema: unknown) => schema }, fetch: async ( diff --git a/packages/provider-pi/src/server/mcpExtensionSource.test.ts b/packages/provider-pi/src/server/mcpExtensionSource.test.ts index 1e2ac44cf4b5c..c4119157a0175 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.test.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.test.ts @@ -400,6 +400,32 @@ describe("Pi tool discovery permissions", () => { assert.equal(replaced?.block, true); assert.equal(confirmations.at(-1), "Allow tool_search?"); }); + + it("gives long inputs that differ past the shown text different confirmation details", async () => { + const bridge = await loadMcpBridge({ runtimeMode: "approval-required" }); + const hook = bridge.handlers.get("tool_call") as unknown as ( + event: { toolName: string; input: unknown }, + ctx: { ui: { confirm: (title: string, detail: string) => Promise } }, + ) => Promise<{ block: true; reason: string } | undefined>; + const details: string[] = []; + const ctx = { + ui: { + confirm: async (_title: string, detail: string) => { + details.push(detail); + return true; + }, + }, + }; + const filler = "a".repeat(4_100); + await hook({ toolName: "bash", input: { command: filler + "\necho one" } }, ctx); + await hook({ toolName: "bash", input: { command: filler + "\necho two" } }, ctx); + await hook({ toolName: "bash", input: { command: "ls" } }, ctx); + const [first, second, short] = details; + assert.equal(first!.slice(0, 4_000), second!.slice(0, 4_000)); + assert.notEqual(first, second); + assert.match(first!, /\n\.\.\. \d+ more characters not shown \(sha256 [0-9a-f]{64}\)$/); + assert.equal(short, JSON.stringify({ command: "ls" }, null, 2)); + }); }); async function loadRequestHook() { diff --git a/packages/provider-pi/src/server/mcpExtensionSource.ts b/packages/provider-pi/src/server/mcpExtensionSource.ts index c63e60feb9e47..48aeff24370de 100644 --- a/packages/provider-pi/src/server/mcpExtensionSource.ts +++ b/packages/provider-pi/src/server/mcpExtensionSource.ts @@ -14,6 +14,7 @@ export const PI_FILE_CHANGE_TOOLS = ["edit", "write"] as const; export const PI_T3_MCP_EXTENSION_SOURCE = `\ import { stripFrontmatter, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent"; +import * as NodeCrypto from "node:crypto"; import * as NodeFSP from "node:fs/promises"; import * as NodePath from "node:path"; import { Type } from "typebox"; @@ -61,12 +62,19 @@ function runtimeMode(): RuntimeMode { : "full-access"; } +// T3 keys "Always allow this session" on this text, so a cut summary ends with the +// full input's hash: calls that differ only past the cut get separate grants. function toolInputSummary(input: unknown): string { + let text: string; try { - return JSON.stringify(input, null, 2).slice(0, 4_000); + text = JSON.stringify(input, null, 2) ?? String(input); } catch { - return String(input).slice(0, 4_000); + text = String(input); } + if (text.length <= 4_000) return text; + const hash = NodeCrypto.createHash("sha256").update(text, "utf16le").digest("hex"); + return text.slice(0, 4_000) + "\\n... " + (text.length - 4_000) + + " more characters not shown (sha256 " + hash + ")"; } function parseSseOrJson(body: string, contentType: string): JsonRpcResponse { From 35557e648f8db1dbd27f4dfc504c4ea45003a586 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:24:25 +0000 Subject: [PATCH 027/253] fix(cli): thread, project, and connect commands skip a server that is gone (#34529) Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- apps/server/src/cli/connect.test.ts | 42 ++++++++++++++++++++++----- apps/server/src/cli/connect.ts | 8 +++-- apps/server/src/cli/project.test.ts | 31 ++++++++++++++++++++ apps/server/src/cli/project.ts | 4 +-- apps/server/src/cli/thread.test.ts | 39 +++++++++++++++++++++++++ apps/server/src/cli/thread.ts | 4 +-- apps/server/src/serverRuntimeState.ts | 13 +++++++++ 7 files changed, 128 insertions(+), 13 deletions(-) diff --git a/apps/server/src/cli/connect.test.ts b/apps/server/src/cli/connect.test.ts index a524ab8ddea52..2e91c079f161f 100644 --- a/apps/server/src/cli/connect.test.ts +++ b/apps/server/src/cli/connect.test.ts @@ -16,6 +16,7 @@ import * as TestConsole from "effect/testing/TestConsole"; import { Command } from "effect/cli"; import { makeCli } from "../binCli.ts"; +import { CLOUD_CLI_DESIRED_LINK_SECRET } from "../cloud/CliState.ts"; import { makePersistedServerRuntimeState, persistServerRuntimeState, @@ -59,9 +60,12 @@ it.effect("does not install the relay client when the user declines the managed ); it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer))( - "t3 connect unlink", + "t3 connect unlink and status", (it) => { - const runUnlink = (recordedPid: number, options?: { readonly portFreed?: boolean }) => + const runConnect = ( + recordedPid: number, + options?: { readonly portFreed?: boolean; readonly command?: "unlink" | "status" }, + ) => Effect.gen(function* () { const requests: Array = []; const warnings: Array = []; @@ -96,10 +100,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) path: `${baseDir}/userdata/server-runtime.json`, state: { ...state, pid: recordedPid }, }); + if (options?.command === "status") { + // Status asks the server for reachability only for a managed link. + yield* fs.makeDirectory(`${baseDir}/userdata/secrets`, { recursive: true }); + yield* fs.writeFileString( + `${baseDir}/userdata/secrets/${CLOUD_CLI_DESIRED_LINK_SECRET}.bin`, + "managed", + ); + } yield* Command.runWith(makeCli({ cloudEnabled: true }), { version: "0.0.0" })([ "connect", - "unlink", + options?.command ?? "unlink", "--base-dir", baseDir, ]).pipe( @@ -128,7 +140,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) it.effect("does not tell the user to restart a server that is gone", () => Effect.gen(function* () { - const { printed, warnings } = yield* runUnlink(deadPid, { portFreed: true }); + const { printed, warnings } = yield* runConnect(deadPid, { portFreed: true }); assert.include(printed, "T3 Connect is disabled locally."); assert.notInclude(warnings.join("\n"), "Restart that server"); @@ -137,7 +149,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) it.effect("warns that a server that is gone may have left its connector running", () => Effect.gen(function* () { - const { warnings } = yield* runUnlink(deadPid, { portFreed: true }); + const { warnings } = yield* runConnect(deadPid, { portFreed: true }); assert.include(warnings.join("\n"), "its cloudflared process may still be running"); }), @@ -145,15 +157,31 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer, NetService.layer)) it.effect("does not send a token to whatever took over a dead server's port", () => Effect.gen(function* () { - const { requests } = yield* runUnlink(deadPid); + const { requests } = yield* runConnect(deadPid); + + assert.deepEqual(requests, []); + }), + ); + + it.effect("status does not send a token to whatever took over a dead server's port", () => + Effect.gen(function* () { + const { requests } = yield* runConnect(deadPid, { command: "status" }); assert.deepEqual(requests, []); }), ); + it.effect("status asks a running server to check reachability", () => + Effect.gen(function* () { + const { requests } = yield* runConnect(process.pid, { command: "status" }); + + assert.deepEqual(requests, ["POST /api/connect/reachability"]); + }), + ); + it.effect("asks a running server to stop its tunnel", () => Effect.gen(function* () { - const { requests, printed, warnings } = yield* runUnlink(process.pid); + const { requests, printed, warnings } = yield* runConnect(process.pid); assert.deepEqual(requests, ["POST /api/connect/unlink"]); assert.include(printed, "T3 Connect is disabled locally."); diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts index 5145429e304d4..f95da6326a35f 100644 --- a/apps/server/src/cli/connect.ts +++ b/apps/server/src/cli/connect.ts @@ -50,7 +50,11 @@ import * as RelayTracing from "../cloud/relayTracing.ts"; import * as ServerConfig from "../config.ts"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ExternalLauncher from "../process/externalLauncher.ts"; -import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { + isProcessAlive, + readLiveServerRuntimeState, + readPersistedServerRuntimeState, +} from "../serverRuntimeState.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; import { resolveCliCommand } from "./invocation.ts"; import * as CliService from "./service.ts"; @@ -339,7 +343,7 @@ const CLOUD_CLI_REACHABILITY_RETRY = Duration.seconds(5); /** Asks the running server to check T3 Connect now. `null` when no server answers. */ const checkLiveReachability = Effect.fn("cloud.cli.check_live_reachability")(function* () { const config = yield* ServerConfig.ServerConfig; - const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath); + const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath); if (Option.isNone(runtimeState)) return null; const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; return yield* withCloudCliSessionToken(environmentAuth, AuthRelayReadScope, (token) => diff --git a/apps/server/src/cli/project.test.ts b/apps/server/src/cli/project.test.ts index 035b7d7e6f710..407905815f434 100644 --- a/apps/server/src/cli/project.test.ts +++ b/apps/server/src/cli/project.test.ts @@ -194,6 +194,37 @@ it.effect.each(["snapshot", "mutation"] as const)( }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), ); +it.effect("does not send a token to whatever took over a dead server's port", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-dead-project-cli-" }); + const baseDir = NodePath.join(root, "state"); + const workspaceRoot = NodePath.join(root, "workspace"); + yield* fs.makeDirectory(workspaceRoot); + const state = yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3_773, + }); + yield* persistServerRuntimeState({ + path: NodePath.join(baseDir, "userdata", "server-runtime.json"), + // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it. + state: { ...state, pid: 4_194_305 }, + }); + let requests = 0; + const fetch: typeof globalThis.fetch = async () => { + requests++; + return Response.json({ projects: [], updatedAt: "2026-01-01T00:00:00.000Z" }); + }; + + yield* runCli(["project", "add", workspaceRoot, "--base-dir", baseDir]).pipe( + Effect.provideService(FetchHttpClient.Fetch, fetch), + ); + + assert.equal(requests, 0); + assert.equal((yield* readProjects(baseDir)).projects[0]?.workspaceRoot, workspaceRoot); + }).pipe(Effect.provide(NodeServices.layer), Effect.scoped), +); + const makeProjectLookupFixture = Effect.fn("ProjectCliTest.makeProjectLookupFixture")(function* () { const fs = yield* FileSystem.FileSystem; const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-project-lookup-" }); diff --git a/apps/server/src/cli/project.ts b/apps/server/src/cli/project.ts index 14d3aeeedb50a..da63d65975ae5 100644 --- a/apps/server/src/cli/project.ts +++ b/apps/server/src/cli/project.ts @@ -39,7 +39,7 @@ import * as ServerSettings from "../serverSettings.ts"; import * as ManagedPolicy from "../policy/ManagedPolicy.ts"; import { clearPersistedServerRuntimeState, - readPersistedServerRuntimeState, + readLiveServerRuntimeState, } from "../serverRuntimeState.ts"; import * as WorkspacePaths from "../workspace/WorkspacePaths.ts"; import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; @@ -360,7 +360,7 @@ const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecu environmentAuth: EnvironmentAuth.EnvironmentAuth["Service"], config: ServerConfig.ServerConfig["Service"], ) { - const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath); + const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath); if (Option.isNone(runtimeState)) { return Option.none<{ readonly origin: string }>(); } diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index 42a4a3e5c8455..5ab4e24d0a8e1 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -136,6 +136,45 @@ it.effect( ), ); +it.effect("does not sign in to whatever took over a dead server's port", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-thread-dead-server-" }); + const state = yield* makePersistedServerRuntimeState({ + config: { host: "127.0.0.1", devUrl: undefined }, + port: 3_773, + }); + yield* persistServerRuntimeState({ + path: path.join(baseDir, "userdata", "server-runtime.json"), + // Above Linux's PID ceiling, as in pair.test.ts: no process can hold it. + state: { ...state, pid: 4_194_305 }, + }); + using session = vi + .spyOn(McpBridge, "mcpToolSession") + .mockReturnValue(Effect.die("no session should open")); + + const error = yield* Command.runWith(threadCommand, { version: "0.0.0" })([ + "list", + "--base-dir", + baseDir, + ]).pipe(Effect.flip); + + assert.strictEqual(error._tag, "ThreadServerNotRunningError"); + assert.strictEqual(session.mock.calls.length, 0); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + NetService.layer, + ConfigProvider.layer(ConfigProvider.fromEnv({ env: { T3CODE_PORT: "3773" } })), + ), + ), + ), +); + /** Answers each tool call with the next scripted response for that tool. */ const scriptedTools = (script: Record>) => { const calls: Array<{ readonly tool: string; readonly args: unknown }> = []; diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index b71d65058301f..53b7df74be2d4 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -31,7 +31,7 @@ import * as ServerConfig from "../config.ts"; import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts"; import { expandHomePath } from "../os-jank.ts"; import * as ProcessRunner from "../processRunner.ts"; -import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { readLiveServerRuntimeState } from "../serverRuntimeState.ts"; import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts"; /** @@ -211,7 +211,7 @@ const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* + readPersistedServerRuntimeState(path).pipe( + Effect.map(Option.filter((state) => isProcessAlive(state.pid))), + ), +); From 9c7f6ebf315883fdd7f76fad45ca623c15caaefc Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:24:53 +0000 Subject: [PATCH 028/253] fix(server): file metadata lookups skip the server's own state files (#34530) Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- apps/server/src/workspace/WorkspaceFileSystem.test.ts | 8 ++++++++ apps/server/src/workspace/WorkspaceFileSystem.ts | 3 ++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/apps/server/src/workspace/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/WorkspaceFileSystem.test.ts index 3306e420b35c5..26e444c1032d6 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.test.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.test.ts @@ -290,6 +290,14 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceFileSystemLive", (i const error = yield* workspaceFileSystem.readFile(input).pipe(Effect.flip); expect(error).toBeInstanceOf(WorkspacePaths.WorkspacePathOutsideRootError); } + const metadata = yield* workspaceFileSystem.getMetadata({ + paths: [ + path.join(config.secretsDir, "example.bin"), + path.join(config.stateDir, "statev2.sqlite"), + config.stateDir, + ], + }); + expect(metadata.entries).toEqual([null, null, { kind: "directory" }]); }), ); diff --git a/apps/server/src/workspace/WorkspaceFileSystem.ts b/apps/server/src/workspace/WorkspaceFileSystem.ts index 489fedc2dce09..2f3823f97e477 100644 --- a/apps/server/src/workspace/WorkspaceFileSystem.ts +++ b/apps/server/src/workspace/WorkspaceFileSystem.ts @@ -148,7 +148,8 @@ export const make = Effect.gen(function* () { // path makes Windows sign in to its host with the user's NTLM credentials. if (!path.isAbsolute(expandedPath) || isNetworkPath(expandedPath)) return null; const stat = yield* fileSystem.stat(expandedPath).pipe(Effect.option); - if (stat._tag === "None") return null; + // Server state files answer like missing paths, as readFile refuses them. + if (stat._tag === "None" || (yield* isServerInternalPath(expandedPath))) return null; if (stat.value.type === "Directory") return { kind: "directory" } as const; if (stat.value.type !== "File") return { kind: "other" } as const; let mimeType: string | undefined; From 8df455c09bf153433f65e45eb548a478c39655f8 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:26:06 +0000 Subject: [PATCH 029/253] fix(acp-registry): ACP Registry installs only change the mode of a contained command (#34531) Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- .../src/server/AcpRegistrySupport.test.ts | 66 +++++++++++++++++++ .../src/server/AcpRegistrySupport.ts | 8 ++- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index d2c335cefd0dd..c0716f802909c 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -839,6 +839,72 @@ describe("AcpRegistrySupport", () => { ); }); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "leaves the mode of a file outside the install root when the command links to it", + () => { + const downloadUrl = "https://registry.test/agent.tar.gz"; + const agent = makeAgent({ + binary: { "linux-x86_64": { archive: downloadUrl, cmd: "./agent" } }, + }); + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-acp-outside-link-", + }); + const outsideFile = `${cacheDir}/outside`; + yield* fileSystem.writeFileString(outsideFile, "private\n"); + yield* fileSystem.chmod(outsideFile, 0o600); + const source = `${cacheDir}/source`; + yield* fileSystem.makeDirectory(source); + yield* fileSystem.symlink(outsideFile, `${source}/agent`); + const archivePath = `${cacheDir}/agent.tar.gz`; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const tar = yield* spawner.spawn( + ChildProcess.make("tar", ["-czf", archivePath, "-C", source, "agent"]), + ); + expect(yield* tar.exitCode).toBe(0); + const archive = yield* fileSystem.readFile(archivePath); + const resolver = yield* AcpRegistrySupport.makeAcpRegistryCatalog({ + cacheDir, + toolsDir: `${cacheDir}/tools`, + registryUrl, + }).pipe( + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + request.url === registryUrl + ? new Response(makeRegistry(agent)) + : new Response(archive), + ), + ), + ), + ), + ); + + const error = yield* resolver.prepare({ agentId: agent.id }).pipe(Effect.flip); + + expect(error.reason).toBe("archive_invalid"); + expect((yield* fileSystem.stat(outsideFile)).mode & 0o777).toBe(0o600); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + TestProviderHost.layer().pipe( + Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), + ), + ), + ), + Effect.provideService(HostProcess.Platform, "linux"), + Effect.provideService(HostProcess.Architecture, "x64"), + ); + }, + ); + it.effect("searches compatible agents with deterministic ranking and bounded metadata", () => { const exact = { ...makeAgent({ npx: { package: "@example/acp@1.2.3" } }), diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 8cff2a3cbf40b..cff335418cd64 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -1356,6 +1356,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const assertExecutableInRoot = Effect.fn("AcpRegistryCatalog.assertExecutableInRoot")(function* ( root: string, executablePath: string, + options?: { readonly makeExecutable?: boolean }, ) { const rootRealPath = yield* fileSystem.realPath(root); const executableRealPath = yield* fileSystem.realPath(executablePath); @@ -1366,6 +1367,10 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct detail: "ACP Registry archive command resolves outside its installation directory.", }); } + // chmod follows symlinks, so only change the mode once the real path is known to be inside. + if (options?.makeExecutable && platform !== "win32") { + yield* fileSystem.chmod(executableRealPath, 0o755); + } const info = yield* fileSystem.stat(executableRealPath); const hasExecutableMode = platform === "win32" || (info.mode & 0o111) !== 0; if (info.type !== "File" || !hasExecutableMode) { @@ -1595,8 +1600,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct detail: `ACP Registry archive for ${agent.id} did not contain '${target.cmd}'.`, }); } - if (platform !== "win32") yield* fileSystem.chmod(stagedExecutable, 0o755); - yield* assertExecutableInRoot(extractionRoot, stagedExecutable); + yield* assertExecutableInRoot(extractionRoot, stagedExecutable, { makeExecutable: true }); yield* fileSystem.remove(installRoot, { recursive: true, force: true }); yield* fileSystem.rename(extractionRoot, installRoot); return yield* assertExecutableInRoot(installRoot, executablePath); From 76b3e3390e2fdb824a3afbc7e6b5300cfec7a6b3 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:26:58 +0000 Subject: [PATCH 030/253] fix(server): MCP tokens still expire after the clock steps back (#34532) Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- .../server/src/mcp/McpSessionRegistry.test.ts | 40 ++++++++++++++- apps/server/src/mcp/McpSessionRegistry.ts | 49 ++++++++++++++----- 2 files changed, 76 insertions(+), 13 deletions(-) diff --git a/apps/server/src/mcp/McpSessionRegistry.test.ts b/apps/server/src/mcp/McpSessionRegistry.test.ts index 50d2b6d74b5cd..457679f87de71 100644 --- a/apps/server/src/mcp/McpSessionRegistry.test.ts +++ b/apps/server/src/mcp/McpSessionRegistry.test.ts @@ -6,6 +6,7 @@ import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts" import * as Effect from "effect/Effect"; import { HttpServer } from "effect/http"; import * as NetAddress from "effect/net/NetAddress"; +import * as TestClock from "effect/testing/TestClock"; import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as McpSessionRegistry from "./McpSessionRegistry.ts"; @@ -22,10 +23,11 @@ const fakeEnvironment = ServerEnvironment.ServerEnvironment.of({ getDescriptor: Effect.die("unused"), }); -const makeRegistry = (now: () => number, httpServer = fakeHttpServer) => +// Without `now`, the registry reads the Effect Clock (TestClock in these tests). +const makeRegistry = (now: (() => number) | undefined, httpServer = fakeHttpServer) => McpSessionRegistry.__testing .make({ - now, + ...(now ? { now } : {}), livenessWindowMs: 100, }) .pipe( @@ -139,6 +141,40 @@ it.effect("expires credentials once their session stops showing signs of life", const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, ""); timestamp += 101; expect(yield* registry.resolve(token)).toBeUndefined(); + // Once a request found it expired, clocks moving back don't bring it back; a provider turn does. + timestamp = 1_000; + expect(yield* registry.resolve(token)).toBeUndefined(); + yield* registry.touch(ThreadId.make("thread-2")); + expect((yield* registry.resolve(token))?.thread.threadId).toBe("thread-2"); + }), +); + +it.effect("a backward wall clock step neither extends nor revives credentials", () => + Effect.gen(function* () { + const registry = yield* makeRegistry(undefined); + const issueToken = (threadId: string) => + registry + .issue({ + threadId: ThreadId.make(threadId), + providerInstanceId: ProviderInstanceId.make("codex"), + capabilities: new Set(["preview"]), + }) + .pipe(Effect.map((issued) => issued.config.authorizationHeader.replace(/^Bearer\s+/, ""))); + + yield* TestClock.setTime(10_000); + const extended = yield* issueToken("thread-extended"); + // setTime backwards moves wall time only; adjust moves both clocks. + yield* TestClock.setTime(1_000); + yield* TestClock.adjust(101); + expect(yield* registry.resolve(extended)).toBeUndefined(); + + const revived = yield* issueToken("thread-revived"); + yield* TestClock.adjust(101); + expect(yield* registry.resolve(revived)).toBeUndefined(); + const active = yield* issueToken("thread-active"); + yield* TestClock.setTime(0); + expect(yield* registry.resolve(revived)).toBeUndefined(); + expect((yield* registry.resolve(active))?.thread.threadId).toBe("thread-active"); }), ); diff --git a/apps/server/src/mcp/McpSessionRegistry.ts b/apps/server/src/mcp/McpSessionRegistry.ts index 80dc4936c677b..ebc8ed74b9385 100644 --- a/apps/server/src/mcp/McpSessionRegistry.ts +++ b/apps/server/src/mcp/McpSessionRegistry.ts @@ -42,10 +42,17 @@ export class McpSessionRegistry extends Context.Service< McpSessionRegistryShape >()("t3/mcp/McpSessionRegistry") {} +interface AliveMark { + readonly wallMs: number; + readonly monotonicMs: number; +} + interface CredentialRecord { readonly tokenHash: string; readonly scope: McpInvocationContext.McpThreadInvocationScope; - readonly lastAliveAt: number; + readonly lastAlive: AliveMark; + /** Set when a request finds the token idle; only `touch` clears it, whatever the clocks do. */ + readonly expired: boolean; } interface RegistryState { @@ -54,6 +61,7 @@ interface RegistryState { export interface McpSessionRegistryOptions { readonly livenessWindowMs?: number; + /** Drives both the wall and monotonic readings. */ readonly now?: () => number; } @@ -69,6 +77,11 @@ const bytesToHex = (bytes: Uint8Array): string => const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url"); +// The larger elapsed reading wins: stepping the wall clock back cannot extend a token, +// and wall time that passes while the host sleeps still counts. +const idleMs = (since: AliveMark, now: AliveMark): number => + Math.max(now.wallMs - since.wallMs, now.monotonicMs - since.monotonicMs); + const getHttpMcpEndpointHost = (address: NetAddress.IpAddress): string => NetAddress.isUnspecified(address) ? "127.0.0.1" @@ -83,7 +96,18 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( const environmentId = yield* environment.getEnvironmentId; const httpServer = yield* HttpServer.HttpServer; const state = yield* SynchronizedRef.make({ records: new Map() }); - const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis; + const { now } = options; + const currentAliveMark: Effect.Effect = now + ? Effect.sync(() => { + const timestamp = now(); + return { wallMs: timestamp, monotonicMs: timestamp }; + }) + : Effect.all({ + wallMs: Clock.currentTimeMillis, + monotonicMs: Clock.monotonicTimeNanos.pipe( + Effect.map((nanos) => Number(nanos / 1_000_000n)), + ), + }); const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS; const endpoint = NetAddress.isInetAddress(httpServer.address) ? `http://${getHttpMcpEndpointHost(httpServer.address.address)}:${httpServer.address.port}/mcp` @@ -96,7 +120,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")( function* (request) { - const issuedAt = yield* currentTimeMillis; + const issuedAlive = yield* currentAliveMark; const providerSessionId = yield* random.uuidV4(); const rawToken = yield* random.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie); const tokenHash = yield* hashToken(rawToken); @@ -117,11 +141,11 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( "pull-requests", ...(request.capabilities ?? (browserToolsAvailable ? (["preview"] as const) : [])), ]), - issuedAt, + issuedAt: issuedAlive.wallMs, }; yield* SynchronizedRef.update(state, ({ records }) => { const next = new Map(records); - next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt }); + next.set(tokenHash, { tokenHash, scope, lastAlive: issuedAlive, expired: false }); return { records: next }; }); return { @@ -143,14 +167,17 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( function* (rawToken) { if (rawToken.length === 0) return undefined; const tokenHash = yield* hashToken(rawToken); - const timestamp = yield* currentTimeMillis; + const alive = yield* currentAliveMark; return yield* SynchronizedRef.modify(state, ({ records }) => { const record = records.get(tokenHash); - if (!record || timestamp - record.lastAliveAt > livenessWindowMs) { - return [undefined, { records }] as const; + if (!record || record.expired) return [undefined, { records }] as const; + if (idleMs(record.lastAlive, alive) > livenessWindowMs) { + const next = new Map(records); + next.set(tokenHash, { ...record, expired: true }); + return [undefined, { records: next }] as const; } const next = new Map(records); - next.set(tokenHash, { ...record, lastAliveAt: timestamp }); + next.set(tokenHash, { ...record, lastAlive: alive }); return [record.scope, { records: next }] as const; }); }, @@ -158,12 +185,12 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* ( const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")( function* (threadId) { - const timestamp = yield* currentTimeMillis; + const alive = yield* currentAliveMark; yield* SynchronizedRef.update(state, ({ records }) => { const next = new Map(records); for (const [tokenHash, record] of records) { if (record.scope.thread.threadId === threadId) { - next.set(tokenHash, { ...record, lastAliveAt: timestamp }); + next.set(tokenHash, { ...record, lastAlive: alive, expired: false }); } } return { records: next }; From 2bcbdae06a495cd9faa9d216b765deb075ae7913 Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:27:53 +0000 Subject: [PATCH 031/253] fix(server): ChatGPT sign-in keeps listening after a stray callback request (#34533) Co-authored-by: maria-rcks <254055478+maria-rcks@users.noreply.github.com> --- .../src/provider/CodexChatGptAuth.test.ts | 16 ++++++++++++---- apps/server/src/provider/CodexChatGptAuth.ts | 17 ++++++++++++++--- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/apps/server/src/provider/CodexChatGptAuth.test.ts b/apps/server/src/provider/CodexChatGptAuth.test.ts index 4e84553dca26a..45ea557b00b5a 100644 --- a/apps/server/src/provider/CodexChatGptAuth.test.ts +++ b/apps/server/src/provider/CodexChatGptAuth.test.ts @@ -401,8 +401,8 @@ const makeHarnessFor = Effect.fnUntraced(function* ( setIdentityFailure: (value: "issuer" | "audience" | "signature") => { identityFailure = value; }, - mismatchCallbackState: () => { - mismatchedState = true; + mismatchCallbackState: (value = true) => { + mismatchedState = value; }, setCallbackClientId: (value: string) => { callbackClientId = value; @@ -871,16 +871,24 @@ it.effect( ), ); -it.effect("rejects mismatched callback state before any token exchange or credential write", () => +it.effect("rejects mismatched callback state and keeps waiting for the real redirect", () => provision( Effect.gen(function* () { const h = yield* makeHarness; h.mismatchCallbackState(); yield* h.signIn; - assert.include((yield* h.phase("failed")).message!, "could not be verified"); + assert.include(h.callbackResponses[0]!.body, "does not belong to the active sign-in"); assert.strictEqual(h.exchanges.length, 0); assert.deepEqual(h.storedRecords(), []); assert.isTrue(Option.isNone(yield* h.auth.read)); + h.mismatchCallbackState(false); + const waiting = yield* h.phase("waiting"); + const redirectUri = new URL(waiting.authorizationUrl!).searchParams.get("redirect_uri")!; + const unparsable = yield* Effect.promise(() => fetch(`${new URL(redirectUri).origin}//`)); + assert.strictEqual(unparsable.status, 404); + yield* h.finishCallback(waiting); + yield* h.phase("succeeded"); + assert.strictEqual(h.exchanges.length, 1); }), ), ); diff --git a/apps/server/src/provider/CodexChatGptAuth.ts b/apps/server/src/provider/CodexChatGptAuth.ts index ad06cdc001ae6..5be14a8a1a08f 100644 --- a/apps/server/src/provider/CodexChatGptAuth.ts +++ b/apps/server/src/provider/CodexChatGptAuth.ts @@ -549,9 +549,10 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* Effect.tryPromise({ try: () => new Promise((resolve, reject) => { + const callbackBase = "http://127.0.0.1/auth/callback"; const server = NodeHttp.createServer((request, response) => { - const url = new URL(request.url ?? "/", "http://127.0.0.1"); - if (request.method !== "GET" || url.pathname !== "/auth/callback") { + const url = URL.parse(request.url ?? "/", callbackBase); + if (request.method !== "GET" || url?.pathname !== "/auth/callback") { response.writeHead(404).end(); return; } @@ -559,8 +560,18 @@ export const makeCodexChatGptAuth = Effect.fn("makeCodexChatGptAuth")(function* response.writeHead(410).end("Sign-in is no longer active."); return; } + // Reject a stray request without ending the sign-in, so the real redirect still lands. + let returned: URL; + try { + returned = codexCallbackUrl(url.toString(), callbackBase, state); + } catch { + response + .writeHead(400) + .end("This response does not belong to the active sign-in."); + return; + } used = true; - callback.resolve({ url, response }); + callback.resolve({ url: returned, response }); }); server.once("error", reject); server.listen(0, "127.0.0.1", () => resolve(server)); From 3e90486b75c44fa06a1442efa175f2996a2f56da Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:28:40 -0800 Subject: [PATCH 032/253] fix(mobile): show and let users skip compaction before sending to stale Claude threads (#34482) --- .../src/features/threads/ThreadDetailScreen.tsx | 17 +++++++++++++---- .../src/state/thread-task-permissions.test.ts | 16 ++++++++++++---- .../src/state/use-thread-composer-state.ts | 5 +++-- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 45d2aad72e428..3e7eec1449e26 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -249,7 +249,8 @@ export interface ThreadDetailScreenProps { /** Set while the next send compacts the thread first. */ readonly compactBeforeSend?: { readonly tokens: number; - readonly keepFullHistory: () => void; + readonly keepFullHistory: boolean; + readonly toggleKeepFullHistory: () => void; } | null; readonly creationState: | { @@ -1691,11 +1692,19 @@ function ThreadDetailBody( {props.compactBeforeSend ? ( ) : null} diff --git a/apps/mobile/src/state/thread-task-permissions.test.ts b/apps/mobile/src/state/thread-task-permissions.test.ts index 3b43a1451eb41..d037ac106a025 100644 --- a/apps/mobile/src/state/thread-task-permissions.test.ts +++ b/apps/mobile/src/state/thread-task-permissions.test.ts @@ -346,15 +346,23 @@ describe("mobile task permissions", () => { expect.not.objectContaining({ compactBeforeSend: true }), ); state.draft = { ...state.draft, modelSelection: undefined }; - composer.compactBeforeSend?.keepFullHistory(); + composer.compactBeforeSend?.toggleKeepFullHistory(); const kept = useThreadComposerState(NO_SIDE_CHATS); - expect(kept.compactBeforeSend).toBeNull(); - await kept.onSendMessage(); + expect(kept.compactBeforeSend?.keepFullHistory).toBe(true); + kept.compactBeforeSend?.toggleKeepFullHistory(); + const compactAgain = useThreadComposerState(NO_SIDE_CHATS); + expect(compactAgain.compactBeforeSend?.keepFullHistory).toBe(false); + await compactAgain.onSendMessage(); + expect(state.enqueue).toHaveBeenLastCalledWith( + expect.objectContaining({ compactBeforeSend: true }), + ); + compactAgain.compactBeforeSend?.toggleKeepFullHistory(); + await useThreadComposerState(NO_SIDE_CHATS).onSendMessage(); expect(state.enqueue).toHaveBeenLastCalledWith( expect.not.objectContaining({ compactBeforeSend: true }), ); // Keeping covers one send, as on web. - expect(useThreadComposerState(NO_SIDE_CHATS).compactBeforeSend?.tokens).toBe(248_000); + expect(useThreadComposerState(NO_SIDE_CHATS).compactBeforeSend?.keepFullHistory).toBe(false); state.freshPending = true; await composer.onSendMessage(); expect(state.enqueue).toHaveBeenLastCalledWith( diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 896adc53f5203..8a762e88c97c6 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -892,11 +892,12 @@ export function useThreadComposerState(input: { providerSubagentStatus, isCompacting, compactBeforeSend: - compactTokens === null || selectedThreadKey === null || keepFullHistory + compactTokens === null || selectedThreadKey === null ? null : { tokens: compactTokens, - keepFullHistory: () => setKeepFullHistory(selectedThreadKey, true), + keepFullHistory, + toggleKeepFullHistory: () => setKeepFullHistory(selectedThreadKey, !keepFullHistory), }, composerDraftKey, followUpBehavior, From 1c65ad032ebc826b71f4d43e733df01de1419d2f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:28:52 -0800 Subject: [PATCH 033/253] fix(web): Cmd+A in the rendered Markdown preview selects only the file (#30738) --- .../files/FilePreviewPanel.browser.test.tsx | 32 +++++++++++++++++-- .../src/components/files/FilePreviewPanel.tsx | 32 +++++++++++++++++-- 2 files changed, 58 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index a0e292d41afa8..4ee9011dad47d 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -121,11 +121,11 @@ function setup() { }; } -function markdownPreview(truncated: boolean) { +function markdownPreview(truncated: boolean, contents = "- [ ] Keep the rest of this file\n") { state.file = { relativePath: "tasks.md", - contents: "- [ ] Keep the rest of this file\n", - byteLength: truncated ? 1_200_000 : 32, + contents, + byteLength: truncated ? 1_200_000 : contents.length, truncated, }; return filePreview("tasks.md"); @@ -278,3 +278,29 @@ describe("rendered Markdown task saves", () => { }); }); }); + +describe("rendered Markdown select all", () => { + it("selects only the rendered file, including after a task toggle", async () => { + using _settings = setup(); + await using screen = await render( + <> +

Transcript text from the chat thread.

+ {markdownPreview(false, "- [ ] Task item\n\nRendered file body.\n")} + , + ); + const expectFileOnlySelection = async () => { + await userEvent.keyboard( + isMacPlatform(navigator.platform) ? "{Meta>}a{/Meta}" : "{Control>}a{/Control}", + ); + const selection = window.getSelection()?.toString() ?? ""; + expect(selection).toContain("Rendered file body."); + expect(selection).not.toContain("Transcript text from the chat thread."); + }; + + await userEvent.click(screen.getByText("Rendered file body.")); + await expectFileOnlySelection(); + // A toggled checkbox keeps focus on an input inside the preview. + await userEvent.click(screen.getByRole("checkbox")); + await expectFileOnlySelection(); + }); +}); diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 43bf1dc864996..0ec8e94facc92 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -47,7 +47,14 @@ import { import { mediaFileReference } from "@t3tools/client-runtime/media-reference"; import { FolderTree, Globe2, WrapTextIcon } from "lucide-react"; import * as Schema from "effect/Schema"; -import { lazy, Suspense, useEffect, useRef, useState } from "react"; +import { + lazy, + Suspense, + useEffect, + useRef, + useState, + type KeyboardEvent as ReactKeyboardEvent, +} from "react"; import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; @@ -61,7 +68,7 @@ import { useStableCallback } from "~/hooks/useStableCallback"; import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage"; import { resolveDiffThemeName } from "~/lib/diffRendering"; import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting"; -import { cn } from "~/lib/utils"; +import { cn, isMacPlatform } from "~/lib/utils"; import { requestWorkspaceFocus } from "~/lib/workspaceFocus"; import type { ChatFileAttachment } from "~/types"; import { isHostPath } from "@t3tools/shared/path"; @@ -933,6 +940,25 @@ function EditableFileSurface({ ); } +function selectRenderedContentOnSelectAll(event: ReactKeyboardEvent) { + const mac = isMacPlatform(navigator.platform); + const selectAll = + event.key.toLowerCase() === "a" && + (mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey) && + !event.shiftKey && + !event.altKey; + // React bubbles keys from portaled children (the image dialog) through this surface. + if ( + !selectAll || + !(event.target instanceof Node) || + !event.currentTarget.contains(event.target) + ) { + return; + } + event.preventDefault(); + window.getSelection()?.selectAllChildren(event.currentTarget); +} + function RenderedMarkdownSurface({ environmentId, cwd, @@ -960,7 +986,7 @@ function RenderedMarkdownSurface({ useFileSaveSession(saveTarget, onPendingChange); return ( - + Date: Wed, 11 Nov 2026 16:32:30 -0800 Subject: [PATCH 034/253] fix(web): don't offer VS Code on iPad, iPhone and Android browsers (#27557) --- .../chat/OpenInPicker.browser.test.tsx | 19 +++++++++ apps/web/src/components/chat/OpenInPicker.tsx | 11 ++++- apps/web/src/connection/clientMetadata.ts | 4 +- apps/web/src/remoteOpen.test.ts | 42 ++++++++++++++++++- apps/web/src/remoteOpen.ts | 9 +++- 5 files changed, 79 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx index 684db30988f3e..da9d7d50a5396 100644 --- a/apps/web/src/components/chat/OpenInPicker.browser.test.tsx +++ b/apps/web/src/components/chat/OpenInPicker.browser.test.tsx @@ -202,6 +202,25 @@ describe("remote editor links", () => { expect(state.openUrl).toHaveBeenCalledWith(expect.stringContaining("ssh-remote+sol")); expect(state.run).not.toHaveBeenCalled(); }); + + it("explains why a phone or tablet browser has no editor to open", async () => { + await using fixture = await setup(); + const { renderPicker, byLabel, primaryButton, menuItems, click, pressOpenFavorite } = fixture; + state.remote = { mode: "remote-links", host: { kind: "ssh-alias", host: "sol" } }; + state.clientEditors = []; + await renderPicker(); + + expect(primaryButton().disabled).toBe(true); + expect((await pressOpenFavorite()).defaultPrevented).toBe(false); + await click(byLabel("Choose editor")); + await vi.waitFor(() => + expect(menuItems().map((item) => item.textContent)).toEqual([ + "Open from a computer to edit on Test host", + ]), + ); + expect(menuItems()[0]!.getAttribute("aria-disabled")).toBe("true"); + expect(state.openUrl).not.toHaveBeenCalled(); + }); }); describe("open in editor announcement", () => { diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index a19491adcd15e..3375fd7f60ea9 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -286,11 +286,18 @@ export const OpenInPicker = memo(function OpenInPicker({ const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null; const primaryLabel = isPanel ? `Open in ${primaryOption?.label ?? "editor"}` : "Open"; + const unavailableReason = + remote.mode === "remote-unavailable" + ? `No SSH route to ${environmentLabel}` + : remote.mode === "remote-links" && options.length === 0 + ? `Open from a computer to edit on ${environmentLabel}` + : null; + const editorItems = ( <> - {remote.mode === "remote-unavailable" ? ( + {unavailableReason !== null ? ( - No SSH route to {environmentLabel} + {unavailableReason} ) : ( <> diff --git a/apps/web/src/connection/clientMetadata.ts b/apps/web/src/connection/clientMetadata.ts index cdb7c9ab2d13c..6ebbdff51df1a 100644 --- a/apps/web/src/connection/clientMetadata.ts +++ b/apps/web/src/connection/clientMetadata.ts @@ -5,7 +5,7 @@ import type { DesktopBridge, } from "@t3tools/contracts"; -interface BrowserIdentity { +export interface BrowserIdentity { readonly userAgent: string; readonly platform: string; readonly maxTouchPoints: number; @@ -32,7 +32,7 @@ function isIpadosDesktopUserAgent(identity: BrowserIdentity): boolean { ); } -function browserClientOs(identity: BrowserIdentity): ClientOs { +export function browserClientOs(identity: BrowserIdentity): ClientOs { const userAgent = identity.userAgent; if (userAgent.trim() === "") return "unknown"; if (/iphone|ipad|ipod/i.test(userAgent) || isIpadosDesktopUserAgent(identity)) return "iOS"; diff --git a/apps/web/src/remoteOpen.test.ts b/apps/web/src/remoteOpen.test.ts index 19cd09142014d..12149f98af238 100644 --- a/apps/web/src/remoteOpen.test.ts +++ b/apps/web/src/remoteOpen.test.ts @@ -6,7 +6,7 @@ import { import { buildRemoteOpenUrl, EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { resolveRemoteOpenState } from "./remoteOpen"; +import { remoteFallbackEditors, resolveRemoteOpenState } from "./remoteOpen"; const environmentId = EnvironmentId.make("environment-1"); @@ -179,6 +179,46 @@ describe("resolveRemoteOpenState", () => { }); }); +describe("remoteFallbackEditors", () => { + it.each([ + { + // iPadOS Safari requests the desktop site with a Macintosh user agent by default. + device: "iPad with a desktop user agent", + userAgent: + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15", + platform: "MacIntel", + maxTouchPoints: 5, + }, + { + device: "iPhone", + userAgent: + "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1", + platform: "iPhone", + maxTouchPoints: 5, + }, + { + device: "Android phone", + userAgent: + "Mozilla/5.0 (Linux; Android 14; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36", + platform: "Linux armv81", + maxTouchPoints: 5, + }, + ])("offers no desktop editor for remote links on an $device", ({ device: _, ...identity }) => { + expect(remoteFallbackEditors(identity)).toEqual([]); + }); + + it("keeps the VS Code fallback for remote links on a Mac", () => { + expect( + remoteFallbackEditors({ + userAgent: + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15", + platform: "MacIntel", + maxTouchPoints: 0, + }), + ).toEqual(["vscode"]); + }); +}); + describe("buildRemoteOpenUrl", () => { it("roots Windows paths", () => { expect( diff --git a/apps/web/src/remoteOpen.ts b/apps/web/src/remoteOpen.ts index 5624169abd696..a62b203663f07 100644 --- a/apps/web/src/remoteOpen.ts +++ b/apps/web/src/remoteOpen.ts @@ -10,6 +10,7 @@ import * as Schema from "effect/Schema"; import { Atom } from "effect/reactivity"; import { useAtomValue } from "@effect/atom-react"; +import { browserClientOs, type BrowserIdentity } from "~/connection/clientMetadata"; import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal"; import { isLoopbackHostname } from "~/environments/primary/target"; import { useLocalStorage } from "~/hooks/useLocalStorage"; @@ -149,6 +150,12 @@ export function useRemoteOpenState(environmentId: EnvironmentId | null): RemoteO const REMOTE_FALLBACK_EDITORS: ReadonlyArray = ["vscode"]; +// Phone and tablet browsers have no desktop editor to receive a vscode:// remote link. +export function remoteFallbackEditors(identity: BrowserIdentity): ReadonlyArray { + const os = browserClientOs(identity); + return os === "iOS" || os === "Android" ? [] : REMOTE_FALLBACK_EDITORS; +} + // Probed once per page: installed editors rarely change, and the probe spawns processes. const remoteCapableEditorsAtom = Atom.make((get): ReadonlyArray => { const probe = window.desktopBridge?.probeRemoteEditors; @@ -159,7 +166,7 @@ const remoteCapableEditorsAtom = Atom.make((get): ReadonlyArray => { }, () => undefined, ); - return REMOTE_FALLBACK_EDITORS; + return remoteFallbackEditors(navigator); }).pipe(Atom.keepAlive, Atom.withLabel("remote-capable-editors")); export function useRemoteCapableEditors(): ReadonlyArray { From 1c3d5f7e82644ce847033a0c82d9b9c8253ebc07 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:37:43 -0800 Subject: [PATCH 035/253] fix(web): a link to a thread on a linked machine no longer opens a blank pane (#34657) --- .../chat/MarkdownThreadLink.browser.test.tsx | 24 +++++++++++++++++++ .../components/chat/MarkdownThreadLink.tsx | 9 +++++-- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx index a379a6afc580a..6febe0ff8b343 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.browser.test.tsx @@ -21,6 +21,12 @@ vi.mock(import("../../state/entities"), () => ({ useProject: (ref: { projectId: string } | null) => ref?.projectId === "essay-project" ? ({ title: "Essays" } as never) : null, })); +vi.mock(import("../../state/environments"), () => ({ + useEnvironmentIdentities: () => [ + { environmentId: EnvironmentId.make("environment"), label: "Here" }, + { environmentId: EnvironmentId.make("remote"), label: "Remote" }, + ], +})); vi.mock(import("../ProjectFavicon"), () => ({ ProjectFavicon: () => ( @@ -132,3 +138,21 @@ it.each([ } }, ); + +it("names a thread on a machine this client has no connection to, without waiting on it", async () => { + const { registry } = setup(); + using _registry = { [Symbol.dispose]: () => registry.dispose() }; + await using screen = await render( + + + , + ); + await expect + .element(screen.getByText("Thread on another machine", { exact: true })) + .toBeVisible(); + await expect.element(screen.getByRole("link")).not.toBeInTheDocument(); +}); diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsx index a88535167db7d..9e897f822ef3f 100644 --- a/apps/web/src/components/chat/MarkdownThreadLink.tsx +++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx @@ -9,6 +9,7 @@ import { import { configuredHostedAppUrl } from "../../hostedPairing"; import { useThreadRefs, useThreadShell } from "../../state/entities"; +import { useEnvironmentIdentities } from "../../state/environments"; import { orchestrationEnvironment } from "../../state/orchestration"; import { useEnvironmentQuery } from "../../state/query"; import { UnresolvedChip } from "../contextChipParts"; @@ -23,8 +24,12 @@ export function MarkdownThreadLink(props: { const candidates = threadLinkCandidates(props.link, props.environmentId); const writtenRef = candidates[0]!; const written = useThreadShell(writtenRef); + // A linked machine's threads are reachable only through its server, not from this client. + const reachable = useEnvironmentIdentities().some( + (environment) => environment.environmentId === writtenRef.environmentId, + ); const lookup = useEnvironmentQuery( - written === null + written === null && reachable ? orchestrationEnvironment.threadLinkMetadata({ environmentId: writtenRef.environmentId, input: { threadIds: candidates.map((ref) => ref.threadId) }, @@ -39,7 +44,7 @@ export function MarkdownThreadLink(props: { const metadata = lookup.data?.[ref.threadId]; return metadata ? [{ ref, metadata }] : []; })[0] ?? null); - const missing = target === null && settled; + const missing = target === null && (settled || !reachable); const guess = missing && props.link.environmentId === null; const refs = useThreadRefs(guess); const remoteRef = guess From f6b260df159143f4d9856230bcbe6dd78e9e3719 Mon Sep 17 00:00:00 2001 From: "Jonas B." <122468993+JonasFocus@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:37:54 -0600 Subject: [PATCH 036/253] fix(server): self-update moves the t3 command to the new runtime (#14875) Co-authored-by: Julius Marminge --- apps/server/src/cloud/bootService.test.ts | 69 ++++++++ apps/server/src/cloud/bootService.ts | 34 +++- apps/server/src/cloud/selfUpdate.test.ts | 2 +- .../src/cloud/serviceLauncherClient.test.ts | 163 +++++++++++++++++- .../server/src/cloud/serviceLauncherClient.ts | 126 ++++++++++++-- apps/server/src/cloud/serviceProtocol.ts | 16 +- .../src/serverRuntimeStartup.autoPull.test.ts | 9 +- apps/server/src/serverRuntimeStartup.test.ts | 2 +- apps/server/src/serverRuntimeStartup.ts | 2 +- 9 files changed, 387 insertions(+), 36 deletions(-) diff --git a/apps/server/src/cloud/bootService.test.ts b/apps/server/src/cloud/bootService.test.ts index 0b60b28e557ad..8c4d5a345f8ee 100644 --- a/apps/server/src/cloud/bootService.test.ts +++ b/apps/server/src/cloud/bootService.test.ts @@ -137,6 +137,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( installerPath = macInstallerPath, xdgConfigHome?: string, managerXdgConfigHome = xdgConfigHome, + installBinDir?: string, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -282,6 +283,7 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( insideService = false, hostExecPath = "/usr/bin/t3", underSudo = false, + serviceInstallBinDir: string | null | undefined = installBinDir, ) => Effect.gen(function* () { const paths = pinnedRuntimePaths(path, serviceBaseDir, cliVersion, platform); @@ -309,6 +311,9 @@ const makeHarness = Effect.fn("test.make_boot_service_harness")(function* ( ConfigProvider.fromEnv({ env: { HOME: home, + ...(serviceInstallBinDir === undefined || serviceInstallBinDir === null + ? {} + : { T3CODE_INSTALL_BIN_DIR: serviceInstallBinDir }), ...(xdgConfigHome === undefined ? {} : { XDG_CONFIG_HOME: xdgConfigHome }), USERPROFILE: home, LOCALAPPDATA: path.join(home, "AppData", "Local"), @@ -572,6 +577,69 @@ it.layer(NodeServices.layer)("boot service install", (it) => { }), ); + it.effect.each(["linux", "darwin"] as const)( + "preserves the custom install bin directory in the installed service on %s", + (platform) => + Effect.gen(function* () { + const installBinDir = '/custom/T3 & <100%>/"quoted"\\bin'; + const { service, makeService, fs } = yield* makeHarness( + platform, + "", + undefined, + undefined, + installBinDir, + ); + const plan = yield* service.install(); + const unit = yield* fs.readFileString(plan.unitPath); + expect(unit).toContain( + platform === "linux" + ? 'Environment=T3CODE_INSTALL_BIN_DIR="/custom/T3 & <100%%>/\\"quoted\\"\\\\bin"' + : 'T3CODE_INSTALL_BIN_DIR\n /custom/T3 & <100%>/"quoted"\\bin', + ); + expect((yield* service.status).current).toBe(true); + + const ordinaryCli = yield* makeService( + "", + "1.2.3", + undefined, + false, + undefined, + false, + null, + ); + expect((yield* ordinaryCli.status).current).toBe(true); + expect((yield* ordinaryCli.install()).installBinDir).toBe(installBinDir); + expect(yield* fs.readFileString(plan.unitPath)).toBe(unit); + + const updatedCli = yield* makeService( + "", + "1.2.4", + undefined, + false, + undefined, + false, + null, + ); + expect((yield* updatedCli.install({ start: false })).installBinDir).toBe(installBinDir); + expect(yield* fs.readFileString(plan.unitPath)).toBe(unit.replaceAll("1.2.3", "1.2.4")); + + const replacementCli = yield* makeService( + "", + "1.2.4", + undefined, + false, + undefined, + false, + "/replacement/bin", + ); + expect((yield* replacementCli.status).current).toBe(false); + expect((yield* replacementCli.install()).installBinDir).toBe("/replacement/bin"); + const laterCli = yield* makeService("", "1.2.4", undefined, false, undefined, false, ""); + expect((yield* laterCli.status).current).toBe(true); + expect((yield* laterCli.install()).installBinDir).toBe("/replacement/bin"); + }), + ); + it.effect.each([ "unset", "empty", @@ -624,6 +692,7 @@ it.layer(NodeServices.layer)("boot service install", (it) => { activeVersion: "1.2.3", }); expect(plan.program).toEqual([runtime.entryPath, "__service-launcher"]); + expect(yield* fs.readFileString(plan.unitPath)).not.toContain("T3CODE_INSTALL_BIN_DIR"); expect(yield* fs.readFileString(plan.unitPath)).toContain( `ExecStart=${runtime.entryPath} __service-launcher`, ); diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.ts index bc7717d457315..1f5bc0c0d355d 100644 --- a/apps/server/src/cloud/bootService.ts +++ b/apps/server/src/cloud/bootService.ts @@ -41,6 +41,7 @@ import { disabledServiceTask, serviceTaskIsDisabled, serviceUnitBaseDirOf as bootServiceBaseDirOf, + serviceUnitEnvironmentValueOf, parseServiceState, serviceStateActiveVersion, serviceStateHasPendingUpdate, @@ -84,6 +85,7 @@ export interface BootServicePlan { readonly baseDir: string; readonly logPath: string; readonly unitPath: string; + readonly installBinDir?: string; /** The manager accepted a detached install; its outcome is written to `logPath`. */ readonly handedOff?: boolean; } @@ -101,6 +103,9 @@ export function renderBootServiceUnit(plan: BootServicePlan): string { "Type=simple", "WorkingDirectory=%h", `Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`, + ...(plan.installBinDir === undefined + ? [] + : [`Environment=T3CODE_INSTALL_BIN_DIR=${quoteSystemdValue(plan.installBinDir)}`]), `Environment=${SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`, `ExecStart=${plan.program.map(quoteSystemdValue).join(" ")}`, // Let the launcher mark an explicit stop before it signals the server. @@ -159,6 +164,12 @@ export function renderBootServicePlist( ` ${escapeXmlText(options.environmentPath)}`, ` T3CODE_HOME`, ` ${escapeXmlText(plan.baseDir)}`, + ...(plan.installBinDir === undefined + ? [] + : [ + ` T3CODE_INSTALL_BIN_DIR`, + ` ${escapeXmlText(plan.installBinDir)}`, + ]), ` ${SERVICE_UNIT_ENV}`, ` ${BOOT_SERVICE_PLIST_FILE}`, ` `, @@ -772,6 +783,9 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ); const xdgConfigHome = yield* Config.String("XDG_CONFIG_HOME").pipe(Config.withDefault("")); const installerPath = yield* Config.String("PATH").pipe(Config.withDefault("")); + const installBinDir = Option.getOrUndefined( + yield* Config.String("T3CODE_INSTALL_BIN_DIR").pipe(Config.option), + ); const xdgRuntimeDir = yield* Config.String("XDG_RUNTIME_DIR").pipe(Config.withDefault("")); // Root under sudo must not reach or start a separate root service. const rootUnderSudo = @@ -989,6 +1003,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { ); }), ).pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); + const planForUnit = (unit: string): BootServicePlan => { + const effectiveInstallBinDir = + installBinDir || serviceUnitEnvironmentValueOf(unit, "T3CODE_INSTALL_BIN_DIR"); + return effectiveInstallBinDir ? { ...plan, installBinDir: effectiveInstallBinDir } : plan; + }; const requireManager = Effect.suspend(() => detectedManager === undefined ? new BootServiceUnsupportedError({ platform }) @@ -1270,7 +1289,10 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { input.baseDir.replaceAll("$", () => "$$"), ...(options?.allowDowngrade === true ? ["--allow-downgrade"] : []), ]); - return { ...plan, handedOff: true }; + const unit = yield* fs + .readFileString(unitPath) + .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); + return { ...planForUnit(unit), handedOff: true }; } // Task Scheduler restarts the task itself, so the files are written as for a deferred // restart while this launcher keeps running, then the restart is handed to the manager. @@ -1281,7 +1303,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { // State first, then unit. The launcher acquires only one at a time, and a // failure to lock the unit must never prevent its durable update commit. - yield* withSelectionLock( + const installedPlan = yield* withSelectionLock( statePath, withSelectionLock( unitPath, @@ -1323,6 +1345,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { .pipe(Effect.mapError((cause) => new BootServiceInstallError({ cause }))); // Files can match the new version even when activation fails; keep that install retryable. yield* fs.writeFileString(restartPendingPath, `${input.cliVersion}\n`, { mode: 0o600 }); + const plan = planForUnit(currentlyInstalled ? yield* fs.readFileString(unitPath) : ""); yield* writeDurably( statePath, // @effect-diagnostics-next-line globalJsonInEffect:off - fixed launcher-owned document. @@ -1344,10 +1367,11 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { const unit = manager.render(plan); yield* writeDurably(unitPath, unit); if (!start && manager.kind === "schtasks") yield* refreshWindowsTask(unit); + return plan; }), ), ).pipe( - Effect.andThen( + Effect.tap( Effect.gen(function* () { if (handOff) { yield* runSteps(manager.handoff ?? []); @@ -1375,7 +1399,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { : Effect.void, ), ); - return handOff ? { ...plan, handedOff: true } : plan; + return handOff ? { ...installedPlan, handedOff: true } : installedPlan; }); const restart: BootService["Service"]["restart"] = Effect.gen(function* () { @@ -1520,7 +1544,7 @@ export const make = Effect.fn("cloud.boot_service.make")(function* (input: { problems, current: problems.length === 0 && - normalizeUnit(unit) === normalizeUnit(manager.render(plan)) && + normalizeUnit(unit) === normalizeUnit(manager.render(planForUnit(unit))) && runtimeEntryExists && Option.isSome(runtimeSentinel) && runtimeSentinel.value.trim() === input.cliVersion && diff --git a/apps/server/src/cloud/selfUpdate.test.ts b/apps/server/src/cloud/selfUpdate.test.ts index 4f95e15382e11..184bd1deb485c 100644 --- a/apps/server/src/cloud/selfUpdate.test.ts +++ b/apps/server/src/cloud/selfUpdate.test.ts @@ -145,7 +145,7 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* ( order.push("accept"); return "launcher-id"; })), - prepareTrial: Effect.undefined, + prepareTrial: () => Effect.undefined, }); const config = yield* ServerConfig.ServerConfig.pipe( Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)), diff --git a/apps/server/src/cloud/serviceLauncherClient.test.ts b/apps/server/src/cloud/serviceLauncherClient.test.ts index 74783cf215594..2c8dc31da24f6 100644 --- a/apps/server/src/cloud/serviceLauncherClient.test.ts +++ b/apps/server/src/cloud/serviceLauncherClient.test.ts @@ -1,4 +1,9 @@ -import { expect, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Logger from "effect/Logger"; +import * as PlatformError from "effect/PlatformError"; +import { assert, expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; @@ -47,13 +52,27 @@ const makeClient = (host: FakeLauncherProcess, currentVersion: string) => ServiceLauncherClient.make({ currentVersion }).pipe( Effect.provideService(ServiceLauncherClient.ServiceLauncherHostProcess, host), Effect.provideService(HostProcess.Environment, host.env), + Effect.provide(NodeServices.layer), ); // regression: #34502 a remote update never replaces the launcher, so an installed one stays protocol 3 it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])( - "waits for a protocol-%i launcher to durably commit the trial update ID", + "waits for a protocol-%i launcher to durably commit the trial update ID, then moves owned launchers", (protocol) => Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-trial-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const installed = path.join(root, ".local/bin/t3"); + for (const file of [exe("1.0.0"), exe("1.1.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, ""); + } + yield* fs.makeDirectory(path.dirname(installed), { recursive: true }); + yield* fs.symlink(exe("1.0.0"), installed); + const pending = { id: "update-1", fromVersion: "1.0.0", @@ -62,10 +81,14 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])( status: "pending" as const, }; const host = new FakeLauncherProcess({ protocol, childVersion: "1.1.0", update: pending }); + host.env["HOME"] = root; const client = yield* makeClient(host, "1.1.0"); - const prepared = yield* Effect.forkChild(client.prepareTrial, { startImmediately: true }); + const prepared = yield* Effect.forkChild(client.prepareTrial({ baseDir }), { + startImmediately: true, + }); yield* Effect.yieldNow; expect(host.sent).toEqual([{ type: "prepared", updateId: "update-1" }]); + assert.equal(yield* fs.readLink(installed), exe("1.0.0")); const committed = { id: pending.id, @@ -75,7 +98,21 @@ it.effect.each([3, SERVICE_LAUNCHER_PROTOCOL])( }; host.emit({ type: "committed", updateId: committed.id }); expect(yield* Fiber.join(prepared)).toEqual(committed); - }), + assert.equal(yield* fs.readLink(installed), exe("1.1.0")); + + // A later start replays the stored outcome; user pins made since then stay put. + yield* fs.remove(installed); + yield* fs.symlink(exe("1.0.0"), installed); + const restarted = new FakeLauncherProcess({ + protocol, + childVersion: "1.1.0", + update: committed, + }); + restarted.env["HOME"] = root; + const restartedClient = yield* makeClient(restarted, "1.1.0"); + expect(yield* restartedClient.prepareTrial({ baseDir })).toEqual(committed); + assert.equal(yield* fs.readLink(installed), exe("1.0.0")); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); it.effect("returns the launcher-generated ID only after update acceptance", () => @@ -169,3 +206,121 @@ it.effect("ignores launcher context inherited without an IPC channel", () => expect(host.sent).toEqual([]); }), ); + +it.layer(NodeServices.layer)("self-update launchers", (it) => { + it.effect( + "updates custom install and PATH launchers, including versions older than fromVersion", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const installed = path.join(root, "custom/bin/t3"); + const onPath = path.join(root, "bin/t3"); + for (const file of [exe("1.0.0"), exe("1.5.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, ""); + } + yield* fs.makeDirectory(path.dirname(installed), { recursive: true }); + yield* fs.symlink(exe("1.5.0"), installed); + yield* fs.makeDirectory(path.dirname(onPath), { recursive: true }); + yield* fs.symlink(exe("1.0.0"), onPath); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + T3CODE_INSTALL_BIN_DIR: path.dirname(installed), + PATH: path.dirname(onPath), + }), + ); + + assert.equal(yield* fs.readLink(installed), exe("2.0.0")); + assert.equal(yield* fs.readLink(onPath), exe("2.0.0")); + }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + ); + + it.effect("still moves the PATH launcher when the install bin one cannot be rewritten", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const exe = (version: string) => path.join(baseDir, "runtime/versions", version, "t3"); + const installed = path.join(root, ".local/bin/t3"); + const onPath = path.join(root, "bin/t3"); + for (const file of [exe("1.0.0"), exe("2.0.0")]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, ""); + } + for (const link of [installed, onPath]) { + yield* fs.makeDirectory(path.dirname(link), { recursive: true }); + yield* fs.symlink(exe("1.0.0"), link); + } + const warnings: unknown[] = []; + const logger = Logger.make(({ logLevel, message }) => { + if (logLevel === "Warn") warnings.push(message); + }); + const failingFs = FileSystem.FileSystem.of({ + ...fs, + rename: (source, destination) => + destination === installed + ? Effect.fail( + new PlatformError.PlatformError( + new PlatformError.SystemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "rename", + pathOrDescriptor: destination, + }), + ), + ) + : fs.rename(source, destination), + }); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: path.dirname(onPath), + }), + Effect.provideService(FileSystem.FileSystem, failingFs), + Effect.provide(Logger.layer([logger], { mergeWithExisting: false })), + ); + + assert.lengthOf(warnings, 1); + assert.include(JSON.stringify(warnings), installed); + assert.equal(yield* fs.readLink(installed), exe("1.0.0")); + assert.equal(yield* fs.readLink(onPath), exe("2.0.0")); + }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + ); + + it.effect("leaves unowned install files and PATH symlinks untouched after self-update", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }); + const baseDir = path.join(root, ".t3"); + const installed = path.join(root, ".local/bin/t3"); + const onPath = path.join(root, "bin/t3"); + const foreign = path.join(root, "other-home/runtime/versions/1.0.0/t3"); + const target = path.join(baseDir, "runtime/versions/2.0.0/t3"); + for (const file of [installed, foreign, target]) { + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, "user-owned file"); + } + yield* fs.makeDirectory(path.dirname(onPath), { recursive: true }); + yield* fs.symlink(foreign, onPath); + + yield* ServiceLauncherClient.repointLaunchers({ baseDir, targetVersion: "2.0.0" }).pipe( + Effect.provideService(HostProcess.Environment, { + HOME: root, + PATH: path.dirname(onPath), + }), + ); + + assert.equal(yield* fs.readFileString(installed), "user-owned file"); + assert.equal(yield* fs.readLink(onPath), foreign); + }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), + ); +}); diff --git a/apps/server/src/cloud/serviceLauncherClient.ts b/apps/server/src/cloud/serviceLauncherClient.ts index d444622dabea4..d29c565b644ff 100644 --- a/apps/server/src/cloud/serviceLauncherClient.ts +++ b/apps/server/src/cloud/serviceLauncherClient.ts @@ -1,12 +1,16 @@ import type { ServerSelfUpdateOutcome } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Context from "effect/Context"; +import * as Cause from "effect/Cause"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import packageJson from "../../package.json" with { type: "json" }; +import { pinnedRuntimePaths, pinnedRuntimeVersionsDir } from "./pinnedRuntime.ts"; import { decodeServiceLauncherContext, decodeServiceLauncherParentMessage, @@ -106,10 +110,10 @@ export class ServiceLauncherClient extends Context.Service< readonly targetVersion: string; readonly dbPath: string; }) => Effect.Effect; - readonly prepareTrial: Effect.Effect< - ServerSelfUpdateOutcome | undefined, - ServiceLauncherClientError - >; + /** Owned `t3` symlinks move to the new runtime only when this start commits the trial. */ + readonly prepareTrial: (input: { + readonly baseDir: string; + }) => Effect.Effect; } >()("t3/cloud/serviceLauncherClient") {} @@ -142,6 +146,83 @@ export const resolveServiceLauncherMode = Effect.fn("cloud.service_launcher_clie }, ); +export const repointLaunchers = Effect.fn("cloud.service_launcher_client.repoint_launchers")( + function* (input: { readonly baseDir: string; readonly targetVersion: string }) { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const environment = yield* HostProcess.Environment; + const platform = yield* HostProcess.Platform; + if (platform !== "linux" && platform !== "darwin") return; + const installBinDir = + environment["T3CODE_INSTALL_BIN_DIR"] || + (environment["HOME"] ? path.join(environment["HOME"], ".local", "bin") : undefined); + const candidates = new Set(); + if (installBinDir !== undefined) candidates.add(path.join(installBinDir, "t3")); + for (const directory of (environment["PATH"] ?? "").split(":")) { + if (directory.length === 0) continue; + const candidate = path.join(directory, "t3"); + if ( + yield* fs.exists(candidate).pipe( + Effect.catch((cause) => + Effect.logWarning("Could not check the t3 command on PATH", { + launchedAs: candidate, + cause, + }).pipe(Effect.as(false)), + ), + ) + ) { + candidates.add(candidate); + break; + } + } + const versionsDir = pinnedRuntimeVersionsDir(path, input.baseDir); + const target = pinnedRuntimePaths(path, input.baseDir, input.targetVersion, platform); + for (const launchedAs of candidates) { + yield* Effect.scoped( + Effect.gen(function* () { + const linkTarget = yield* fs.readLink(launchedAs).pipe( + Effect.asSome, + Effect.catchIf( + (error) => + error.reason._tag === "NotFound" || + (error.reason.cause as NodeJS.ErrnoException | undefined)?.code === "EINVAL", + () => Effect.succeedNone, + ), + ); + if (Option.isNone(linkTarget)) return; + const relative = path.relative( + versionsDir, + path.resolve(path.dirname(launchedAs), linkTarget.value), + ); + if ( + relative.length === 0 || + relative === ".." || + relative.startsWith(`..${path.sep}`) || + path.isAbsolute(relative) + ) + return; + const temporary = yield* fs.makeTempDirectoryScoped({ + directory: path.dirname(launchedAs), + prefix: ".t3-launcher-", + }); + const link = path.join(temporary, "t3"); + yield* fs.symlink(target.entryPath, link); + yield* fs.rename(link, launchedAs); + }), + ).pipe( + Effect.catchCause((cause) => + Cause.hasInterrupts(cause) + ? Effect.interrupt + : Effect.logWarning("Could not move the t3 command to the updated version", { + launchedAs, + cause, + }), + ), + ); + } + }, +); + /** Completes when the launcher asks this server to stop, which Windows cannot signal. */ export const awaitServiceLauncherStop = Effect.fn("cloud.service_launcher_client.await_stop")( function* (options?: { readonly currentVersion?: string }) { @@ -162,6 +243,11 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o readonly currentVersion?: string; }) { const { host, context, managed } = yield* resolveStartup(options); + // prepareTrial runs later, outside whatever context built the client. + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const environment = yield* HostProcess.Environment; + const platform = yield* HostProcess.Platform; const exchange = ( message: ServiceLauncherChildMessage, @@ -239,23 +325,31 @@ export const make = Effect.fn("cloud.service_launcher_client.make")(function* (o context?.update === undefined || context.update.status === "pending" ? undefined : context.update; - const prepareTrial = + const prepareTrial = (input: { readonly baseDir: string }) => pending !== undefined ? exchange( { type: "prepared", updateId: pending.id }, (reply) => reply.type === "committed" && reply.updateId === pending.id, ).pipe( - Effect.flatMap((reply) => { - if (reply.type !== "committed") { - return Effect.die("service launcher returned an impossible prepared response"); - } - return Effect.succeed({ - id: pending.id, - fromVersion: pending.fromVersion, - targetVersion: pending.targetVersion, - status: "committed" as const, - }); - }), + Effect.flatMap((reply) => + reply.type !== "committed" + ? Effect.die("service launcher returned an impossible prepared response") + : repointLaunchers({ + baseDir: input.baseDir, + targetVersion: pending.targetVersion, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fs), + Effect.provideService(Path.Path, path), + Effect.provideService(HostProcess.Environment, environment), + Effect.provideService(HostProcess.Platform, platform), + Effect.as({ + id: pending.id, + fromVersion: pending.fromVersion, + targetVersion: pending.targetVersion, + status: "committed" as const, + }), + ), + ), ) : Effect.succeed(outcome); diff --git a/apps/server/src/cloud/serviceProtocol.ts b/apps/server/src/cloud/serviceProtocol.ts index eeb6333435795..47a02022fe91d 100644 --- a/apps/server/src/cloud/serviceProtocol.ts +++ b/apps/server/src/cloud/serviceProtocol.ts @@ -46,11 +46,19 @@ export const disabledServiceTask = (taskXml: string): string => ? taskXml : taskXml.replace(" ", " false\n "); -export function serviceUnitBaseDirOf(contents: string): string | undefined { - const systemd = /^Environment=T3CODE_HOME=(.*)$/m.exec(contents)?.[1]; +export function serviceUnitEnvironmentValueOf( + contents: string, + name: "T3CODE_HOME" | "T3CODE_INSTALL_BIN_DIR", +): string | undefined { + const systemd = new RegExp(`^Environment=${name}=(.*)$`, "m").exec(contents)?.[1]; if (systemd !== undefined) return unquoteSystemdValue(systemd.trim()); - const plist = /T3CODE_HOME<\/key>\s*([^<]*)<\/string>/.exec(contents)?.[1]; - if (plist !== undefined) return unescapeXmlText(plist); + const plist = new RegExp(`${name}\\s*([^<]*)`).exec(contents)?.[1]; + return plist === undefined ? undefined : unescapeXmlText(plist); +} + +export function serviceUnitBaseDirOf(contents: string): string | undefined { + const unix = serviceUnitEnvironmentValueOf(contents, "T3CODE_HOME"); + if (unix !== undefined) return unix; const task = /[^<]* "--base-dir" "([^"]*)"/.exec(contents)?.[1]; return task === undefined ? undefined : unquoteWindowsArgument(task); } diff --git a/apps/server/src/serverRuntimeStartup.autoPull.test.ts b/apps/server/src/serverRuntimeStartup.autoPull.test.ts index 3d009798c3355..2bc8f31c8f8b3 100644 --- a/apps/server/src/serverRuntimeStartup.autoPull.test.ts +++ b/apps/server/src/serverRuntimeStartup.autoPull.test.ts @@ -148,10 +148,11 @@ it.effect("parks automatic pull until activation without delaying command readin Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ managed: true, protocol: SERVICE_LAUNCHER_PROTOCOL, - prepareTrial: Deferred.succeed(prepared, undefined).pipe( - Effect.andThen(Deferred.await(commitTrial)), - Effect.as(undefined), - ), + prepareTrial: () => + Deferred.succeed(prepared, undefined).pipe( + Effect.andThen(Deferred.await(commitTrial)), + Effect.as(undefined), + ), }), Layer.mock(GitVcsDriver.GitVcsDriver)({ statusDetails: (root) => diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index 492387a6217ec..180defacbfcc6 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -202,7 +202,7 @@ it.effect.each([ Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({ managed: false, protocol: undefined, - prepareTrial: Effect.undefined, + prepareTrial: () => Effect.undefined, }), Layer.mock(GitVcsDriver.GitVcsDriver)({}), Layer.mock(AnalyticsService.AnalyticsService)({}), diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index 9296635010841..689659ab23f59 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -633,7 +633,7 @@ const make = Effect.fn("serverRuntimeStartup.make")(function* (options?: Startup yield* runStartupPhase("http.wait", Deferred.await(httpListening)); yield* runStartupPhase("auxiliary-roots.parked", options?.awaitAuxiliaryParked ?? Effect.void); - const updateOutcome = yield* launcher.prepareTrial; + const updateOutcome = yield* launcher.prepareTrial({ baseDir: serverConfig.baseDir }); yield* Effect.logDebug("startup phase: publishing welcome event", { environmentId: environment.environmentId, From 9c96180aa3e0d216abf7b4eaa5e6e03f4cc18541 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:38:05 -0800 Subject: [PATCH 037/253] fix(server): t3_thread_launch says when its project does not exist (#29109) --- apps/server/src/mcp/linkOrigin.test.ts | 17 +++++++- .../src/mcp/toolkits/project/handlers.test.ts | 34 +++++++++++++++ .../src/mcp/toolkits/project/handlers.ts | 41 ++++++++++--------- apps/server/src/peer/PeerForwarding.test.ts | 17 +++++++- apps/server/src/peer/RemoteDelegation.test.ts | 3 +- 5 files changed, 90 insertions(+), 22 deletions(-) diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts index b8e3b3d2cadb1..928fda0dd72f8 100644 --- a/apps/server/src/mcp/linkOrigin.test.ts +++ b/apps/server/src/mcp/linkOrigin.test.ts @@ -16,6 +16,7 @@ import { } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import { McpSchema, McpServer } from "effect/ai"; import * as ServerConfig from "../config.ts"; @@ -133,7 +134,21 @@ const layerTools = Layer.mergeAll( Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), Layer.provide( Layer.mock(ProjectService.ProjectService)({ - getById: () => Effect.succeedNone, + getById: (id) => + Effect.succeed( + id === projectId + ? Option.some({ + id, + title: "t3code", + workspaceRoot: "/p/t3code", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-10-18T00:00:00.000Z", + updatedAt: "2026-10-18T00:00:00.000Z", + deletedAt: null, + }) + : Option.none(), + ), create: (input) => Effect.succeed({ id: input.projectId, diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index 6266e31abece0..b2ba460d0c8b7 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -642,6 +642,40 @@ it.effect("a launch into a new worktree creates nothing when its branch collides }), ); +it.effect("a launch into an unknown project says the project was not found", () => + Effect.gen(function* () { + const launched: Array = []; + const { modelSelection, dependencies } = clientLaunchHarness({ + runtimeModeCeiling: "auto", + launched, + }); + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)), + ), + ); + for (const workspaceStrategy of [ + undefined, + { type: "worktree", baseRef: "main", startFromOrigin: false } as const, + ]) { + const result = yield* toolkit + .handle("t3_thread_launch", { + title: "Fix", + message: "Fix the bug", + projectId: ProjectId.make("current"), + modelSelection, + ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }), + }) + .pipe(Stream.unwrap, Stream.runCollect, Effect.provide(dependencies)); + expect(result.at(-1)?.result).toMatchObject({ + code: "invalid_request", + message: "The project was not found.", + }); + } + expect(launched).toHaveLength(0); + }), +); + it.effect("a retried worktree launch replays after its base ref is gone", () => Effect.gen(function* () { const launched: Array = []; diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 2c60c7fb8676b..2ad7161cb630b 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -151,11 +151,6 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { ), )).projectId : yield* resolveProjectId(context, input.projectId); - const readProject = Project.ProjectService.pipe( - Effect.flatMap((projects) => projects.getById(projectId)), - Effect.mapError(unavailable), - Effect.map(Option.getOrUndefined), - ); // A retry of an accepted launch replays it: it keeps the model it started // with and skips the checks only a new launch needs, which the project // may no longer pass, such as a base branch deleted since. @@ -166,15 +161,26 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { const launchedModel = launched === null || launched.deletedAt !== null ? undefined : launched.modelSelection; const replaying = launchedModel !== undefined; - if (!replaying && input.workspaceStrategy?.type === "existing_worktree") { - const project = yield* readProject; - if (project === undefined) - return yield* new OrchestratorMcpFailure({ - code: "invalid_request", - message: "The project was not found.", - }); + const project = replaying + ? undefined + : yield* Project.ProjectService.pipe( + Effect.flatMap((projects) => projects.getById(projectId)), + Effect.mapError(unavailable), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + new OrchestratorMcpFailure({ + code: "invalid_request", + message: "The project was not found.", + }), + ), + onSome: Effect.succeed, + }), + ), + ); + if (project !== undefined && input.workspaceStrategy?.type === "existing_worktree") yield* assertProjectWorktree(project.workspaceRoot, input.workspaceStrategy.worktreePath); - } if (!replaying && input.modelSelection !== undefined) { const { instanceId, model } = input.modelSelection; const providers = yield* (yield* ProviderRegistry.ProviderRegistry).getProviders; @@ -201,15 +207,12 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { // project's effective defaults, as the composer does. Its mode stays // within the ceiling it was approved with. const projectDefaults = - caller === undefined && !replaying + caller === undefined && project !== undefined ? yield* ServerSettings.ServerSettingsService.pipe( Effect.flatMap((settings) => settings.getSettings), Effect.mapError(unavailable), - Effect.flatMap((settings) => - Effect.map( - readProject, - (project) => resolveProjectSettings(settings, projectId, project).settings, - ), + Effect.map( + (settings) => resolveProjectSettings(settings, projectId, project).settings, ), ) : undefined; diff --git a/apps/server/src/peer/PeerForwarding.test.ts b/apps/server/src/peer/PeerForwarding.test.ts index 857c1049b56a4..3c4e07444e4fb 100644 --- a/apps/server/src/peer/PeerForwarding.test.ts +++ b/apps/server/src/peer/PeerForwarding.test.ts @@ -16,6 +16,7 @@ import { expect, it } from "@effect/vitest"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; import { McpSchema, McpServer } from "effect/ai"; @@ -166,7 +167,21 @@ const boxLaunches = (seen: Ref.Ref) => const boxProjects = (seen: Ref.Ref) => Layer.merge( Layer.mock(ProjectService.ProjectService)({ - getById: () => Effect.succeedNone, + getById: (id) => + Effect.succeed( + id === boxProject + ? Option.some({ + id, + title: "t3code", + workspaceRoot: "/box/t3code", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-10-18T00:00:00.000Z", + updatedAt: "2026-10-18T00:00:00.000Z", + deletedAt: null, + }) + : Option.none(), + ), create: (input) => Ref.update(seen, (current) => ({ ...current, diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.ts index 1f97ae6023d09..bddb8e4cc4a86 100644 --- a/apps/server/src/peer/RemoteDelegation.test.ts +++ b/apps/server/src/peer/RemoteDelegation.test.ts @@ -567,7 +567,8 @@ const boxToolkitLayer = (thread: BoxThread) => { Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), Layer.provide( Layer.mock(ProjectService.ProjectService)({ - getById: () => Effect.succeedNone, + getById: (id) => + Effect.succeed(Option.fromNullishOr(boxProjects.find((project) => project.id === id))), // More than a page, so finding the project with this repository pages. listPage: ({ cursor, limit }) => Effect.succeed({ From fd64128014f2513a5d3d7ccbdf71febb74423e86 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:43:21 -0800 Subject: [PATCH 038/253] fix(mobile): iOS web previews keep their flick momentum (#27671) --- apps/mobile/src/components/PdfPreview.tsx | 2 ++ apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx | 2 ++ .../settings/components/SettingsLegalDocumentRouteScreen.tsx | 2 ++ apps/mobile/src/features/threads/HtmlRenderWebView.tsx | 2 ++ apps/mobile/src/features/threads/McpAppWebView.tsx | 2 ++ apps/mobile/src/lib/webViewDecelerationRate.ts | 4 ++++ 6 files changed, 14 insertions(+) create mode 100644 apps/mobile/src/lib/webViewDecelerationRate.ts diff --git a/apps/mobile/src/components/PdfPreview.tsx b/apps/mobile/src/components/PdfPreview.tsx index 07ad774d5700e..6bbe24a3b3f4e 100644 --- a/apps/mobile/src/components/PdfPreview.tsx +++ b/apps/mobile/src/components/PdfPreview.tsx @@ -3,6 +3,7 @@ import { View } from "react-native"; import { WebView } from "react-native-webview"; import { FilePreviewLoading, FilePreviewNotice } from "../features/files/FilePreviewFeedback"; +import { webViewDecelerationRate } from "../lib/webViewDecelerationRate"; export function PdfPreview(props: { readonly uri: string }) { const [error, setError] = useState(null); @@ -13,6 +14,7 @@ export function PdfPreview(props: { readonly uri: string }) { source={{ uri: props.uri }} originWhitelist={["*"]} automaticallyAdjustContentInsets={false} + decelerationRate={webViewDecelerationRate} contentInsetAdjustmentBehavior="never" startInLoadingState onError={(event) => diff --git a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx index e105d2082498f..0c40fc4e088b4 100644 --- a/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx +++ b/apps/mobile/src/features/files/WorkspaceFileWebPreview.tsx @@ -11,6 +11,7 @@ import { PdfPreview } from "../../components/PdfPreview"; import { ControlPill } from "../../components/ui/ControlPill"; import { useHardwareBack } from "../../lib/backHandler"; import { isPdfPreviewUri } from "../../lib/pdfPreview"; +import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; import { useContentTopInset } from "../../components/ui/useBarInset"; export function WorkspaceFileWebPreview(props: { readonly uri: string | null }) { @@ -58,6 +59,7 @@ function DocumentWebPreview(props: { readonly uri: string }) { source={{ uri: props.uri }} // react-native-webview defaults to "never", which starts the page under the header. contentInsetAdjustmentBehavior="automatic" + decelerationRate={webViewDecelerationRate} originWhitelist={["*"]} allowsBackForwardNavigationGestures allowsFullscreenVideo diff --git a/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx b/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx index ca79a8c66fcb9..350c260b779f0 100644 --- a/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx +++ b/apps/mobile/src/features/settings/components/SettingsLegalDocumentRouteScreen.tsx @@ -10,6 +10,7 @@ import { AppText as Text } from "../../../components/ui/AppText"; import { LoadingStrip } from "../../../components/ui/LoadingStrip"; import { SymbolView } from "../../../components/ui/AppSymbol"; import { isLegalDocumentUrl, LEGAL_URL } from "../lib/legal-document-url"; +import { webViewDecelerationRate } from "../../../lib/webViewDecelerationRate"; interface SettingsLegalDocumentRouteScreenProps { readonly documentName: string; @@ -100,6 +101,7 @@ export function SettingsLegalDocumentRouteScreen({ cacheEnabled={false} cacheMode="LOAD_NO_CACHE" allowsBackForwardNavigationGestures + decelerationRate={webViewDecelerationRate} domStorageEnabled={false} incognito javaScriptEnabled={false} diff --git a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx index 117d13f364d44..bf22cd01a1966 100644 --- a/apps/mobile/src/features/threads/HtmlRenderWebView.tsx +++ b/apps/mobile/src/features/threads/HtmlRenderWebView.tsx @@ -19,6 +19,7 @@ import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { useAssetUrlState, useRefreshAssetUrl } from "../../state/assets"; import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider"; +import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; const ROW_BOTTOM_MARGIN = 8; const FULL_SCREEN_GUTTER = 16; @@ -130,6 +131,7 @@ export function HtmlRenderWebView(props: { showsVerticalScrollIndicator={!props.nested} showsHorizontalScrollIndicator={!props.nested} scrollEnabled={scrollable} + decelerationRate={webViewDecelerationRate} // Android's patched WebView always keeps horizontal drags. Only pages // with vertical overflow hold vertical drags until they reach an edge. nestedScrollEnabled={props.nested && overflow.y} diff --git a/apps/mobile/src/features/threads/McpAppWebView.tsx b/apps/mobile/src/features/threads/McpAppWebView.tsx index 39c69ca0bebd6..cf03775b7c7fc 100644 --- a/apps/mobile/src/features/threads/McpAppWebView.tsx +++ b/apps/mobile/src/features/threads/McpAppWebView.tsx @@ -34,6 +34,7 @@ import { shareGeneratedAttachment } from "../../lib/attachmentDownload"; import { mobileHtmlRenderTheme } from "../../lib/htmlRenderTheme"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { uuidv4 } from "../../lib/uuid"; +import { webViewDecelerationRate } from "../../lib/webViewDecelerationRate"; import { useAssetUrlState } from "../../state/assets"; import { appAtomRegistry } from "../../state/atom-registry"; import { useThreadShell } from "../../state/entities"; @@ -536,6 +537,7 @@ export function ThreadMcpApp(props: { accessibilityLabel={`${app.server} app`} style={{ flex: 1, backgroundColor: "transparent" }} nestedScrollEnabled + decelerationRate={webViewDecelerationRate} originWhitelist={["*"]} // Android misreports nested frames as top-level; rely on iframe sandboxing there and gate navigation elsewhere. onShouldStartLoadWithRequest={(request) => diff --git a/apps/mobile/src/lib/webViewDecelerationRate.ts b/apps/mobile/src/lib/webViewDecelerationRate.ts new file mode 100644 index 0000000000000..2ee2269316b14 --- /dev/null +++ b/apps/mobile/src/lib/webViewDecelerationRate.ts @@ -0,0 +1,4 @@ +import { Platform } from "react-native"; + +// react-native-webview on Fabric leaves an unset rate at 0, which UIKit clamps to "fast"; Android crashes on the string. +export const webViewDecelerationRate = Platform.OS === "ios" ? "normal" : undefined; From 1e25ef9e5747c321af91b81ab3492b22c65a91da Mon Sep 17 00:00:00 2001 From: maria Date: Thu, 12 Nov 2026 00:47:53 +0000 Subject: [PATCH 039/253] feat(github): unvouched PRs get an open PR limit, a conflict window, and a 72 hour close notice (#34555) --- .agents/skills/contribution-triage/SKILL.md | 21 +- .github/scripts/pr-limits.cjs | 295 ++++++++++++++++++++ .github/workflows/pr-limits.yml | 72 +++++ CONTRIBUTING.md | 31 +- knip.jsonc | 1 + 5 files changed, 414 insertions(+), 6 deletions(-) create mode 100644 .github/scripts/pr-limits.cjs create mode 100644 .github/workflows/pr-limits.yml diff --git a/.agents/skills/contribution-triage/SKILL.md b/.agents/skills/contribution-triage/SKILL.md index 21ba3b7a6566a..49a62c5e905e6 100644 --- a/.agents/skills/contribution-triage/SKILL.md +++ b/.agents/skills/contribution-triage/SKILL.md @@ -111,6 +111,8 @@ trusted policy and reassess changed submission evidence; neither example grants Do not automatically close a PR if a maintainer in the trusted `TRIAGE_EXEMPTIONS.td` list has commented or submitted a review, including on earlier heads, or if `triage:keep-open` is present. +Comments that triage itself posted, such as an earlier notice or question, are not maintainer +involvement, even when they were posted from a maintainer's account on that maintainer's behalf. Leave protected PRs open for maintainer decision. This does not grant an author exemption, eligibility, or review approval. @@ -126,7 +128,17 @@ comment text but do not write to GitHub. Keep the eligibility finding separate f This is a routing exception, not a claim that the PR passed eligibility or correctness review. - **Closure warranted.** The assessment is complete and establishes a specific policy violation. Prepare a clear explanation under [closure and reconsideration](../../../CONTRIBUTING.md#closure-and-reconsideration), - post it, and close the PR. Verify that the explanation is present and the PR is closed. The comment + post it, then read the repository variable `PR_LIMITS_ENFORCE` + (`gh variable get PR_LIMITS_ENFORCE -R pingdotgg/t3code`). When it prints `true`, apply + `triage:closing` as the last thing you do to the PR, verify that the explanation and the label + are present, and do not close the PR yourself: + [pr-limits.yml](../../../.github/workflows/pr-limits.yml) closes it 72 hours after the label. Any + activity on the PR after the label, including a further comment or label from you, removes the + label; treat an author's reply or push as new evidence, reassess, and apply the label again only + if the finding still holds. When the command prints any other value, or fails saying the variable + was not found, the variable is off and nothing would close a labeled PR: close it yourself and + verify that the explanation is present and the PR is closed. Only another failure, such as a + permission error, means the variable cannot be read; then report the closure as incomplete. The comment must name the violated rule, cite supporting submission evidence, link the maintained guide section, and give a concrete remedy. Missing contributor evidence can warrant closure; explain what must be established. Missing product approval calls for maintainer discussion, not an agent's product decision. @@ -173,9 +185,10 @@ description, evidence, approvals, existing triage comments, PR open/closed state label when relevant. Reassess changes that could invalidate the finding. Reuse an existing explanation only if it still matches the current finding; avoid duplicate comments, closures, or label applications. -For closure, establish that the required explanation is posted before closing. If posting fails or its -result is ambiguous, read back the comments before retrying or proceeding. If the comment succeeds but -closure fails, preserve the comment and retry only the unfinished closure after checking current state. +For closure, establish that the required explanation is posted before applying `triage:closing` or +closing. If posting fails or its result is ambiguous, read back the comments before retrying or +proceeding. If the comment succeeds but the label or the closure fails, preserve the comment and retry +only that unfinished step after checking current state. Handle a failed or ambiguous label application the same way: inspect labels before any retry. If access or state still cannot be verified, report an incomplete action and the step needed to resume. Do not retry blindly or claim success for an unverified action. diff --git a/.github/scripts/pr-limits.cjs b/.github/scripts/pr-limits.cjs new file mode 100644 index 0000000000000..e63174950e126 --- /dev/null +++ b/.github/scripts/pr-limits.cjs @@ -0,0 +1,295 @@ +const fs = require("node:fs"); + +const HOUR_MS = 60 * 60 * 1000; +const OPEN_LIMIT = 3; +const CONFLICT_IDLE_MS = 7 * 24 * HOUR_MS; +const NOTICE_MS = 72 * HOUR_MS; +// A first run meets the whole backlog. These keep one run from flooding watchers or GitHub's +// limit on how fast a token may comment. +const MAX_REQUESTS_PER_RUN = 100; +const MAX_CLOSES_PER_RUN = 50; +const WRITE_PAUSE_MS = 1_000; +// Measured here: about two and a half minutes until every open PR has an answer. +const MERGEABLE_WAIT_MS = 150_000; +// GitHub stamps a label event and the PR's updatedAt a second or two apart. +const SAME_MOMENT_MS = 15_000; + +const REBASE_LABEL = "needs-rebase"; +const CLOSING_LABEL = "triage:closing"; +const KEEP_OPEN_LABEL = "triage:keep-open"; +const UNVOUCHED_LABEL = "vouch:unvouched"; +const WRITE_PERMISSIONS = new Set(["admin", "maintain", "write"]); +const EXEMPTIONS_PATH = ".github/TRIAGE_EXEMPTIONS.td"; +const VOUCHED_PATH = ".github/VOUCHED.td"; +const LOGIN_PATTERN = /^github:([A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38})$/; + +// `labels` matches a PR that carries any one of them. +const SWEEP_QUERY = ` + query ($owner: String!, $repo: String!, $labels: [String!], $cursor: String) { + repository(owner: $owner, name: $repo) { + pullRequests(states: OPEN, labels: $labels, first: 100, after: $cursor) { + pageInfo { hasNextPage endCursor } + nodes { + number + mergeable + baseRefName + updatedAt + author { login } + labels(first: 100) { nodes { name } } + timelineItems(itemTypes: [LABELED_EVENT], last: 20) { + nodes { ... on LabeledEvent { createdAt label { name } } } + } + } + } + } + }`; + +const RECHECK_QUERY = ` + query ($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + state + mergeable + updatedAt + labels(first: 100) { nodes { name } } + } + } + }`; + +const AUTHOR_OPEN_PRS_QUERY = ` + query ($q: String!) { + search(query: $q, type: ISSUE, first: 50) { + nodes { ... on PullRequest { number } } + } + }`; + +// Fails closed: a missing, empty, or malformed list must never read as "nobody is exempt". +function parseExemptions(text) { + const logins = new Set(); + for (const raw of text.split("\n")) { + const line = raw.trim(); + if (line === "" || line.startsWith("#")) continue; + const match = LOGIN_PATTERN.exec(line); + if (!match) throw new Error(`${EXEMPTIONS_PATH}: malformed entry "${line}"`); + const login = match[1].toLowerCase(); + if (logins.has(login)) throw new Error(`${EXEMPTIONS_PATH}: duplicate entry "${line}"`); + logins.add(login); + } + if (logins.size === 0) throw new Error(`${EXEMPTIONS_PATH}: no entries`); + return logins; +} + +// VOUCHED.td: one `github:login` per line, `#` comments, and `-github:login reason` to denounce. +function vouchedLogins(text) { + const logins = new Set(); + for (const raw of text.split("\n")) { + const entry = raw.trim().split(/\s+/)[0]; + if (entry.startsWith("github:")) logins.add(entry.slice("github:".length).toLowerCase()); + } + if (logins.size === 0) throw new Error(`${VOUCHED_PATH}: no entries`); + return logins; +} + +function labeledAt(pr, name) { + const last = pr.timelineItems.nodes.filter((event) => event.label?.name === name).at(-1); + return last ? Date.parse(last.createdAt) : undefined; +} + +// The whole policy for the two windows. Activity is anything that moves the PR's updatedAt: a +// push, a comment, a review, a label. Nobody can set that time, so nothing here trusts the author. +function decide(pr, exemptions, now) { + const labels = new Set(pr.labels.nodes.map((label) => label.name)); + if (labels.has(KEEP_OPEN_LABEL)) return "skip"; + const updatedAt = Date.parse(pr.updatedAt); + + if (labels.has(CLOSING_LABEL)) { + const since = labeledAt(pr, CLOSING_LABEL); + if (since === undefined) return "unknown-notice"; + // Any activity after the notice sends the PR back to triage. + if (updatedAt - since > SAME_MOMENT_MS) return "clear-notice"; + return now - since >= NOTICE_MS ? "close-notice" : "skip"; + } + + const exempt = exemptions.has((pr.author?.login ?? "").toLowerCase()); + const subject = labels.has(UNVOUCHED_LABEL) && !exempt; + if (labels.has(REBASE_LABEL)) { + if (!subject || pr.mergeable === "MERGEABLE") return "clear-rebase"; + // Activity restarts the seven days and keeps the label, so a PR is asked to rebase once. + const idle = now - updatedAt >= CONFLICT_IDLE_MS; + return idle && pr.mergeable === "CONFLICTING" ? "close-conflict" : "skip"; + } + return subject && pr.mergeable === "CONFLICTING" ? "request-rebase" : "skip"; +} + +function guideLink(context, anchor) { + return `https://github.com/${context.repo.owner}/${context.repo.repo}/blob/main/CONTRIBUTING.md#${anchor}`; +} + +async function removeLabel(github, context, number, name) { + try { + await github.rest.issues.removeLabel({ ...context.repo, issue_number: number, name }); + } catch (error) { + if (error.status !== 404) throw error; + } +} + +async function closeWithComment(github, context, number, body) { + await github.rest.issues.createComment({ ...context.repo, issue_number: number, body }); + await github.rest.pulls.update({ ...context.repo, pull_number: number, state: "closed" }); +} + +async function sweep({ github, context, core, dryRun }) { + const exemptions = parseExemptions(fs.readFileSync(EXEMPTIONS_PATH, "utf8")); + const repo = { owner: context.repo.owner, repo: context.repo.repo }; + const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + + const list = async () => { + const prs = []; + for (let cursor = null; ;) { + const page = ( + await github.graphql(SWEEP_QUERY, { + ...repo, + cursor, + labels: [UNVOUCHED_LABEL, REBASE_LABEL, CLOSING_LABEL], + }) + ).repository.pullRequests; + prs.push(...page.nodes); + if (!page.pageInfo.hasNextPage) return prs; + cursor = page.pageInfo.endCursor; + } + }; + // GitHub computes mergeability lazily and forgets it whenever the base moves. Asking starts the + // computation, so ask once more. A PR that is still unknown waits for tomorrow's run. + let prs = await list(); + if (prs.some((pr) => pr.mergeable === "UNKNOWN")) { + await pause(MERGEABLE_WAIT_MS); + prs = await list(); + } + + const now = Date.now(); + const count = {}; + for (const pr of prs) { + const { number } = pr; + let action = decide(pr, exemptions, now); + if (action === "skip") continue; + if (action === "unknown-notice") { + core.warning(`#${number}: cannot tell when ${CLOSING_LABEL} was applied, leaving it open.`); + continue; + } + if (action === "request-rebase" && (count[action] ?? 0) >= MAX_REQUESTS_PER_RUN) continue; + if (action.startsWith("close")) { + if ((count["close-conflict"] ?? 0) + (count["close-notice"] ?? 0) >= MAX_CLOSES_PER_RUN) { + continue; + } + // The list is minutes old by now. Closing is the one step worth a second look. + const fresh = (await github.graphql(RECHECK_QUERY, { ...repo, number })).repository + .pullRequest; + if (fresh.state !== "OPEN") continue; + // A merge to the base can resolve a conflict without touching the PR, so this is re-read + // too. An answer that is not ready yet reads as "not conflicting" and waits for tomorrow. + action = decide({ ...pr, ...fresh }, exemptions, now); + if (!action.startsWith("close")) continue; + } + + count[action] = (count[action] ?? 0) + 1; + core.info(`#${number} ${action}${dryRun ? " (dry run)" : ""}`); + if (dryRun) continue; + + if (action === "request-rebase") { + // The request goes first: a label without it would start a clock nobody was told about. + await github.rest.issues.createComment({ + ...context.repo, + issue_number: number, + body: [ + `This PR conflicts with \`${pr.baseRefName}\`. Rebase it or merge \`${pr.baseRefName}\` into it. If it still conflicts after 7 days with no activity, it will be closed automatically.`, + "", + `See the [conflict window](${guideLink(context, "conflict-window")}).`, + ].join("\n"), + }); + await github.rest.issues.addLabels({ + ...context.repo, + issue_number: number, + labels: [REBASE_LABEL], + }); + } else if (action === "clear-rebase") { + await removeLabel(github, context, number, REBASE_LABEL); + } else if (action === "clear-notice") { + await removeLabel(github, context, number, CLOSING_LABEL); + } else { + const conflict = action === "close-conflict"; + await closeWithComment( + github, + context, + number, + conflict + ? [ + `Closing: this PR still conflicts with \`${pr.baseRefName}\` and has had no activity for 7 days since the rebase request.`, + "", + `To continue, rebase the branch and open a new PR that links this one. See the [conflict window](${guideLink(context, "conflict-window")}).`, + ].join("\n") + : [ + "Closing: 72 hours have passed since the triage notice above with no activity on this PR.", + "", + `To ask for reconsideration, address the notice and comment here, or open a focused replacement PR that links this one. See [closure and reconsideration](${guideLink(context, "closure-and-reconsideration")}).`, + ].join("\n"), + ); + // Without this a maintainer's reopen would be closed again by the next run. + await removeLabel(github, context, number, conflict ? REBASE_LABEL : CLOSING_LABEL); + } + await pause(WRITE_PAUSE_MS); + } + + const summary = Object.entries(count).map(([action, n]) => `${n} ${action}`); + core.info( + `${dryRun ? "Dry run. " : ""}${prs.length} PRs read: ${summary.join(", ") || "nothing to do"}.`, + ); + return count; +} + +async function enforceOpenLimit({ github, context, core, dryRun }) { + const pr = context.payload.pull_request; + const author = pr.user.login; + // Who is trusted is decided here rather than by the vouch action, which reports its own failed + // lookups as "not vouched". Every read below throws on failure, and a throw closes nothing. + if (pr.user.type === "Bot") return; + if (parseExemptions(fs.readFileSync(EXEMPTIONS_PATH, "utf8")).has(author.toLowerCase())) return; + if (vouchedLogins(fs.readFileSync(VOUCHED_PATH, "utf8")).has(author.toLowerCase())) return; + const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({ + ...context.repo, + username: author, + }); + if (WRITE_PERMISSIONS.has(access.permission)) return; + if (pr.labels.some((label) => label.name === KEEP_OPEN_LABEL)) return; + // Someone else reopening a PR is a maintainer overriding the limit. + const reopened = context.payload.action === "reopened"; + if (reopened && context.payload.sender.login.toLowerCase() !== author.toLowerCase()) return; + + const q = `repo:${context.repo.owner}/${context.repo.repo} is:pr is:open author:${author} sort:created-asc`; + const { search } = await github.graphql(AUTHOR_OPEN_PRS_QUERY, { q }); + // A new PR counts only the older ones, so two opened together cannot close each other. + const others = search.nodes.filter( + (node) => node.number && (reopened ? node.number !== pr.number : node.number < pr.number), + ).length; + if (others < OPEN_LIMIT) { + core.info(`PR #${pr.number}: ${author} has ${others} other open PRs.`); + return; + } + if (dryRun) { + core.notice(`Dry run. PR #${pr.number} would close: ${author} has ${others} other open PRs.`); + return; + } + + await closeWithComment( + github, + context, + pr.number, + [ + `Closing: ${author} already has ${OPEN_LIMIT} or more open PRs here, which is the limit for contributors who are not vouched.`, + "", + `Once one of them is merged or closed, open this again. See the [open PR limit](${guideLink(context, "open-pr-limit")}).`, + ].join("\n"), + ); + core.info(`PR #${pr.number}: closed, ${author} has ${others} other open PRs.`); +} + +module.exports = { decide, enforceOpenLimit, parseExemptions, sweep }; diff --git a/.github/workflows/pr-limits.yml b/.github/workflows/pr-limits.yml new file mode 100644 index 0000000000000..75943062735cd --- /dev/null +++ b/.github/workflows/pr-limits.yml @@ -0,0 +1,72 @@ +name: PR Limits + +# Deterministic PR rules from CONTRIBUTING.md: the open PR limit, the conflict +# window, and the 72 hour close window that follows a triage notice. +# +# Nothing is labeled, commented on, or closed until the repository variable +# PR_LIMITS_ENFORCE is "true". Until then every run logs what it would do. A +# sweep reads the variable once when it starts; to stop one, cancel the run. + +on: + pull_request_target: + types: [opened, reopened] + schedule: + - cron: "23 5 * * *" + workflow_dispatch: + inputs: + dry_run: + description: Log what the sweep would do without labeling, commenting, or closing. + type: boolean + default: true + +permissions: + contents: read + issues: write + pull-requests: write + +jobs: + open-limit: + name: Open PR limit + if: github.event_name == 'pull_request_target' + runs-on: ubuntu-24.04 + steps: + # pull_request_target has a write token. Load the script from the default + # branch and never run PR code. Cone mode also checks out the files beside + # .github/scripts, which is where TRIAGE_EXEMPTIONS.td and VOUCHED.td live. + - name: Checkout trusted scripts + uses: actions/checkout@v6 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: .github/scripts + + - name: Close PRs over the limit + uses: actions/github-script@v8 + env: + DRY_RUN: ${{ vars.PR_LIMITS_ENFORCE != 'true' }} + with: + script: | + const limits = require("./.github/scripts/pr-limits.cjs"); + await limits.enforceOpenLimit({ github, context, core, dryRun: process.env.DRY_RUN === "true" }); + + sweep: + name: Conflict and close windows + if: github.event_name != 'pull_request_target' + runs-on: ubuntu-24.04 + concurrency: + group: pr-limits-sweep + cancel-in-progress: false + steps: + - name: Checkout trusted scripts + uses: actions/checkout@v6 + with: + ref: ${{ github.event.repository.default_branch }} + sparse-checkout: .github/scripts + + - name: Request rebases and close what went unanswered + uses: actions/github-script@v8 + env: + DRY_RUN: ${{ vars.PR_LIMITS_ENFORCE != 'true' || (github.event_name == 'workflow_dispatch' && inputs.dry_run) }} + with: + script: | + const limits = require("./.github/scripts/pr-limits.cjs"); + await limits.sweep({ github, context, core, dryRun: process.env.DRY_RUN === "true" }); diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5578da31082ed..3f1da7bdf66f2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -141,14 +141,41 @@ supported event fetches current full PR state and assesses cumulative changes; u not wired and there is no periodic sweep. This guide does not announce a deployed automation or change existing review settings. Neither triage nor a Macroscope review authorizes merging. + + +## Open PR limit and conflict window + +Two rules run without triage, in [pr-limits.yml](.github/workflows/pr-limits.yml). Neither applies +to vouched contributors, to maintainers in [TRIAGE_EXEMPTIONS.td](.github/TRIAGE_EXEMPTIONS.td), or to +a PR labeled `triage:keep-open`. They do not assess eligibility. They and the closure notice below are +enforced only while the repository variable `PR_LIMITS_ENFORCE` is `true`; until then triage closes +PRs directly. + +A contributor who is not vouched can have 3 open PRs. A further PR is closed when it is opened. Get +one of the open PRs merged or closed, then open it again. A maintainer who reopens a PR overrides the +limit for that PR. + + + +A PR labeled `vouch:unvouched` that conflicts with its base branch gets a request to rebase and the +`needs-rebase` label. The label comes off once the PR no longer conflicts. A PR that still conflicts +after 7 days with no activity is closed. Any activity on the PR, such as a push, a comment, or a +review from anyone, restarts the 7 days. + ## Closure and reconsideration Automated triage leaves a PR open for maintainer decision if someone in the trusted [TRIAGE_EXEMPTIONS.td](.github/TRIAGE_EXEMPTIONS.td) list has commented or submitted a review, -including on an earlier head, or if `triage:keep-open` is present. This protection does not imply -eligibility or review approval. +including on an earlier head, or if `triage:keep-open` is present. Comments that triage itself +posted, such as an earlier notice, do not count, even when they came from a maintainer's account. +This protection does not imply eligibility or review approval. + +A policy-based closure starts with a notice. Triage posts the explanation and applies +`triage:closing`, and the PR closes 72 hours later. Any activity on the PR within that time, such as +a reply, a push, or a maintainer's comment, removes the label and sends the PR back to triage, which +reassesses it with the new evidence. PRs that violate these requirements can be closed before deeper review. Multiple independent fixes require splitting. Missing approval requires maintainer discussion or issue triage, as applicable. diff --git a/knip.jsonc b/knip.jsonc index 068c8cf84ab69..e3589f643c325 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -12,6 +12,7 @@ // CodeRabbit loads its configuration by filename. ".coderabbit.config.ts", ".github/scripts/thread-transfer-report.cjs", + ".github/scripts/pr-limits.cjs", ], "vite": { "entry": [".github/**/*.test.cjs"] }, "vitest": { "entry": [".github/**/*.test.cjs"] }, From 4e6924753cac26b904b76f59a44cff026914a132 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:51:11 -0800 Subject: [PATCH 040/253] fix(web): pasted CRLF text keeps its blank lines and caret in the composer (#27280) --- ...rPromptEditorTiptap.input.browser.test.tsx | 20 +++++++++++++++++++ .../components/ComposerPromptEditorTiptap.tsx | 4 ++-- .../composerInlineTokenPaste.test.ts | 6 ++++++ .../components/composerInlineTokenPaste.ts | 7 ++++++- 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 0e29db4f2dd77..2aaaabee7ad93 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -362,6 +362,26 @@ it("keeps unknown dollar names editable when restoring and pasting a draft", asy expect(serializeEditorDoc(editor.state.doc).value).toBe(value); }); +it.each(["x\r\n\r\ny", "x\r\ry"])( + "pastes %j with the same blank line as x\\n\\ny", + async (text) => { + await using screen = await mountEditor(""); + const { editor } = screen; + await act(async () => { + editor.commands.focus("end"); + const clipboardData = new DataTransfer(); + clipboardData.setData("text/plain", text); + editor.view.dom.dispatchEvent( + new ClipboardEvent("paste", { clipboardData, cancelable: true }), + ); + }); + const paragraphs: string[] = []; + editor.state.doc.forEach((node) => paragraphs.push(node.textContent)); + expect(paragraphs).toEqual(["x", "", "y"]); + expect(serializeEditorDoc(editor.state.doc).value).toBe("x\n\ny"); + }, +); + it("keeps the caret inside unknown dollar text across rich and plain remounts", async () => { const value = "echo $HOME now"; await using screen = await mountEditor(value); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 474b2f1f181c6..3761e6e8ea4ec 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -131,7 +131,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { ComposerCodeBlockNodeView } from "./chat/ComposerCodeBlockNodeView"; import { resolveAssistantCitationCommentDismissal } from "./chat/assistantCitationCommentDismissal"; import { composerCodeBlockHighlight } from "./composerCodeBlockHighlight"; -import { importPastedComposerText } from "./composerInlineTokenPaste"; +import { importPastedComposerText, readPastedPlainText } from "./composerInlineTokenPaste"; import { didComposerSelectionChangeVisibly } from "./composerSelection"; import type { ComposerDraftContextRecords } from "./composerContextPresentation"; @@ -1367,7 +1367,7 @@ function ComposerPromptEditorTiptapInner( handlePaste: (view, event) => { const clipboardData = event.clipboardData; if (!clipboardData || clipboardData.files.length > 0) return false; - const pastedText = clipboardData.getData("text/plain"); + const pastedText = readPastedPlainText(clipboardData); if (!pastedText) return false; event.preventDefault(); // Paste verbatim inside fences; markdown parsing would split blocks and create unsupported chips. diff --git a/apps/web/src/components/composerInlineTokenPaste.test.ts b/apps/web/src/components/composerInlineTokenPaste.test.ts index 1ab28a5b7ff51..d201cd3adc71a 100644 --- a/apps/web/src/components/composerInlineTokenPaste.test.ts +++ b/apps/web/src/components/composerInlineTokenPaste.test.ts @@ -56,4 +56,10 @@ describe("importPastedComposerText", () => { pasted, ); }); + + it("imports CRLF and CR clipboard text with LF line breaks", () => { + expect( + importPastedComposerText(clipboard({ "text/plain": "x\r\n\r\ny\rz" }), () => new Map()), + ).toBe("x\n\ny\nz"); + }); }); diff --git a/apps/web/src/components/composerInlineTokenPaste.ts b/apps/web/src/components/composerInlineTokenPaste.ts index 0862f81ee8355..0e1a84aa71af2 100644 --- a/apps/web/src/components/composerInlineTokenPaste.ts +++ b/apps/web/src/components/composerInlineTokenPaste.ts @@ -20,6 +20,11 @@ import { readThreadShell } from "~/state/entities"; const threadTitle = (ref: ScopedThreadRef) => readThreadShell(ref)?.title; +// Matches ProseMirror's default clipboard parser, which a custom handlePaste bypasses. +export function readPastedPlainText(clipboardData: Pick): string { + return clipboardData.getData("text/plain").replace(/\r\n?/g, "\n"); +} + /** Pasted thread links count as context too, so they become chips like a copied chip does. */ export function readPastedComposerContext( clipboardData: Pick, @@ -65,7 +70,7 @@ export function importPastedComposerText( fragment: ComposerContextClipboardFragment, ) => ReadonlyMap, ): string { - const pastedText = clipboardData.getData("text/plain"); + const pastedText = readPastedPlainText(clipboardData); const fragment = importContextFragment ? readPastedComposerContext(clipboardData) : null; const rewrittenIds = fragment && fragment.records.length > 0 ? importContextFragment!(fragment) : null; From ccc9aaf10b5f40382d0ca68b8523aa2f434c841f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:51:37 -0800 Subject: [PATCH 041/253] fix(server): a cancelled queued Claude continuation no longer drops later wakes (#30114) --- .../Adapters/ClaudeAdapterV2.test.ts | 709 +++++++++++++++++- .../Adapters/ClaudeAdapterV2.ts | 316 +++++++- ...laudeAutomaticDelivery.integration.test.ts | 290 +++++++ .../ProviderContinuationService.ts | 93 ++- .../testkit/ProviderReplayHarness.ts | 1 + .../server/ProviderContinuationRequests.ts | 2 + 6 files changed, 1354 insertions(+), 57 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index d2330829b096d..d5de0f85d815f 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -13910,7 +13910,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("keeps a newer wake latched when a stale continuation request is cleared", () => + it.effect("keeps a newer wake's output when a stale continuation request is cleared", () => Effect.scoped( Effect.gen(function* () { const SECOND_TASK_ID = "b2ndwake"; @@ -13976,11 +13976,546 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); assert.lengthOf(harness.continuationRequests, 2); - yield* harness.continuationRequests[0]!.clearIfCurrent!(); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); yield* harness.offerAndWait( - claudeSdkFrame({ ...wakeAssistant, uuid: "00000000-0000-4000-8000-000000000135" }), + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000135", + text: "Second build done.", + }), + ); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000136", + result: "Second build done.", + origin: { kind: "task-notification" }, + }), + ); + assert.lengthOf(harness.continuationRequests, 2); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-stale-clear-3"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 3, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.awaitTerminal(3); + assert.isTrue( + harness.events.some( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.text === "Second build done.", + ), + "clearing the first wake's request must not discard the second wake's output", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + + it.effect("offers the next wake when a cancelled wake's release arrives after it opened", () => + Effect.scoped( + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-late-release"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000141", + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000142", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000143" }), + ); + assert.lengthOf(harness.continuationRequests, 1); + + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeAssistant, uuid: "00000000-0000-4000-8000-000000000144" }), + ); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000145", result: "Done." }), + ); + assert.lengthOf( + harness.continuationRequests, + 2, + "the wake that opened before the cancelled wake's release must get its own continuation", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + + it.effect("does not offer a wake again when it is cancelled before its first root frame", () => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-early-cancel"), + text: "Start an agent in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTaskStarted, task_type: "local_agent" }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeNotification); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + assert.lengthOf( + harness.continuationRequests, + 1, + "the cancelled wake must not be offered again", + ); + + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000146" }), + ); + assert.lengthOf(harness.continuationRequests, 2, "the next wake must be offered"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + + it.effect("offers a later task's wake when a cancelled wake never opens", () => + Effect.scoped( + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-never-opens"), + text: "Start an agent and a build in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTaskStarted, task_type: "local_agent" }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000151", + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + // Claude never opens a wake for the agent's notification. + yield* harness.offerAndWait(wakeNotification); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000152", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000153" }), + ); + yield* harness.offerAndWait( + makeAssistantTextFrame({ uuid: "00000000-0000-4000-8000-000000000154", text: "Built." }), + ); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000155", result: "Built." }), + ); + assert.lengthOf( + harness.continuationRequests, + 2, + "the build's wake must get its own continuation", + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + + it.effect.each([ + { ending: "notification", cancelled: "after its result" }, + { ending: "tool result", cancelled: "after its result" }, + { ending: "tool result", cancelled: "while the subagent ran" }, + ] as const)( + "does not replay a subagent that finished inside a cancelled wake (ended by $ending, cancelled $cancelled)", + ({ ending, cancelled }) => + Effect.scoped( + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const SUBAGENT_TASK_ID = "fg-agent"; + const SUBAGENT_TOOL_USE_ID = "toolu-fg-agent"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-finished-subagent"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000161", + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + // The first wake runs a subagent to completion before its result. + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "task_started", + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + description: "Inspect build output", + subagent_type: "general-purpose", + task_type: "local_agent", + prompt: "Inspect the build output.", + uuid: "00000000-0000-4000-8000-000000000162", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000168", + text: "Reading the build log.", + }), + parent_tool_use_id: SUBAGENT_TOOL_USE_ID, + }), + ); + if (cancelled === "while the subagent ran") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } + yield* harness.offerAndWait( + ending === "notification" + ? claudeSdkFrame({ + type: "system", + subtype: "task_notification", + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + status: "completed", + output_file: "/tmp/fg-agent.output", + summary: "Inspected", + uuid: "00000000-0000-4000-8000-000000000163", + session_id: WAKE_NATIVE_SESSION, + }) + : claudeSdkFrame({ + type: "user", + uuid: "00000000-0000-4000-8000-000000000163", + session_id: WAKE_NATIVE_SESSION, + parent_tool_use_id: null, + message: { + role: "user", + content: [ + { + type: "tool_result", + tool_use_id: SUBAGENT_TOOL_USE_ID, + content: "Inspected", + }, + ], + }, + }), + ); + yield* harness.offerAndWait(wakeResult); + if (cancelled === "after its result") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } + + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000164", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000165" }), + ); + assert.lengthOf(harness.continuationRequests, 2); + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-finished-subagent-2"), + text: "Background task completed.", + attachments: [], + providerTurnOrdinal: 2, + messageCreatedBy: "agent", + messageCreationSource: "provider", + }), + ); + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000000166", + text: "Second build done.", + }), + ); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000167", + result: "Second build done.", + origin: { kind: "task-notification" }, + }), + ); + yield* harness.awaitTerminal(2); + + const subagentStatuses = harness.events.flatMap((event) => + event.type === "subagent.updated" && + event.subagent.nativeTaskRef?.nativeId === SUBAGENT_TASK_ID + ? [event.subagent.status] + : [], + ); + assert.notInclude( + subagentStatuses, + "running", + "a subagent that finished in the cancelled wake must not be replayed as running", + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + + it.effect("offers a cancelled wake once when an empty lifecycle result precedes its turn", () => + Effect.scoped( + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-empty-lifecycle"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000171", + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000172", + result: "", + numTurns: 0, + origin: { kind: "task-notification" }, + terminalReason: null, + }), + ); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000173" }), + ); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + assert.lengthOf( + harness.continuationRequests, + 1, + "the cancelled wake must not be offered again", + ); + + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000174", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000175" }), + ); + assert.lengthOf(harness.continuationRequests, 2, "the next wake must be offered"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + + it.effect("does not offer a cancelled wake again for its trailing empty lifecycle result", () => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-trailing-lifecycle"), + text: "Run a build in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.offerAndWait(wakeResult); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000176" }), + ); + yield* harness.offerAndWait( + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000177", + result: "", + numTurns: 0, + origin: { kind: "task-notification" }, + terminalReason: null, + }), + ); + assert.lengthOf(harness.continuationRequests, 1); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + assert.lengthOf( + harness.continuationRequests, + 1, + "a lifecycle result after the cancelled wake must not open another continuation", ); - assert.lengthOf(harness.continuationRequests, 2); }).pipe( Effect.provide( Layer.mergeAll( @@ -13994,6 +14529,82 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect.each([ + "before the cancelled wake's result", + "after the cancelled wake's result", + ] as const)( + "offers a subagent's wake that arrives behind a cancelled wake (notified %s)", + (notified) => + Effect.scoped( + Effect.gen(function* () { + const SUBAGENT_TASK_ID = "bg-agent"; + const SUBAGENT_TOOL_USE_ID = "toolu-bg-agent"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-later-subagent"), + text: "Run a build and an agent in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(wakeTaskStarted); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + task_type: "local_agent", + uuid: "00000000-0000-4000-8000-000000000181", + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* harness.awaitTerminal(1); + + const subagentNotification = claudeSdkFrame({ + ...wakeNotification, + task_id: SUBAGENT_TASK_ID, + tool_use_id: SUBAGENT_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SUBAGENT_TASK_ID}.output`, + summary: "Agent finished", + uuid: "00000000-0000-4000-8000-000000000182", + }); + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + assert.lengthOf(harness.continuationRequests, 1); + if (notified === "before the cancelled wake's result") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + yield* harness.offerAndWait(subagentNotification); + yield* harness.offerAndWait(wakeResult); + } else { + yield* harness.offerAndWait(wakeResult); + yield* harness.offerAndWait(subagentNotification); + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } + assert.lengthOf( + harness.continuationRequests, + 2, + "the subagent's wake must get its own continuation", + ); + assert.equal(harness.continuationRequests[1]?.detail, "Agent finished"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect.each([true, false])( "carries a rejected wake rate limit into the continuation failure (event=%s)", (standaloneEvent) => @@ -14412,6 +15023,96 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect.each(["before", "after"] as const)( + "offers a later wake when a wake a user turn absorbed is cancelled %s that turn ends", + (cancelled) => + Effect.scoped( + Effect.gen(function* () { + const SECOND_TASK_ID = "b2ndwake"; + const SECOND_TOOL_USE_ID = "toolu_second_wake"; + const harness = yield* makeWakeHarness; + const now = yield* DateTime.now; + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-cancel-1"), + text: "Run two builds in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer( + harness.sdkMessages, + claudeSdkFrame({ + ...wakeTaskStarted, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + uuid: "00000000-0000-4000-8000-000000000191", + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeNotification); + yield* Queue.offer(harness.sdkMessages, turnOneResult); + yield* harness.awaitTerminal(1); + yield* harness.offerAndWait(wakeTurnInit); + yield* harness.offerAndWait(wakeAssistant); + yield* harness.awaitContinuation(1); + + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make("attempt-claude-wake-absorbed-cancel-2"), + text: "Any update on the pull request?", + attachments: [], + providerTurnOrdinal: 2, + }), + ); + yield* harness.until(() => harness.offeredMessages.length === 2); + if (cancelled === "before") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } + yield* Queue.offer( + harness.sdkMessages, + makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000192", + result: "Checks passed and the pull request is up to date.", + }), + ); + yield* harness.awaitTerminal(2); + if (cancelled === "after") { + yield* harness.continuationRequests[0]!.onRunEndedWithoutStarting!(); + } + + yield* harness.offerAndWait( + claudeSdkFrame({ + ...wakeNotification, + task_id: SECOND_TASK_ID, + tool_use_id: SECOND_TOOL_USE_ID, + output_file: `/tmp/claude-replay/tasks/${SECOND_TASK_ID}.output`, + uuid: "00000000-0000-4000-8000-000000000193", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ ...wakeTurnInit, uuid: "00000000-0000-4000-8000-000000000194" }), + ); + assert.lengthOf(harness.continuationRequests, 2, "the later wake must be offered"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), + ); + it.effect("ignores a zero-turn task-notification origin result during a normal user turn", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 7bdd80435a281..91f27c816cf33 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -3616,6 +3616,45 @@ function isClaudeSubagentAsyncLaunchAck(output: ClaudeNativeToolOutput): boolean return claudeSubagentResultText(output).startsWith("Async agent launched successfully."); } +// Background Agent launches ACK immediately and workflow launches return run handles; only task_notification settles those. +function claudeToolResultSettlesSubagent( + toolResult: ClaudeToolResultContentBlock, + output: ClaudeNativeToolOutput, +): boolean { + return ( + isClaudeToolResultError(toolResult) || + (parseClaudeWorkflowRunHandles(claudeNativeToolOutputValue(output)) === undefined && + !isClaudeSubagentAsyncLaunchAck(output)) + ); +} + +function claudeSettledSubagentToolUseIds(messages: ReadonlyArray): ReadonlySet { + return new Set( + messages.flatMap((entry) => + entry.type === "user" && entry.parent_tool_use_id == null + ? claudeToolResultEntriesFromMessage(entry).flatMap(({ toolResult, output }) => + claudeToolResultSettlesSubagent(toolResult, output) ? [toolResult.tool_use_id] : [], + ) + : [], + ), + ); +} + +function claudeWakeBufferDetail(messages: ReadonlyArray): string | null { + return ( + messages + .flatMap((entry) => + entry.type === "system" && + entry.subtype === "task_notification" && + typeof entry.summary === "string" && + entry.summary.length > 0 + ? [entry.summary] + : [], + ) + .at(-1) ?? null + ); +} + const WEB_FETCH_SNIPPET_MAX_CHARS = 8_000; function webSearchPatternsFromClaudeTool(input: { @@ -4242,6 +4281,18 @@ function isClaudeTaskNotificationOriginResult(message: SDKMessage): message is S return message.type === "result" && message.origin?.kind === "task-notification"; } +// A session-task lifecycle result: it can precede a wake's real turn and ends no turn. +function isClaudeEmptyTaskNotificationSuccess(message: SDKMessage): boolean { + return ( + isClaudeTaskNotificationOriginResult(message) && + message.subtype === "success" && + !message.is_error && + message.num_turns === 0 && + message.result.length === 0 && + terminalStatusFromResult(message) === "completed" + ); +} + // The CLI throttles unchanged rate_limit_event frames, but repeats this // undeclared payload on each blocked assistant response. const isClaudeBlockedAssistantRateLimit = Schema.is( @@ -5695,7 +5746,19 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return { kind: "command", label, outcome }; } }); - const requestedContinuations = yield* Ref.make(new Map()); + // `end` is the offered wake's last frame once known: its result, or the last frame a user turn absorbed. + // A retired latch belongs to a cancelled wake that has not ended; its root frames are dropped until it does. + // Claude may never open an "unopened" one, so a later task's notification releases it instead. + const requestedContinuations = yield* Ref.make( + new Map< + string, + { + readonly token: symbol; + readonly end: SDKMessage | undefined; + readonly retired: "unopened" | "opened" | null; + } + >(), + ); const absorbedWakes = yield* Ref.make(new Set()); const heldProposedPlansByToolUseId = new Map(); const runtimeContext = yield* Effect.context(); @@ -6185,13 +6248,34 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* forgetAbsorbedWake(nativeThreadId); }); + const releaseContinuationLatch = (nativeThreadId: string) => + Ref.update(requestedContinuations, (current) => { + if (!current.has(nativeThreadId)) return current; + const updated = new Map(current); + updated.delete(nativeThreadId); + return updated; + }); + // Claude runs one root turn at a time, so a user turn's result also ends a wake turn it // folded in. The continuation replays that wake's buffered frames but gets no result of its own. const markAbsorbedWake = Effect.fnUntraced(function* (nativeThreadId: string) { + const latch = (yield* Ref.get(requestedContinuations)).get(nativeThreadId); + if (latch !== undefined && latch.retired !== null) { + yield* releaseContinuationLatch(nativeThreadId); + return; + } const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? []; const lastResult = messages.findLastIndex((entry) => entry.type === "result"); if (!messages.slice(lastResult + 1).some(isClaudeRootTurnFrame)) return; yield* Ref.update(absorbedWakes, (current) => new Set(current).add(nativeThreadId)); + if (latch !== undefined && latch.end === undefined) { + yield* Ref.update(requestedContinuations, (current) => + new Map(current).set(nativeThreadId, { + ...latch, + end: messages.findLast(isClaudeRootTurnFrame), + }), + ); + } }); // The SDK emits no initial roster; reset roster and wake eligibility when opening a live query. @@ -8960,6 +9044,34 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (!isWakeEvidence) { return; } + const retired = (yield* Ref.get(requestedContinuations)).get( + wakeInput.nativeThreadId, + )?.retired; + if ( + retired === "unopened" && + (isPendingTaskNotification || isPendingSubagentNotification) + ) { + yield* releaseContinuationLatch(wakeInput.nativeThreadId); + } else if ( + retired != null && + (isClaudeRootTurnFrame(message) || + message.type === "result" || + message.type === "rate_limit_event") + ) { + if (isClaudeEmptyTaskNotificationSuccess(message)) { + yield* setRetiredLatch(wakeInput.nativeThreadId, "unopened"); + } else if (message.type === "result") { + yield* releaseContinuationLatch(wakeInput.nativeThreadId); + yield* offerBufferedWake(wakeInput.nativeThreadId); + } else if (isClaudeRootTurnFrame(message)) { + yield* setRetiredLatch(wakeInput.nativeThreadId, "opened"); + yield* dropSettledSubagents( + wakeInput.nativeThreadId, + claudeSettledSubagentToolUseIds([message]), + ); + } + return; + } const notificationSummary = isNotification && typeof message.summary === "string" && message.summary.length > 0 ? message.summary @@ -9010,6 +9122,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( message.task_id, ); } + if (message.type === "result" && !isClaudeEmptyTaskNotificationSuccess(message)) { + yield* Ref.update(requestedContinuations, (current) => { + const latch = current.get(wakeInput.nativeThreadId); + if (latch === undefined || latch.end !== undefined) return current; + return new Map(current).set(wakeInput.nativeThreadId, { ...latch, end: message }); + }); + } // Open continuations only after root init, user, assistant, or result frames prove a wake began. // Background child frames can stream while the root is idle. const buffered = (yield* Ref.get(wakeBuffers)).get(wakeInput.nativeThreadId); @@ -9029,30 +9148,38 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { return; } - const route = (yield* Ref.get(lastTurnRouteByNativeThread)).get(wakeInput.nativeThreadId); + yield* offerWakeContinuation(wakeInput.nativeThreadId); + }); + + const offerWakeContinuation = Effect.fnUntraced(function* (nativeThreadId: string) { + const route = (yield* Ref.get(lastTurnRouteByNativeThread)).get(nativeThreadId); if (route === undefined) { yield* Effect.logWarning("orchestration-v2.claude-wake-turn-unroutable", { providerSessionId: input.providerSessionId, - nativeThreadId: wakeInput.nativeThreadId, + nativeThreadId, }); return; } - const nativeThreadId = wakeInput.nativeThreadId; - const latch = Symbol(nativeThreadId); + const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId); + const token = Symbol(nativeThreadId); const shouldOffer = yield* Ref.modify(requestedContinuations, (current) => { if (current.has(nativeThreadId)) { return [false, current] as const; } const updated = new Map(current); - updated.set(nativeThreadId, latch); + updated.set(nativeThreadId, { + token, + end: buffered?.messages.find( + (entry) => entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry), + ), + retired: null, + }); return [true, updated] as const; }); if (!shouldOffer) { return; } - const detail = - (yield* Ref.get(wakeBuffers)).get(wakeInput.nativeThreadId)?.detail ?? null; - const reports = yield* takeWakeReports(wakeInput.nativeThreadId); + const reports = yield* takeWakeReports(nativeThreadId); const notification = backgroundWorkNotification( [...(reports?.values() ?? [])].map((entry) => entry.report), ); @@ -9061,25 +9188,156 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( threadId: route.threadId, providerThreadId: route.providerThreadId, }); + // A process reset can clear and re-latch this thread; a stale request must not retire the newer wake. + const retire = (): Effect.Effect => + sdkMessageLock.withPermits(1)(retireOfferedWake(nativeThreadId, token)); yield* continuationRequests.offer({ threadId: route.threadId, providerThreadId: route.providerThreadId, driver: CLAUDE_PROVIDER, - detail, + detail: buffered?.detail ?? null, ...(notification === null ? {} : { notification }), - // A process reset can clear and re-latch this thread; a stale failure must not release the newer wake. - clearIfCurrent: () => - Ref.update(requestedContinuations, (current) => { - if (current.get(nativeThreadId) !== latch) { - return current; - } - const updated = new Map(current); - updated.delete(nativeThreadId); - return updated; - }), + clearIfCurrent: retire, + onRunEndedWithoutStarting: retire, }); }); + // Drops what the unstarted continuation would have shown. Starts of subagents still running stay + // because later child frames and notifications resolve their owner from them. + const retireOfferedWake = Effect.fnUntraced(function* ( + nativeThreadId: string, + token: symbol, + ) { + const latch = (yield* Ref.get(requestedContinuations)).get(nativeThreadId); + if (latch?.token !== token) return; + const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages; + const messages = buffered ?? []; + const endIndex = + latch.end === undefined ? messages.length - 1 : messages.indexOf(latch.end); + const retired = messages.slice(0, endIndex + 1); + const later = messages.slice(endIndex + 1); + const retiredTaskIds = new Set( + retired.flatMap((entry) => + entry.type === "system" && entry.subtype === "task_notification" + ? [entry.task_id] + : [], + ), + ); + const settledToolUseIds = claudeSettledSubagentToolUseIds(retired); + const kept = [ + ...retired.filter( + (entry) => + entry.type === "system" && + entry.subtype === "task_started" && + !retiredTaskIds.has(entry.task_id) && + (entry.tool_use_id === undefined || !settledToolUseIds.has(entry.tool_use_id)), + ), + ...later, + ]; + if (!(yield* replaceWakeBuffer(nativeThreadId, buffered, kept, retiredTaskIds))) return; + if (latch.end === undefined) { + // A lifecycle result closes the root frames before it without opening the wake's turn. + const sinceLifecycleResult = retired.slice( + retired.findLastIndex(isClaudeEmptyTaskNotificationSuccess) + 1, + ); + yield* setRetiredLatch( + nativeThreadId, + sinceLifecycleResult.some(isClaudeRootTurnFrame) ? "opened" : "unopened", + ); + return; + } + yield* releaseContinuationLatch(nativeThreadId); + yield* forgetAbsorbedWake(nativeThreadId); + yield* offerBufferedWake(nativeThreadId); + }); + + const setRetiredLatch = (nativeThreadId: string, retired: "unopened" | "opened") => + Ref.update(requestedContinuations, (current) => { + const latch = current.get(nativeThreadId); + return latch === undefined || latch.retired === retired + ? current + : new Map(current).set(nativeThreadId, { ...latch, retired }); + }); + + // Compare-and-set: a process reset clears the buffer without the SDK message lock, and must not be undone. + const replaceWakeBuffer = Effect.fnUntraced(function* ( + nativeThreadId: string, + expected: ReadonlyArray | undefined, + messages: ReadonlyArray, + droppedTaskIds: ReadonlySet, + ) { + const replaced = yield* Ref.modify(wakeBuffers, (current) => { + if (current.get(nativeThreadId)?.messages !== expected) + return [false, current] as const; + const updated = new Map(current); + if (messages.length === 0) updated.delete(nativeThreadId); + else + updated.set(nativeThreadId, { messages, detail: claudeWakeBufferDetail(messages) }); + return [true, updated] as const; + }); + if (!replaced) return false; + yield* Ref.update(wakeReportsByNativeThread, ({ userTurns, reports }) => { + const threadReports = reports.get(nativeThreadId); + if (threadReports === undefined) return { userTurns, reports }; + const remaining = new Map( + [...threadReports].filter(([taskId]) => !droppedTaskIds.has(taskId)), + ); + const updatedReports = new Map(reports); + if (remaining.size === 0) updatedReports.delete(nativeThreadId); + else updatedReports.set(nativeThreadId, remaining); + return { userTurns, reports: updatedReports }; + }); + return true; + }); + + // A retired wake's dropped tool results still settle the subagents it kept for later frames. + const dropSettledSubagents = Effect.fnUntraced(function* ( + nativeThreadId: string, + settledToolUseIds: ReadonlySet, + ) { + if (settledToolUseIds.size === 0) return; + const buffered = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages; + const messages = buffered ?? []; + const settledTaskIds = new Set( + messages.flatMap((entry) => + entry.type === "system" && + entry.subtype === "task_started" && + entry.tool_use_id !== undefined && + settledToolUseIds.has(entry.tool_use_id) + ? [entry.task_id] + : [], + ), + ); + const kept = messages.filter((entry) => { + const parentToolUseId = parentToolUseIdFromSdkMessage(entry); + return ( + (parentToolUseId === null || !settledToolUseIds.has(parentToolUseId)) && + !(entry.type === "system" && "task_id" in entry && settledTaskIds.has(entry.task_id)) + ); + }); + if (kept.length === messages.length) return; + yield* replaceWakeBuffer(nativeThreadId, buffered, kept, settledTaskIds); + }); + + // After a retired wake releases its latch, a wake buffered behind it has had no offer of its own. + const offerBufferedWake = Effect.fnUntraced(function* (nativeThreadId: string) { + const messages = (yield* Ref.get(wakeBuffers)).get(nativeThreadId)?.messages ?? []; + const reports = (yield* Ref.get(wakeReportsByNativeThread)).reports.get(nativeThreadId); + // A lifecycle result ends no turn, and closes the root frames before it. + const hasWake = + messages + .slice(messages.findLastIndex(isClaudeEmptyTaskNotificationSuccess) + 1) + .some(isClaudeRootTurnFrame) || + messages.some( + (entry) => + (entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry)) || + (entry.type === "system" && + entry.subtype === "task_notification" && + reports?.get(entry.task_id)?.report.kind === "subagent"), + ); + if (hasWake) yield* offerWakeContinuation(nativeThreadId); + }); + // Untraced like the roster message handling: it runs for every streamed roster change. const emitRosterUpdate = Effect.fnUntraced(function* ( nativeThreadId: string, @@ -10241,13 +10499,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( subagent !== undefined && findToolCall(context, toolResult.tool_use_id) === undefined ) { - // Background Agent launches ACK immediately; only task_notification settles them. - if ( - !isClaudeToolResultError(toolResult) && - (runHandles !== undefined || isClaudeSubagentAsyncLaunchAck(output)) - ) { - continue; - } + if (!claudeToolResultSettlesSubagent(toolResult, output)) continue; const result = claudeSubagentResultText(output); yield* updateClaudeSubagentNode({ context, @@ -11922,15 +12174,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( .some((entry) => isClaudeTurnStartMessage(entry)); // The CLI can append empty task successes after a failure. Filter // those for replay without changing the raw-tail successor guard. - const isEmptyTaskNotificationSuccess = (entry: SDKMessage) => - isClaudeTaskNotificationOriginResult(entry) && - entry.subtype === "success" && - !entry.is_error && - entry.num_turns === 0 && - entry.result.length === 0 && - terminalStatusFromResult(entry) === "completed"; const replayResultIndex = drained.findLastIndex( - (entry) => entry.type === "result" && !isEmptyTaskNotificationSuccess(entry), + (entry) => + entry.type === "result" && !isClaudeEmptyTaskNotificationSuccess(entry), ); const lastResult = drained[replayResultIndex === -1 ? lastResultIndex : replayResultIndex]; diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 9700757eb8bbe..fc27392eda0db 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -15,6 +15,7 @@ import { type OrchestrationV2DomainEvent, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -36,6 +37,7 @@ import * as EffectWorker from "./EffectWorker.ts"; import * as EventSink from "./EventSink.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; +import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; @@ -610,3 +612,291 @@ it.effect("applies an effort change to the running Claude query without waiting ), ), ); + +const backgroundTaskStarted = (taskId: string) => + frame({ + type: "system", + subtype: "task_started", + task_id: taskId, + tool_use_id: `tool-${taskId}`, + description: "Background build", + is_backgrounded: true, + task_type: "local_bash", + uuid: `started-${taskId}`, + session_id: sessionId, + }); + +const backgroundTaskNotification = (taskId: string) => + frame({ + type: "system", + subtype: "task_notification", + task_id: taskId, + tool_use_id: `tool-${taskId}`, + status: "completed", + output_file: `/tmp/claude-replay/tasks/${taskId}.output`, + summary: `Background build ${taskId} completed`, + uuid: `notification-${taskId}`, + session_id: sessionId, + }); + +const wakeAssistant = (uuid: string) => + frame({ + type: "assistant", + uuid, + session_id: sessionId, + parent_tool_use_id: null, + message: { + id: `msg-${uuid}`, + role: "assistant", + type: "message", + model: modelSelection.model, + content: [{ type: "text", text: `Background build finished (${uuid}).` }], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 1, output_tokens: 1 }, + }, + }); + +it.effect("offers a continuation for a later wake after a queued continuation is cancelled", () => + Effect.scoped( + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("claude-cancelled-continuation"); + const sdkMessages = yield* Queue.unbounded(); + const processed = new WeakMap>(); + const offerAndWait = Effect.fnUntraced(function* (message: SDKMessage) { + const done = yield* Deferred.make(); + processed.set(message, done); + yield* Queue.offer(sdkMessages, message); + yield* Deferred.await(done); + }); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const random = yield* SecureRandom.SecureRandom; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const continuations: ProviderContinuationRequests.ProviderContinuationRequest[] = []; + const services = + yield* Effect.context< + Effect.Services> + >(); + const registry = ProviderAdapterRegistry.layerFromAdaptersEffect( + Effect.gen(function* () { + const requests = yield* ProviderContinuationRequests.ProviderContinuationRequests; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: modelSelection.instanceId, + settings, + environment: {}, + attachmentsDir: cwd, + fileSystem, + path, + random, + idAllocator, + continuationRequests: { + offer: (request) => + Effect.sync(() => continuations.push(request)).pipe( + Effect.andThen(requests.offer(request)), + ), + }, + queryRunner: { + allocateSessionId: Effect.succeed(sessionId), + open: () => + Effect.succeed({ + // Resolve each frame's Deferred once the adapter pulls the next one. + messages: Stream.fromQueue(sdkMessages).pipe( + Stream.flatMap((message) => + Stream.make(message).pipe( + Stream.concat( + Stream.fromEffect( + Effect.suspend(() => { + const done = processed.get(message); + return done === undefined + ? Effect.void + : Deferred.succeed(done, undefined); + }), + ).pipe(Stream.drain), + ), + ), + ), + ), + offer: () => Effect.void, + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Effect.void, + close: Effect.void, + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }).pipe(Effect.provideContext(services)); + return [adapter]; + }), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make("thread:cancelled-continuation"); + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const runUpdated = (messageId: string, status: string) => + watch( + (event) => + event.type === "run.updated" && + event.payload.userMessageId === messageId && + event.payload.status === status, + ); + // A user turn that leaves a background task running when it ends. + const userTurnWithBackgroundTask = Effect.fnUntraced(function* ( + id: string, + taskId: string, + ) { + const running = yield* runUpdated(id, "running"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(id), + threadId, + messageId: MessageId.make(id), + text: "Run the build in the background.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(running); + const waiting = yield* runUpdated(id, "waiting"); + yield* Queue.offer(sdkMessages, backgroundTaskStarted(taskId)); + yield* Queue.offer(sdkMessages, result(`result-${id}`, false)); + yield* Fiber.join(waiting); + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:cancelled-continuation"), + title: "Cancelled continuation", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + + // The first run is still finalizing when its background task wakes Claude. + yield* userTurnWithBackgroundTask("first", "build-1"); + const queued = yield* watch( + (event) => event.type === "run.created" && event.payload.status === "queued", + ); + yield* offerAndWait(backgroundTaskNotification("build-1")); + yield* offerAndWait(wakeAssistant("wake-1")); + yield* Fiber.join(queued); + assert.lengthOf(continuations, 1); + const continuationRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + ); + assert.ok(continuationRun !== undefined); + yield* orchestrator.dispatch({ + type: "queued-run.cancel", + commandId: CommandId.make("cancel"), + threadId, + runId: continuationRun.id, + }); + yield* offerAndWait(result("wake-1-result", false)); + yield* worker.drain(); + yield* orchestrator.resumeQueuedRuns; + yield* worker.drain(); + const idle = yield* orchestrator.getThreadProjection(threadId); + assert.equal(idle.runs.find((run) => run.id === continuationRun.id)?.status, "cancelled"); + assert.isFalse(idle.runs.some((run) => run.status === "queued")); + + yield* userTurnWithBackgroundTask("second", "build-2"); + yield* worker.drain(); + // The second user run has completed, so this continuation starts without queueing. + const isContinuationRun = ( + event: OrchestrationV2DomainEvent, + type: string, + status: string, + ) => + (event.type === "run.created" || event.type === "run.updated") && + event.type === type && + event.payload.status === status && + event.payload.userMessageId !== MessageId.make("first") && + event.payload.userMessageId !== MessageId.make("second"); + const secondCreated = yield* watch((event) => + isContinuationRun(event, "run.created", "starting"), + ); + const secondRunning = yield* watch((event) => + isContinuationRun(event, "run.updated", "running"), + ); + yield* offerAndWait(backgroundTaskNotification("build-2")); + yield* offerAndWait(wakeAssistant("wake-2")); + assert.lengthOf( + continuations, + 2, + "the wake after a cancelled queued continuation must offer a new continuation", + ); + yield* Fiber.join(secondCreated); + yield* worker.drain(); + yield* Fiber.join(secondRunning); + const secondContinuation = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "running", + ); + assert.ok(secondContinuation !== undefined); + const secondWaiting = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.id === secondContinuation.id && + event.payload.status === "waiting", + ); + yield* offerAndWait(result("wake-2-result", false)); + yield* Fiber.join(secondWaiting); + yield* worker.drain(); + const settled = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + settled.runs.find((run) => run.id === secondContinuation.id)?.status, + "completed", + ); + assert.deepEqual( + settled.turnItems.flatMap((item) => + item.runId === secondContinuation.id && item.type === "assistant_message" + ? [item.text] + : [], + ), + ["Background build finished (wake-2)."], + "the continuation must carry only its own wake's output", + ); + assert.lengthOf(continuations, 2, "two wakes must offer exactly two continuations"); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: "claude-cancelled-continuation" }, + registry, + { runEffectWorker: false, runContinuationWorker: true }, + ), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ), +); diff --git a/apps/server/src/orchestration-v2/ProviderContinuationService.ts b/apps/server/src/orchestration-v2/ProviderContinuationService.ts index ac414413ca3bc..01f6e0acb989d 100644 --- a/apps/server/src/orchestration-v2/ProviderContinuationService.ts +++ b/apps/server/src/orchestration-v2/ProviderContinuationService.ts @@ -1,10 +1,17 @@ -import { CommandId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { + CommandId, + type MessageId, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Ref from "effect/Ref"; +import * as Stream from "effect/Stream"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; +import type * as Orchestrator from "./Orchestrator.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import { isUndeliveredMailboxSteer } from "./NotificationMailbox.ts"; @@ -73,6 +80,54 @@ export const layer = Layer.effectDiscard( return [Math.min(100 * 2 ** Math.min(attempt, 6), 5_000), updated] as const; }); + // Cancelling or stopping a queued continuation ends it unstarted; only the request can release the adapter's wake latch. + const releaseIfNeverStarted = Effect.fn("ProviderContinuationService.releaseIfNeverStarted")( + function* ( + request: ProviderContinuationRequests.ProviderContinuationRequest, + messageId: MessageId, + dispatched: Orchestrator.OrchestratorV2DispatchResult, + ) { + const onRunEndedWithoutStarting = request.onRunEndedWithoutStarting; + if (onRunEndedWithoutStarting === undefined) return; + const runId = dispatched.storedEvents.flatMap(({ event }) => + event.type === "run.created" && event.payload.userMessageId === messageId + ? [event.payload.id] + : [], + )[0]; + if (runId === undefined) return; + yield* threads + .streamStoredEventsFrom({ + threadId: request.threadId, + afterSequence: dispatched.sequence, + eventType: "run.updated", + }) + .pipe( + Stream.filter( + ({ event }) => + event.type === "run.updated" && + event.payload.id === runId && + ThreadManagementService.isTerminalRunStatus(event.payload.status), + ), + Stream.runHead, + Effect.flatMap((ended) => + Option.isSome(ended) && + ended.value.event.type === "run.updated" && + ended.value.event.payload.startedAt === null + ? onRunEndedWithoutStarting() + : Effect.void, + ), + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.provider-continuation.run-watch-failed", { + threadId: request.threadId, + providerThreadId: request.providerThreadId, + cause, + }), + ), + Effect.forkScoped, + ); + }, + ); + const dispatchContinuation = Effect.fn("ProviderContinuationService.dispatchContinuation")( function* (request: ProviderContinuationRequests.ProviderContinuationRequest) { const projection = yield* threads.getThreadRecords( @@ -186,23 +241,25 @@ export const layer = Layer.effectDiscard( ordinal: projection.messages.length + 1, })); const commandId = CommandId.make(`provider-continuation:${messageId}`); - const dispatch = threads.dispatch({ - type: "message.dispatch", - commandId, - threadId: request.threadId, - messageId, - text: request.detail ?? CONTINUATION_MESSAGE_TEXT, - notification: request.notification ?? { - source: { kind: "background_task" }, - outcome: "updated", - summary: "Background activity updated", - }, - attachments: [], - dispatchMode: { type: "queue_after_active" }, - createdBy: "agent", - // Only buffered wakes use creationSource "provider"; Claude would drain an empty buffer instead of prompting message_text. - creationSource: request.delivery === "message_text" ? "server" : "provider", - }); + const dispatch = threads + .dispatch({ + type: "message.dispatch", + commandId, + threadId: request.threadId, + messageId, + text: request.detail ?? CONTINUATION_MESSAGE_TEXT, + notification: request.notification ?? { + source: { kind: "background_task" }, + outcome: "updated", + summary: "Background activity updated", + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + // Only buffered wakes use creationSource "provider"; Claude would drain an empty buffer instead of prompting message_text. + creationSource: request.delivery === "message_text" ? "server" : "provider", + }) + .pipe(Effect.tap((dispatched) => releaseIfNeverStarted(request, messageId, dispatched))); // Catch after dispatchIfCurrent so adapters see raw failures first; clearIfCurrent is idempotent and covers others. const logInstanceDisabled = ( error: ThreadManagementService.ThreadManagementProviderInstanceDisabledError, diff --git a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts index 0f416ea8451f1..6cedd4889ee7c 100644 --- a/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts +++ b/apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts @@ -518,6 +518,7 @@ export function layerWithRegistry( recoverDelegatedTask: orchestrator.recoverDelegatedTask, cancelDelegatedTask: orchestrator.cancelDelegatedTask, delegatedTaskResultPending: orchestrator.delegatedTaskResultPending, + streamStoredEventsFrom: orchestrator.streamStoredEventsFrom, }); }), ).pipe(Layer.provide(layerOrchestratorProvided)); diff --git a/packages/provider-core/src/server/ProviderContinuationRequests.ts b/packages/provider-core/src/server/ProviderContinuationRequests.ts index 936769c46c3e4..576edcc221a11 100644 --- a/packages/provider-core/src/server/ProviderContinuationRequests.ts +++ b/packages/provider-core/src/server/ProviderContinuationRequests.ts @@ -30,6 +30,8 @@ export interface ProviderContinuationRequest { effect: Effect.Effect, ) => Effect.Effect, E, R>; readonly clearIfCurrent?: () => Effect.Effect; + /** Called when the run this request dispatched ends without starting, such as a cancelled queued run. */ + readonly onRunEndedWithoutStarting?: () => Effect.Effect; } /** The default drops requests; share the live layer with the worker that drains them. */ From 6a03ef6568da3f962714b1ea8f0de91a947c9014 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:52:33 -0800 Subject: [PATCH 042/253] fix(web): app keybindings on Mod+B, Mod+I and Mod+E win over composer formatting (#34493) --- ...rPromptEditorTiptap.input.browser.test.tsx | 62 ++++++++++++++++++- .../components/ComposerPromptEditorTiptap.tsx | 15 +++++ apps/web/src/keybindings.ts | 7 +++ apps/web/src/shortcuts/dispatcher.ts | 25 ++++++-- 4 files changed, 104 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx index 2aaaabee7ad93..6971383b851e5 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.input.browser.test.tsx @@ -19,6 +19,7 @@ import { act, fakeTimers, render } from "../../test/render"; import { flatToMarkdown, pmToFlat, serializeEditorDoc } from "~/composer-rich-text-doc"; import { isMacPlatform } from "~/lib/utils"; +import { registerCommands } from "~/shortcuts/dispatcher"; import { ComposerPromptEditorTiptap as ComposerPromptEditor, type ComposerPromptEditorHandle, @@ -36,11 +37,13 @@ function Composer({ richTextEnabled, skills, onChange, + onCommandKeyDown = () => false, }: { value: string; richTextEnabled: boolean; skills: ReadonlyArray; onChange?: ComposerPromptEditorProps["onChange"] | undefined; + onCommandKeyDown?: ComposerPromptEditorProps["onCommandKeyDown"] | undefined; }) { const [prompt, setPrompt] = useState({ value, cursor: value.length }); return ( @@ -58,6 +61,7 @@ function Composer({ onChange?.(...args); }} onPaste={() => {}} + onCommandKeyDown={onCommandKeyDown} /> ); } @@ -67,9 +71,16 @@ function composer( richTextEnabled = true, skills: ReadonlyArray = [], onChange?: ComposerPromptEditorProps["onChange"], + onCommandKeyDown?: ComposerPromptEditorProps["onCommandKeyDown"], ) { return ( - + ); } @@ -254,6 +265,55 @@ it.each([ }, ); +it.each([ + ["e", false, false], + ["i", false, false], + ["e", true, false], + ["e", false, true], +])( + "leaves Mod+%s to an app command bound to it instead of formatting (composer command: %s, declined capture command: %s)", + async (key, composerClaimsKey, declinedCapture) => { + const openUsage = vi.fn((event: KeyboardEvent) => { + if (declinedCapture) return false; + event.preventDefault(); + }); + using _commands = { + [Symbol.dispose]: registerCommands( + { "usage.open": openUsage }, + { + keybindings: () => [ + { + command: "usage.open", + shortcut: { + key, + metaKey: false, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: true, + }, + }, + ], + capture: declinedCapture, + }, + ), + }; + const composerCommand = vi.fn(() => composerClaimsKey); + await using screen = await mountEditor("word", true, [], undefined, composerCommand); + const { editor } = screen; + await act(async () => { + editor.commands.focus(); + editor.commands.setTextSelection({ from: 1, to: 5 }); + }); + await vi.waitFor(() => expect(document.activeElement).toBe(editor.view.dom)); + const modifier = isMacPlatform(navigator.platform) ? "Meta" : "Control"; + await userEvent.keyboard(`{${modifier}>}${key}{/${modifier}}`); + expect(composerCommand).toHaveBeenCalled(); + expect(openUsage).toHaveBeenCalledTimes(composerClaimsKey ? 0 : 1); + expect(serializeEditorDoc(editor.state.doc).value).toBe(declinedCapture ? "`word`" : "word"); + }, +); + it.each([false, true])( "composes an umlaut without wrapping the preedit text (rich text: %s)", async (richTextEnabled) => { diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 3761e6e8ea4ec..5895b63cbb9a0 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -112,7 +112,9 @@ import { } from "~/composer-undo-grouping"; import { collectInlineContextIds } from "~/lib/composerContextReferences"; import { resolveDiffThemeName } from "~/lib/diffRendering"; +import { isRichTextFormattingShortcut } from "~/keybindings"; import { cn, isMacPlatform } from "~/lib/utils"; +import { hasCommandForKeyDown } from "~/shortcuts/dispatcher"; import { basenameOfPath } from "~/pierre-icons"; import { WorkspaceEntryTooltip } from "./chat/WorkspaceEntryIcon"; import { FileTagChipContent } from "./chat/FileTagChip"; @@ -1107,6 +1109,19 @@ function ComposerPromptEditorTiptapInner( editable: !disabled, editorProps: { attributes: editorAttributes, + handleDOMEvents: { + // Composer commands keep precedence; otherwise true skips the editor's keymaps without + // preventDefault, so a bound app command still runs. + keydown: (_view, event) => { + if (!isRichTextFormattingShortcut(event)) return false; + if (readCallbacks().onCommandKeyDown?.(event.key, event)) { + event.preventDefault(); + event.stopPropagation(); + return true; + } + return hasCommandForKeyDown(event); + }, + }, handleKeyDown: (view, event) => { // In a right-to-left line the start is on the right. const backArrow = caretLineDirection(view.state) === "rtl" ? "ArrowRight" : "ArrowLeft"; diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index cf2be46dcbdcc..364adea75fc76 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -398,6 +398,13 @@ export function isRichTextBoldShortcut( ); } +/** Mod+B, Mod+I and Mod+E, the mark chords the rich-text composer binds. */ +export function isRichTextFormattingShortcut(event: ShortcutEventLike): boolean { + if (!(event.metaKey || event.ctrlKey) || event.altKey || event.shiftKey) return false; + const keys = resolveEventKeys(event); + return keys.has("b") || keys.has("i") || keys.has("e"); +} + export function isTerminalClearShortcut( event: ShortcutEventLike, platform = navigator.platform, diff --git a/apps/web/src/shortcuts/dispatcher.ts b/apps/web/src/shortcuts/dispatcher.ts index 5ce799cf482d5..9e361e825db7f 100644 --- a/apps/web/src/shortcuts/dispatcher.ts +++ b/apps/web/src/shortcuts/dispatcher.ts @@ -57,16 +57,21 @@ function isInsideConfirmation(target: EventTarget | null): boolean { return target instanceof Element && target.closest('[role="alertdialog"]') !== null; } -function runScope(scope: CommandScope, event: KeyboardEvent): boolean { +function scopeCommandHandler(scope: CommandScope, event: KeyboardEvent) { const { commands, options } = scope; - if (options.when && !options.when(event)) return false; - if (options.onKeyDown && options.onKeyDown(event) !== false) return true; const command = resolveShortcutCommand( event, options.keybindings?.() ?? appAtomRegistry.get(primaryServerKeybindingsAtom), { context: { ...readFocusContext(event), ...options.context?.() } }, ); - const handler = command === null ? undefined : commands[command]; + return command === null ? undefined : commands[command]; +} + +function runScope(scope: CommandScope, event: KeyboardEvent): boolean { + const { options } = scope; + if (options.when && !options.when(event)) return false; + if (options.onKeyDown && options.onKeyDown(event) !== false) return true; + const handler = scopeCommandHandler(scope, event); if (handler === undefined) return false; if (isInsideConfirmation(event.target)) { event.preventDefault(); @@ -75,6 +80,18 @@ function runScope(scope: CommandScope, event: KeyboardEvent): boolean { return handler(event) !== false; } +/** + * Whether a bubble-phase command is bound to this keydown, for widgets that would otherwise + * consume it. Capture scopes have already run (and declined) by the time a widget sees it. + */ +export function hasCommandForKeyDown(event: KeyboardEvent): boolean { + return globalScopes.some( + (scope) => + (!scope.options.when || scope.options.when(event)) && + scopeCommandHandler(scope, event) !== undefined, + ); +} + function runScopes(scopes: readonly CommandScope[], event: KeyboardEvent): boolean { for (let index = scopes.length - 1; index >= 0; index -= 1) { if (event.defaultPrevented) return true; From 338e73859abdaa0d88a39cdb06a56fe512c6a1d4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 16:59:17 -0800 Subject: [PATCH 043/253] fix(web): thread shortcuts work with the narrow sidebar closed (#23568) --- apps/web/src/components/Sidebar.motion.ts | 6 +++ .../components/sidebar/SidebarThreadRow.tsx | 11 ++-- .../sidebar/routeReveal.browser.test.tsx | 51 ++++++++++++++++++- .../web/src/components/sidebar/routeReveal.ts | 23 +++++++-- .../components/ui/sidebar.browser.test.tsx | 30 +++++++++++ apps/web/src/components/ui/sidebar.tsx | 27 +++++++--- 6 files changed, 132 insertions(+), 16 deletions(-) diff --git a/apps/web/src/components/Sidebar.motion.ts b/apps/web/src/components/Sidebar.motion.ts index fbc0d8434a82b..0e86c3c9a0e94 100644 --- a/apps/web/src/components/Sidebar.motion.ts +++ b/apps/web/src/components/Sidebar.motion.ts @@ -120,6 +120,12 @@ export function createSidebarListMotion(parent: HTMLUListElement) { return { update(animate: boolean) { if (disposed) return; + // A hidden list (the closed narrow sheet stays mounted) reports zero + // offsets, which would make the first pass after it opens animate every row. + if (parent.getClientRects().length === 0) { + suspend(); + return; + } const next = new Map( Array.from(parent.children) .filter((node): node is HTMLElement => node instanceof HTMLElement && !exiting.has(node)) diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 05e8984200470..1813eba805656 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -560,7 +560,7 @@ type SidebarThreadRowProps = { wokeAt: string | null; isActive: boolean; // Set on the active row only; scrolls it into view when a reveal is owed. - revealRef?: ((row: HTMLElement, threadKey: string) => void) | undefined; + revealRef?: ((row: HTMLElement, threadKey: string) => (() => void) | undefined) | undefined; // Unlike isActive, never true for the ancestor standing in for an open // subagent: drafts and PR clicks care about which composer is on screen. isRouteThread: boolean; @@ -668,8 +668,13 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP const { leaseLiveStatus, rowRef: leaseRowRef } = useSidebarRowSubscriptionLease(props.isActive); const { revealRef } = props; const rowRef = (row: HTMLElement | null) => { - if (row !== null) revealRef?.(row, threadKey); - return leaseRowRef(row); + const stopReveal = row === null ? undefined : revealRef?.(row, threadKey); + const releaseLease = leaseRowRef(row); + if (!stopReveal) return releaseLease; + return () => { + stopReveal(); + releaseLease?.(); + }; }; const isRegeneratingTitle = thread.titleRegeneration != null; const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]); diff --git a/apps/web/src/components/sidebar/routeReveal.browser.test.tsx b/apps/web/src/components/sidebar/routeReveal.browser.test.tsx index a87333e40ff08..a3b9c1f349e30 100644 --- a/apps/web/src/components/sidebar/routeReveal.browser.test.tsx +++ b/apps/web/src/components/sidebar/routeReveal.browser.test.tsx @@ -1,7 +1,8 @@ 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 { render } from "../../../test/render"; +import { Sidebar, SidebarProvider, SidebarTrigger, useSidebar } from "../ui/sidebar"; import { type SidebarRouteReveal, useActiveRowReveal } from "./routeReveal"; const ROW_HEIGHT_PX = 24; @@ -28,6 +29,12 @@ function RevealList(props: { ); } +// Reads the sidebar context like the real thread list, so opening the sheet re-renders it. +function SheetRevealList(props: Parameters[0]) { + useSidebar(); + return ; +} + const rowKeys = (count: number) => Array.from({ length: count }, (_, index) => `thread-${index}`); const newReveal = (): SidebarRouteReveal => ({ observedKey: null, pendingKey: null }); @@ -141,4 +148,46 @@ describe("useActiveRowReveal", () => { ); await expect.element(screen.getByText("thread-40", { exact: true })).toBeInViewport(); }); + + it("stops watching a hidden active row once it unmounts", async () => { + const reveal = newReveal(); + using observe = vi.spyOn(ResizeObserver.prototype, "observe"); + using unobserve = vi.spyOn(ResizeObserver.prototype, "unobserve"); + using disconnect = vi.spyOn(ResizeObserver.prototype, "disconnect"); + await using screen = await render( + , + // No router: the route arrives as the activeKey prop. + { router: false }, + ); + const row = screen.getByText("thread-40", { exact: true }).element(); + expect(observe).toHaveBeenCalledWith(row); + + // A widening viewport unmounts the closed sheet before it ever opens. + await screen.rerender(