diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs index 87a153f7b030d..8e79fceda4142 100644 --- a/.pnpmfile.cjs +++ b/.pnpmfile.cjs @@ -1,16 +1,22 @@ const fs = require("node:fs"); const path = require("node:path"); -// Our forks ship as tarballs in apps/mobile/deps. A pnpm patch on one is a second source of -// truth that the next tarball silently drops, so changes go to the fork (apps/mobile/deps/README.md). +// Our forks ship as tarballs in apps/mobile/deps and apps/web/deps. A pnpm patch on one is a +// second source of truth that the next tarball silently drops, so changes go to the fork (see +// the README beside each tarball). +const FORK_APPS = ["apps/mobile", "apps/web"]; + function forkTarballPatches(patchedDependencies) { - const manifestPath = path.join(__dirname, "apps/mobile/package.json"); - // Release staging installs a partial workspace without the mobile app. - if (!patchedDependencies || !fs.existsSync(manifestPath)) return []; - const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); - const forks = Object.keys(dependencies).filter((name) => - String(dependencies[name]).startsWith("file:deps/"), - ); + if (!patchedDependencies) return []; + const forks = FORK_APPS.flatMap((app) => { + const manifestPath = path.join(__dirname, app, "package.json"); + // Release staging installs a partial workspace without every app. + if (!fs.existsSync(manifestPath)) return []; + const { dependencies = {} } = JSON.parse(fs.readFileSync(manifestPath, "utf8")); + return Object.keys(dependencies).filter((name) => + String(dependencies[name]).startsWith("file:deps/"), + ); + }); return Object.keys(patchedDependencies).filter((key) => forks.some((name) => key === name || key.startsWith(`${name}@`)), ); @@ -23,7 +29,7 @@ module.exports = { if (forkPatches.length > 0) { throw new Error( `pnpm-workspace.yaml patches ${forkPatches.join(", ")}, which ships as a fork tarball in ` + - "apps/mobile/deps. Change the fork and replace the tarball instead (apps/mobile/deps/README.md).", + "an app's deps directory. Change the fork and replace the tarball instead (deps/README.md).", ); } // Windows installs need Linux x64 glibc binaries because WSL shares node_modules. diff --git a/README.md b/README.md index 3b4222b89623e..9e02113baa114 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ This is a fork of T3 Code that integrates a few additional features, including: - **Compact when idle for Claude threads:** a choice in Settings → Providers → Advanced → Compact idle threads. Besides compacting before the prompt cache expires, it compacts a large idle Claude thread (default 400K tokens or more) a set time (default 15 minutes) after the last message or answer from a user or a bot, so the compaction runs while no one waits for a reply. The token counts and the wait are set right under the choice. - **Prune idle worker threads:** `t3 prune-worker-threads` deletes the messages, turn items, nodes, plans and runtime requests of idle worker threads. A worker thread is idle when it has no open run and, in the last 7 days, was not created, had no run requested or ended, and had no turn item or message updated. A worker thread is a subagent thread that an agent started. Subagent threads that a bot starts are workers too. Threads a person opens, bot threads themselves and a person's forks are never workers. An idle worker keeps its rows while recovery still needs the worker, or while a thread that keeps its own rows names the worker as parent or fork source. Pruned threads keep their thread row, runs, parent link and pull request links, so they still show up and open with no messages. The command runs only when you call it, so run it daily to keep worker transcripts from piling up. Other threads still grow the database. With `--dry-run`, the command only prints how many threads it would empty and how many rows it would delete. You can run the command while the server runs. - **One way to start subagents in Claude and Codex threads:** T3 Code starts Claude and Codex sessions without the provider's own subagent tools: Claude's `Agent`, `Workflow`, `SendMessage` and `ListAgents`, and Codex's `spawn_agent` with its other collaboration tools. The agent starts every subagent, same provider and model included, with T3 Code's `delegate_task` tool, so each child is a T3 Code thread that you can open and follow. -- **Files remember where you stopped reading:** a file in the right panel opens where you left it when you switch back to its tab, close and reopen it, or reload the app. This covers code, Markdown, PDFs, large text files, CSV and TSV tables, HTML pages, Word and PowerPoint files, the first sheet of an Excel or ODS spreadsheet, notebooks, Mermaid diagrams and chat attachments; video and audio come back paused at the time you left. If the file changed, it opens at the same place, or at its start or end when that place is gone. Places stay in this browser for 30 days. A link to a line still jumps to that line once. PDFs in the right panel open in T3 Code's own PDF viewer, also in Chrome and Edge on the desktop. Image zoom, fonts, archives, SQLite files, ODT, ODP, RTF and EPUB files, HTML attachments and the other sheets of a spreadsheet still open at the top. A place in a notebook cell after the first 20 opens at the end of cell 20. +- **Files remember where you stopped reading:** a file in the right panel opens where you left it when you switch back to its tab, close and reopen it, or reload the app. This covers code, Markdown source, PDFs, large text files, CSV and TSV tables, HTML pages, Word and PowerPoint files, the first sheet of an Excel or ODS spreadsheet, notebooks, Mermaid diagrams and chat attachments; video and audio come back paused at the time you left. If the file changed, it opens at the same place, or at its start or end when that place is gone. Places stay in this browser for 30 days. A link to a line still jumps to that line once. PDFs in the right panel open in T3 Code's own PDF viewer, also in Chrome and Edge on the desktop. Image zoom, fonts, archives, SQLite files, ODT, ODP, RTF and EPUB files, HTML attachments, the other sheets of a spreadsheet and rendered workspace Markdown still open at the top. Text files of 1 MB to 64 MB open in source view in parts after the first megabyte, so past 1 MB a saved place may not be restored and a line link may stop at the end of the text loaded so far. [Issue #264](https://github.com/orbitingflea/t3code/issues/264) tracks support for rendered workspace Markdown and these 1 MB to 64 MB text files. A place in a notebook cell after the first 20 opens at the end of cell 20. - **Reflink worktrees on Linux:** Settings → Worktrees → Reflink worktrees (on by default) clones new worktrees copy-on-write from a cache of recent checkouts on the worktree location's drive, so worktrees share disk space until files change. Drives that cannot clone, such as ext4, use Git's normal checkout. - **FYI messages between agents:** an agent can send another thread an FYI, a note of at most 16,000 characters that needs no action and starts no turn. The receiving agent gets it with its next turn; a running Claude Code thread gets it at its next tool call. An FYI counts as delivered only when the turn that carries it finishes: a turn that fails, is stopped, restarts or is reverted gives it back, so the agent may see it twice. When a thread has an FYI waiting and has been idle for 6 hours, T3 Code wakes it to deliver its FYIs, unless the thread is settled, archived, waiting for your answer or holds queued messages; a snoozed thread waits until its snooze ends. The 6 hours count from the thread's last turn, or from the reset of a usage limit that stopped it on the provider it still uses (or from the end of a snooze that ends after that reset), so an FYI to a thread that has been idle longer wakes it within minutes. A thread whose usage limit has no known reset time, or whose provider fails every turn, gets a failed wake every 6 hours while an FYI waits. A wake carries up to 16,000 characters of FYIs. The rest, and any that a wake gives back because it failed or you stopped it, get another wake after 6 more idle hours. A wake is a new turn, so **Resume** no longer continues a turn that ended before it. Settle or archive a thread to stop its wakes. The timeline marks these messages "FYI · waiting", "FYI · sent" while the turn that carries them runs, and "FYI" once it finished. - **Open server files by their path:** in a browser signed in to T3 Code at its own address, open `/` (such as `https://t3.example.com/home/ana/work/report.html`) to see that file read-only, for files under the server user's home folder and temp folder. A session needs the `filesystem:read` permission, and a signed-out browser gets a sign-in page. Text and code of any type show as plain text, and images, PDFs, audio and video show as themselves. A folder shows its `index.html`, or else a list of its files. Links ending in `:line` or `:line:col` open the file. Names that start with `.`, and T3 Code's own data folder, are not served. An HTML page runs in a sandboxed frame at the same address: its scripts run but cannot act as you in T3, and it loads files from its own folder and below for an hour, though its scripts cannot fetch them. A page directly in the home or temp folder loads no other files. An HTML page linked from another site, or any HTML page over plain HTTP, first shows an Open link. diff --git a/apps/desktop/src/app/DesktopCliShim.test.ts b/apps/desktop/src/app/DesktopCliShim.test.ts index 929148fdbb32f..dda8e058b7179 100644 --- a/apps/desktop/src/app/DesktopCliShim.test.ts +++ b/apps/desktop/src/app/DesktopCliShim.test.ts @@ -66,10 +66,11 @@ const fakeAppImage = (canMount = true, app = REPORTER) => { return { root, image, appImage, shim }; }; -// Stays up after a signal until the test lets it finish, like a server shutting down. +// Stays up after a signal until the test lets it finish, like a server shutting down. A group +// signal and the launcher's forwarded one can both arrive; a re-run trap would read stdin's EOF. const SLOW_SERVER = [ "#!/bin/sh", - "trap 'echo stopping >&3; read go; echo \"stopped $go\" >&3; exit 7' TERM HUP", + 'trap \'trap "" TERM HUP; echo stopping >&3; read go; echo "stopped $go" >&3; exit 7\' TERM HUP', "echo ready", "while :; do sleep 0.05; done", "", diff --git a/apps/desktop/src/electron/ElectronMenu.test.ts b/apps/desktop/src/electron/ElectronMenu.test.ts new file mode 100644 index 0000000000000..df98bdf4e9e85 --- /dev/null +++ b/apps/desktop/src/electron/ElectronMenu.test.ts @@ -0,0 +1,45 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import type * as Electron from "electron"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import { vi } from "vite-plus/test"; + +const { menu } = vi.hoisted(() => ({ + menu: { template: [] as Electron.MenuItemConstructorOptions[] }, +})); + +vi.mock("electron", () => ({ + Menu: { + buildFromTemplate: (template: Electron.MenuItemConstructorOptions[]) => { + menu.template = template; + return { popup: (options: Electron.PopupOptions) => options.callback?.() }; + }, + }, +})); + +import * as ElectronMenu from "./ElectronMenu.ts"; + +describe("ElectronMenu", () => { + it.effect("shows ampersands in labels instead of reading them as mnemonics", () => + Effect.gen(function* () { + const electronMenu = yield* ElectronMenu.make; + yield* electronMenu.showContextMenu({ + window: { webContents: { getZoomFactor: () => 1 } } as Electron.BrowserWindow, + items: [ + { id: "filter", label: "Filter by R&D" }, + { id: "more", label: "A&B", children: [{ id: "child", label: "C && D" }] }, + ], + position: Option.none(), + source: Option.none(), + }); + + assert.deepEqual( + menu.template.map((item) => item.label), + ["Filter by R&&D", "A&&B"], + ); + const submenu = menu.template[1]!.submenu as Electron.MenuItemConstructorOptions[]; + assert.equal(submenu[0]!.label, "C &&&& D"); + }).pipe(Effect.provideService(HostProcess.Platform, "win32")), + ); +}); diff --git a/apps/desktop/src/electron/ElectronMenu.ts b/apps/desktop/src/electron/ElectronMenu.ts index 540326346edf8..873281685054d 100644 --- a/apps/desktop/src/electron/ElectronMenu.ts +++ b/apps/desktop/src/electron/ElectronMenu.ts @@ -168,7 +168,8 @@ export const make = Effect.gen(function* () { } const itemOption: Electron.MenuItemConstructorOptions = { - label: item.label, + // Electron reads a single & as a mnemonic marker and drops it. + label: item.label.replaceAll("&", "&&"), enabled: !item.disabled, ...(typeof item.checked === "boolean" ? { type: "checkbox", checked: item.checked } : {}), }; diff --git a/apps/desktop/src/electron/ElectronProtocol.ts b/apps/desktop/src/electron/ElectronProtocol.ts index 7563898f43efc..43208638f12d8 100644 --- a/apps/desktop/src/electron/ElectronProtocol.ts +++ b/apps/desktop/src/electron/ElectronProtocol.ts @@ -20,7 +20,7 @@ export function getDesktopScheme(isDevelopment: boolean): string { return isDevelopment ? DESKTOP_DEVELOPMENT_SCHEME : DESKTOP_PRODUCTION_SCHEME; } -function getDesktopOrigin(isDevelopment: boolean): string { +export function getDesktopOrigin(isDevelopment: boolean): string { return `${getDesktopScheme(isDevelopment)}://${DESKTOP_HOST}`; } diff --git a/apps/desktop/src/window/DesktopWindow.test.ts b/apps/desktop/src/window/DesktopWindow.test.ts index f2b655b1b69d8..e4e426b1975ae 100644 --- a/apps/desktop/src/window/DesktopWindow.test.ts +++ b/apps/desktop/src/window/DesktopWindow.test.ts @@ -74,6 +74,12 @@ function makeFakeBrowserWindow() { const webContentsListeners = new Map void>(); let zoomLevel = 0; const webContents = { + id: 1, + session: { + webRequest: { + onBeforeSendHeaders: vi.fn(), + }, + }, copyImageAt: vi.fn(), focus: vi.fn(), isDestroyed: vi.fn(() => false), diff --git a/apps/desktop/src/window/DesktopWindow.ts b/apps/desktop/src/window/DesktopWindow.ts index 880b9dfef4ab9..c99fbb52c49e2 100644 --- a/apps/desktop/src/window/DesktopWindow.ts +++ b/apps/desktop/src/window/DesktopWindow.ts @@ -14,12 +14,13 @@ import { msg } from "gt-i18n"; import { type DesktopSnapShotEvent, DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts"; import * as DesktopAssets from "../app/DesktopAssets.ts"; +import * as DesktopClerk from "../app/DesktopClerk.ts"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; import * as DesktopPrimaryPaste from "../app/DesktopPrimaryPaste.ts"; import { makeComponentLogger } from "../app/DesktopObservability.ts"; import * as DesktopState from "../app/DesktopState.ts"; import * as ElectronMenu from "../electron/ElectronMenu.ts"; -import { getDesktopUrl } from "../electron/ElectronProtocol.ts"; +import { getDesktopOrigin, getDesktopUrl } from "../electron/ElectronProtocol.ts"; import * as ElectronShell from "../electron/ElectronShell.ts"; import * as ElectronTheme from "../electron/ElectronTheme.ts"; import * as ElectronWindow from "../electron/ElectronWindow.ts"; @@ -44,6 +45,7 @@ import { m } from "../i18n/messages.ts"; import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts"; import { makeQuitShortcutHandler } from "./QuitHold.ts"; import { copyContextMenuImage } from "./ContextMenuImage.ts"; +import { installMainWindowRemoteRequestHeaderPolicy } from "./RemoteRequestHeaders.ts"; const TITLEBAR_HEIGHT = 40; @@ -408,6 +410,7 @@ export const make = Effect.gen(function* () { Effect.suspend(() => pendingMainReveals.get(window) ?? electronWindow.reveal(window)), ); let flushMainWindowBounds: Effect.Effect = Effect.void; + let remoteRequestHeaderOwner: Electron.BrowserWindow | null = null; const dismissConnectingSplash = Effect.gen(function* () { const splash = yield* Ref.getAndSet(splashWindowRef, Option.none()); @@ -1036,6 +1039,19 @@ export const make = Effect.gen(function* () { // Desktop IPC only answers the main window, so register it before its renderer can call in. yield* electronWindow.setMain(window); + remoteRequestHeaderOwner = window; + const detachRemoteRequestHeaders = installMainWindowRemoteRequestHeaderPolicy( + window.webContents.session, + { + desktopOrigin: getDesktopOrigin(environment.isDevelopment), + mainWebContentsId: window.webContents.id, + clerkFrontendApiHostname: DesktopClerk.desktopClerkFrontendApiHostname, + devServerOrigin: Option.getOrUndefined( + Option.map(environment.devServerUrl, (url) => url.origin), + ), + isDevelopment: environment.isDevelopment, + }, + ); loadApplication(); if (environment.isDevelopment) { window.webContents.openDevTools({ mode: "detach" }); @@ -1045,6 +1061,10 @@ export const make = Effect.gen(function* () { if (!backendHasStarted) mainClosedDuringStartup = true; clearDevelopmentLoadRetry(); clearBoundsPersist(); + if (remoteRequestHeaderOwner === window) { + remoteRequestHeaderOwner = null; + detachRemoteRequestHeaders(); + } void runPromise(electronWindow.clearMain(Option.some(window))); }); diff --git a/apps/desktop/src/window/RemoteRequestHeaders.test.ts b/apps/desktop/src/window/RemoteRequestHeaders.test.ts new file mode 100644 index 0000000000000..fee9aedb16c63 --- /dev/null +++ b/apps/desktop/src/window/RemoteRequestHeaders.test.ts @@ -0,0 +1,186 @@ +import { assert, describe, it } from "@effect/vitest"; + +import { + stripDesktopOriginHeaders, + type MainWindowRequestHeaderPolicy, +} from "./RemoteRequestHeaders.ts"; + +const packagedPolicy: MainWindowRequestHeaderPolicy = { + desktopOrigin: "t3code://app", + mainWebContentsId: 42, + clerkFrontendApiHostname: "clerk.t3.codes", + isDevelopment: false, +}; + +const devPolicy: MainWindowRequestHeaderPolicy = { + desktopOrigin: "t3code-dev://app", + mainWebContentsId: 42, + clerkFrontendApiHostname: "clerk.t3.codes", + devServerOrigin: "http://devbox.internal:5733", + isDevelopment: true, +}; + +describe("RemoteRequestHeaders", () => { + it.each([ + "https://remote.example.com/.well-known/t3/environment", + "http://127.0.0.1:8080/api/auth/bootstrap", + "ws://127.0.0.1:8080/ws?ticket=abc", + "wss://remote.example.com/ws?ticket=abc", + ])("strips Origin and Sec-Fetch-* on outbound main-window %s requests", (url) => { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + "Sec-Fetch-Mode": "cors", + "Sec-Fetch-Dest": "empty", + "sec-fetch-user": "?1", + Authorization: "Bearer secret", + DPoP: "proof-jwt", + }, + }); + + assert.deepEqual(headers, { + Authorization: "Bearer secret", + DPoP: "proof-jwt", + }); + }); + + it("strips lowercase origin headers and allows null frames (WebSocket upgrades and workers)", () => { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url: "wss://remote.example.com/ws", + webContentsId: 42, + frame: null, + requestHeaders: { + origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + Upgrade: "websocket", + }, + }); + + assert.deepEqual(headers, { + Upgrade: "websocket", + }); + }); + + it("preserves headers for Clerk frontend API requests", () => { + for (const url of ["https://clerk.t3.codes/v1/client", "https://CLERK.T3.CODES./v1/client"]) { + const headers = stripDesktopOriginHeaders(packagedPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }); + assert.isUndefined(headers); + } + }); + + it("preserves headers for dev loopback and exact devServerOrigin, while stripping other ports and remote hosts", () => { + for (const url of [ + "http://localhost:3773/api/health", + "http://app.localhost:3773/api/health", + "http://127.0.0.1:3773/api/health", + "http://[::1]:3773/api/health", + "ws://127.0.0.1:3773/ws", + "http://devbox.internal:5733/api/health", + "ws://devbox.internal:5733/ws", + ]) { + assert.isUndefined( + stripDesktopOriginHeaders(devPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code-dev://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + } + + for (const url of [ + "http://devbox.internal:8080/api/auth/bootstrap", + "https://remote.example.com/api/auth/bootstrap", + ]) { + assert.deepEqual( + stripDesktopOriginHeaders(devPolicy, { + url, + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code-dev://app", + "Sec-Fetch-Site": "cross-site", + "Content-Type": "application/json", + }, + }), + { "Content-Type": "application/json" }, + ); + } + }); + + it("never touches sandboxed iframes (Origin: null), subframes, or other webContents", () => { + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + Origin: "null", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: {} }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 99, + frame: { parent: null }, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: undefined, + frame: null, + requestHeaders: { + Origin: "t3code://app", + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + + assert.isUndefined( + stripDesktopOriginHeaders(packagedPolicy, { + url: "https://remote.example.com/api/test", + webContentsId: 42, + frame: { parent: null }, + requestHeaders: { + "Sec-Fetch-Site": "cross-site", + }, + }), + ); + }); +}); diff --git a/apps/desktop/src/window/RemoteRequestHeaders.ts b/apps/desktop/src/window/RemoteRequestHeaders.ts new file mode 100644 index 0000000000000..61df4c3535160 --- /dev/null +++ b/apps/desktop/src/window/RemoteRequestHeaders.ts @@ -0,0 +1,129 @@ +import * as NetAddress from "effect/net/NetAddress"; +import * as Result from "effect/Result"; +import type * as Electron from "electron"; + +// `*://` matches only http and https, so WebSocket schemes are listed separately. +const REMOTE_REQUEST_URL_PATTERNS = ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"]; + +export interface MainWindowRequestHeaderPolicy { + readonly desktopOrigin: string; + readonly mainWebContentsId: number; + readonly clerkFrontendApiHostname?: string | undefined; + readonly devServerOrigin?: string | undefined; + readonly isDevelopment: boolean; +} + +export interface MainWindowRequestHeaderDetails { + readonly url: string; + readonly webContentsId?: number | undefined; + readonly frame?: { readonly parent: unknown } | null | undefined; + readonly requestHeaders: Record; +} + +function normalizeHostname(hostname: string): string { + return hostname + .toLowerCase() + .replace(/^\[(.*)\]$/, "$1") + .replace(/\.$/, ""); +} + +function isLoopbackHostname(hostname: string): boolean { + return ( + hostname === "localhost" || + hostname.endsWith(".localhost") || + Result.match(NetAddress.ipFromString(hostname), { + onSuccess: NetAddress.isLoopback, + onFailure: () => false, + }) + ); +} + +function toHttpOrigin(url: URL): string { + if (url.protocol === "ws:") { + return `http://${url.host}`; + } + if (url.protocol === "wss:") { + return `https://${url.host}`; + } + return url.origin; +} + +function isSubframe(details: MainWindowRequestHeaderDetails): boolean { + try { + return details.frame != null && details.frame.parent !== null; + } catch { + return true; + } +} + +function hasExactDesktopOriginHeader( + requestHeaders: Record, + desktopOrigin: string, +): boolean { + let matched = false; + for (const [name, value] of Object.entries(requestHeaders)) { + if (name.toLowerCase() !== "origin") continue; + if (value !== desktopOrigin) return false; + matched = true; + } + return matched; +} + +function shouldPreserveOriginHeader(policy: MainWindowRequestHeaderPolicy, url: URL): boolean { + const hostname = normalizeHostname(url.hostname); + if ( + policy.clerkFrontendApiHostname !== undefined && + hostname === normalizeHostname(policy.clerkFrontendApiHostname) + ) { + return true; + } + if (!policy.isDevelopment) return false; + if (policy.devServerOrigin !== undefined && toHttpOrigin(url) === policy.devServerOrigin) { + return true; + } + return isLoopbackHostname(hostname); +} + +/** + * Strips Electron's synthetic `Origin` (`t3code://app`) and `Sec-Fetch-*` headers on outbound + * main-window requests so origin-checking reverse proxies treat Desktop like native T3 clients. + */ +export function stripDesktopOriginHeaders( + policy: MainWindowRequestHeaderPolicy, + details: MainWindowRequestHeaderDetails, +): Record | undefined { + if (details.webContentsId !== policy.mainWebContentsId) return undefined; + if (isSubframe(details)) return undefined; + if (!hasExactDesktopOriginHeader(details.requestHeaders, policy.desktopOrigin)) { + return undefined; + } + + const parsedUrl = URL.parse(details.url); + if (parsedUrl === null || shouldPreserveOriginHeader(policy, parsedUrl)) { + return undefined; + } + + const nextHeaders: Record = {}; + for (const [name, value] of Object.entries(details.requestHeaders)) { + const lowerName = name.toLowerCase(); + if (lowerName === "origin" || lowerName.startsWith("sec-fetch-")) continue; + nextHeaders[name] = value; + } + return nextHeaders; +} + +export function installMainWindowRemoteRequestHeaderPolicy( + session: Pick, + policy: MainWindowRequestHeaderPolicy, +): () => void { + session.webRequest.onBeforeSendHeaders( + { urls: REMOTE_REQUEST_URL_PATTERNS }, + (details, callback) => { + const requestHeaders = stripDesktopOriginHeaders(policy, details); + callback(requestHeaders === undefined ? {} : { requestHeaders }); + }, + ); + return () => { + session.webRequest.onBeforeSendHeaders(null); + }; +} diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index a563b6a4ee3a7..470091f334fb7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -555,8 +555,40 @@ describe("parseResolvedPath", () => { // Path.layer joins with POSIX separators here, so the test windir is a POSIX path. const WSL_EXE = "/windows/System32/wsl.exe"; +const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; +const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; + +const registrySpawner = (keys: ReadonlyArray) => + ChildProcessSpawner.make((command) => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode( + command._tag === "StandardCommand" && + command.command === "reg.exe" && + keys.some((key) => command.args.includes(key)) + ? 0 + : 1, + ), + ), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); -const isAvailable = (policy?: Parameters[0]) => +const isAvailable = ( + policy?: Parameters[0], + serviceKeys: ReadonlyArray = [STORE_SERVICE], +) => makeIsAvailable("win32", "/windows").pipe( Effect.provide( Layer.mergeAll( @@ -565,9 +597,17 @@ const isAvailable = (policy?: Parameters[ DesktopManagedPolicy.layerTest(policy), ), ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, registrySpawner(serviceKeys)), ); describe("makeIsAvailable", () => { + it.effect("needs a registered WSL service, not just the System32 install stub", () => + Effect.gen(function* () { + assert.isFalse(yield* isAvailable(undefined, [])); + assert.isTrue(yield* isAvailable(undefined, [INBOX_SERVICE])); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index f1d2fccde537b..9d9540a65dc7d 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1119,13 +1119,50 @@ const getUserHomeImpl = ( Effect.orElseSucceed(() => Option.none()), ); +// Store/MSI WSL registers WSLService and inbox WSL registers LxssManager; either key means installed. +const WSL_SERVICE_KEYS = [ + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", +] as const; +const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); + +const wslServiceRegistered = Effect.scoped( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const registered = yield* Effect.forEach( + WSL_SERVICE_KEYS, + (key) => + spawner + .spawn( + ChildProcess.make("reg.exe", ["query", key], { + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + killSignal: "SIGTERM", + forceKillAfter: PROCESS_TERMINATE_GRACE, + }), + ) + .pipe(Effect.flatMap((handle) => handle.exitCode)), + { concurrency: "unbounded" }, + ); + return registered.some((exitCode) => (exitCode as unknown as number) === 0); + }), +).pipe( + Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.orElseSucceed(() => false), +); + export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* ( platform: NodeJS.Platform, windir: string, ): Effect.fn.Return< boolean, never, - FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy + | FileSystem.FileSystem + | Path.Path + | DesktopManagedPolicy.DesktopManagedPolicy + | ChildProcessSpawner.ChildProcessSpawner > { if (platform !== "win32") return false; const path = yield* Path.Path; @@ -1134,6 +1171,8 @@ export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable" if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) { return false; } + // System32\wsl.exe is also an install stub on Windows without WSL, so check for its service. + if (!(yield* wslServiceRegistered)) return false; // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none. return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( Effect.map((found) => found === undefined), @@ -1245,6 +1284,7 @@ export const layer = Layer.effect( // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O. const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, environment.path), Effect.provideService( DesktopManagedPolicy.DesktopManagedPolicy, diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift index c54a1a84e9644..d07908a4b27fa 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorModule.swift @@ -117,6 +117,7 @@ public class T3ComposerEditorModule: Module { "onComposerBlur", "onComposerSubmit", "onComposerPasteImages", + "onComposerPasteImagesPending", "onComposerContextPress", "onComposerPasteContext", "onComposerPasteText", diff --git a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift index 253376fe5e4d3..2f24b0d98752c 100644 --- a/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift +++ b/apps/mobile/modules/t3-composer-editor/ios/T3ComposerEditorView.swift @@ -86,6 +86,8 @@ private final class ComposerTextView: UITextView { ]) var onPasteImages: (([String]) -> Void)? + /// Change in how many pasted images are still loading: +n when a paste is accepted, -n once it settles. + var onPasteImagesPending: ((Int) -> Void)? var onPasteContext: (([String: String]) -> Void)? var onPasteText: ((String, NSRange) -> Void)? var clipboardFragment = "" @@ -308,6 +310,8 @@ private final class ComposerTextView: UITextView { } func loadImages(from providers: [NSItemProvider]) { + guard !providers.isEmpty else { return } + onPasteImagesPending?(providers.count) let group = DispatchGroup() let lock = NSLock() var images = [(data: Data, fileExtension: String)?](repeating: nil, count: providers.count) @@ -325,10 +329,11 @@ private final class ComposerTextView: UITextView { store((object as? UIImage)?.pngData().map { ($0, "png") }) } } - // Decoding a GIF to UIImage keeps only its first frame, so pass its bytes through. - if provider.hasItemConformingToTypeIdentifier(UTType.gif.identifier) { - _ = provider.loadDataRepresentation(forTypeIdentifier: UTType.gif.identifier) { data, _ in - if let data { store((data, "gif")) } else { loadPNG() } + // Re-encoding a photo as PNG inflates it several times and keeps only a GIF's first frame, + // so pass the provider's own encoding through when it is one the attachment path reads. + if let original = Self.passthroughImageType(of: provider) { + _ = provider.loadDataRepresentation(forTypeIdentifier: original.type.identifier) { data, _ in + if let data { store((data, original.fileExtension)) } else { loadPNG() } } } else { loadPNG() @@ -336,7 +341,11 @@ private final class ComposerTextView: UITextView { } group.notify(queue: .main) { [weak self] in - guard let self, !self.isReadOnly else { + guard let self else { + return + } + defer { self.onPasteImagesPending?(-providers.count) } + guard !self.isReadOnly else { return } let urls = images.compactMap { $0 }.compactMap { @@ -418,6 +427,23 @@ private final class ComposerTextView: UITextView { return sourceOffset } + private static let passthroughImageTypes: [(type: UTType, fileExtension: String)] = [ + (.gif, "gif"), (.jpeg, "jpg"), (.heic, "heic"), (.png, "png"), (.webP, "webp"), + ] + + /// Providers list representations best first, so the first supported one is the original. + private static func passthroughImageType( + of provider: NSItemProvider + ) -> (type: UTType, fileExtension: String)? { + for identifier in provider.registeredTypeIdentifiers { + guard let registered = UTType(identifier) else { continue } + if let match = passthroughImageTypes.first(where: { registered.conforms(to: $0.type) }) { + return match + } + } + return nil + } + private static func writeTemporaryImage(_ image: UIImage) -> String? { image.pngData().flatMap { writeTemporaryImage($0, fileExtension: "png") } } @@ -507,6 +533,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro let onComposerBlur = EventDispatcher() let onComposerSubmit = EventDispatcher() let onComposerPasteImages = EventDispatcher() + let onComposerPasteImagesPending = EventDispatcher() let onComposerContextPress = EventDispatcher() let onComposerPasteContext = EventDispatcher() let onComposerPasteText = EventDispatcher() @@ -537,6 +564,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate, UITextDro textView.onPasteImages = { [weak self] urls in self?.onComposerPasteImages(["uris": urls]) } + textView.onPasteImagesPending = { [weak self] delta in + self?.onComposerPasteImagesPending(["delta": delta]) + } textView.onPasteContext = { [weak self] context in guard let self else { return } let selection = self.sourceSelection() diff --git a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift index 6b69f29d308d5..83c1920bfd133 100644 --- a/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift +++ b/apps/mobile/modules/t3-composer-editor/tests/ios/main.swift @@ -271,6 +271,17 @@ gifEditor.onPasteImages = { urls in exit(0) } +// A provider that finishes on a later main-queue turn, like a full-size photo still loading. +private let deferredPNG = image.pngData()! +private let deferredProvider = NSItemProvider() +deferredProvider.registerDataRepresentation(forTypeIdentifier: UTType.png.identifier, visibility: .all) { completion in + DispatchQueue.main.async { completion(deferredPNG, nil) } + return nil +} +private var pendingDeltas: [Int] = [] +private let deferredEditor = ComposerTextView() +deferredEditor.onPasteImagesPending = { pendingDeltas.append($0) } + // Inline provider completion places the attachment callback before this main-queue check. DispatchQueue.main.async { check(pastedImages.count == 1, "An accepted provider-based paste must emit exactly one attachment batch") @@ -287,7 +298,16 @@ DispatchQueue.main.async { "The attachment must contain the pasted image's pixels") check(pasteEditor.text == "Keep this draft", "Image paste must preserve the draft text") print("Composer provider-paste checks passed") - check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path") - gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)]) + deferredEditor.onPasteImages = { urls in + urls.compactMap(URL.init(string:)).forEach { try? FileManager.default.removeItem(at: $0) } + DispatchQueue.main.async { + check(pendingDeltas == [1, -1], "A finished paste must settle its preparation: \(pendingDeltas)") + print("Composer paste-preparation checks passed") + check(gifProvider.canLoadObject(ofClass: UIImage.self), "A GIF provider must take the image paste path") + gifEditor.paste(itemProviders: [gifProvider, ImmediateImageProvider(image: image)]) + } + } + deferredEditor.paste(itemProviders: [deferredProvider]) + check(pendingDeltas == [1], "Preparation must be reported before the provider finishes: \(pendingDeltas)") } dispatchMain() diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt index b4183cb3c8fcf..3b45931f87eb3 100644 --- a/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt +++ b/apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3WorkspaceNavigationModule.kt @@ -416,6 +416,7 @@ class T3WorkspaceNavigationView( "threads" -> "Chats" "pullRequests" -> "Pulls" "issues" -> "Issues" + "workflows" -> "Workflows" "usage" -> "Usage" else -> "Settings" } @@ -429,6 +430,7 @@ class T3WorkspaceNavigationView( "threads" -> R.drawable.t3_chats "pullRequests" -> R.drawable.t3_pull_requests "issues" -> R.drawable.t3_issues + "workflows" -> R.drawable.t3_workflows "usage" -> R.drawable.t3_usage else -> R.drawable.t3_settings } diff --git a/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_workflows.xml b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_workflows.xml new file mode 100644 index 0000000000000..a6f6ea7edcfc5 --- /dev/null +++ b/apps/mobile/modules/t3-native-controls/android/src/main/res/drawable/t3_workflows.xml @@ -0,0 +1,3 @@ + + + diff --git a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift index 9df738d37fa67..666f59df83485 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3SidebarTabBarView.swift @@ -109,9 +109,15 @@ final class T3SidebarTabBarView: ExpoView, UITabBarDelegate { private func prepareItems() { let iconBundle = Bundle(for: Self.self).url(forResource: "T3NativeControlIcons", withExtension: "bundle").flatMap(Bundle.init(url:)) let pullRequestIcon = UIImage(named: "pull-request", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) - let labels = ["threads": "Chats", "pullRequests": "PRs", "issues": "Issues", "usage": "Usage", "settings": "Settings"] + let labels = [ + "threads": "Chats", "pullRequests": "PRs", "issues": "Issues", "workflows": "Workflows", + "usage": "Usage", "settings": "Settings", + ] let issueIcon = UIImage(named: "issue", in: iconBundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate) - let symbols = ["threads": "text.bubble", "usage": "chart.bar.xaxis", "settings": "gearshape"] + let symbols = [ + "threads": "text.bubble", "workflows": "point.3.connected.trianglepath.dotted", + "usage": "chart.bar.xaxis", "settings": "gearshape", + ] for (tab, label) in labels { let icon = tab == "pullRequests" ? pullRequestIcon : tab == "issues" ? issueIcon : UIImage(systemName: symbols[tab] ?? "circle") let item = UITabBarItem(title: nil, image: tabIcon(icon), tag: 0) diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt index d86861018c77d..3334efd268bc3 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/ReviewDiffCanvasDrawing.kt @@ -70,6 +70,11 @@ internal class ReviewDiffCanvasDrawing(context: Context) { ) } + fun fileHeaderCheckboxHitRect(top: Int, bottom: Int, width: Int, style: DiffStyle): RectF { + val checkbox = fileHeaderCheckboxRect(top, bottom, width, style) + return RectF(checkbox.left - 14f * density, top.toFloat(), width.toFloat(), bottom.toFloat()) + } + fun drawDisclosureChevron( canvas: Canvas, rect: RectF, diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index e2d5a12d76304..2888917a89044 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -766,7 +766,7 @@ private class DiffCanvasView(context: Context) : View(context) { rowHitAt(event.y)?.let { hit -> val target = if ( hit.row.kind == "file" && - drawing.fileHeaderCheckboxRect( + drawing.fileHeaderCheckboxHitRect( hit.top, hit.bottom, width, diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 0c65ddf19460a..07d9a58a3553c 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -1029,6 +1029,7 @@ private struct ReviewDiffFileHeaderInteractiveRects { let chevron: CGRect let icon: CGRect let checkbox: CGRect + let checkboxHitTarget: CGRect } private struct ReviewDiffStickyFileHeaderIndex { @@ -1643,7 +1644,7 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let interactiveRects = fileHeaderInteractiveRects(for: row, cardRect: rect) let fileId = resolvedFileId(for: row) - if interactiveRects.checkbox.contains(point) { + if interactiveRects.checkboxHitTarget.contains(point) { onToggleViewedFile?(fileId) return } @@ -2349,10 +2350,17 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { let chevronRect = CGRect(x: cardRect.minX + horizontalPadding, y: centerY - 10, width: 20, height: 20) let iconRect = CGRect(x: chevronRect.maxX + 8, y: centerY - 10, width: 20, height: 20) let checkboxRect = CGRect(x: cardRect.maxX - horizontalPadding - 20, y: centerY - 10, width: 20, height: 20) + let checkboxHitMinX = checkboxRect.minX - 14 return ReviewDiffFileHeaderInteractiveRects( chevron: chevronRect, icon: iconRect, - checkbox: checkboxRect + checkbox: checkboxRect, + checkboxHitTarget: CGRect( + x: checkboxHitMinX, + y: cardRect.minY, + width: cardRect.maxX - checkboxHitMinX, + height: cardRect.height + ) ) } diff --git a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt index f2992979bf522..63e1acece9074 100644 --- a/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt +++ b/apps/mobile/modules/t3-review-diff/tests/android/src/test/kotlin/expo/modules/t3reviewdiff/ReviewDiffGeometryTest.kt @@ -149,6 +149,18 @@ class ReviewDiffGeometryTest { } } + @Test + fun viewedCheckboxHitTargetSpansTheHeaderHeightAndTrailingEdge() { + val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) + val style = DiffStyle.defaults(1f) + val glyph = drawing.fileHeaderCheckboxRect(100, 144, 320, style) + val hit = drawing.fileHeaderCheckboxHitRect(100, 144, 320, style) + assertTrue(hit.contains(glyph)) + assertTrue(hit.contains(glyph.left - 13f, 101f)) + assertTrue(hit.contains(319f, 143f)) + assertTrue(!hit.contains(glyph.left - 15f, 122f)) + } + @Test fun asciiWidthCacheDoesNotRetainPerRowMeasurementObjects() { val drawing = ReviewDiffCanvasDrawing(RuntimeEnvironment.getApplication()) diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx index 42403edbb1e7d..38eba55e812ed 100644 --- a/apps/mobile/src/Stack.tsx +++ b/apps/mobile/src/Stack.tsx @@ -139,6 +139,8 @@ import { SettingsProjectGroupingRouteScreen } from "./features/settings/Settings import { SettingsProjectOverviewRouteScreen } from "./features/settings/SettingsProjectOverviewRouteScreen"; import { UsageLimitAccountScreen } from "./features/usage/UsageLimitsPooled"; import { UsageRouteScreen } from "./features/usage/UsageRouteScreen"; +import { WorkflowRunRouteScreen } from "./features/workflows/WorkflowRunRouteScreen"; +import { WorkflowStepSheet } from "./features/workflows/WorkflowStepSheet"; import { SettingsAboutRouteScreen } from "./features/settings/SettingsAboutRouteScreen"; import { SettingsNotificationsRouteScreen } from "./features/settings/SettingsNotificationsRouteScreen"; import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen"; @@ -210,6 +212,7 @@ const ROUTE_TITLES: Readonly> = { NewTaskRepositories: msg("Repositories"), AddProject: msg("Add project"), ThreadFiles: msg("Files"), + WorkflowRun: msg("Run", { $context: "noun, page title for one workflow run" }), SettingsLegal: msg("Legal"), ConnectOnboarding: msg("Set up {product}", { product: "T3 Connect" }), Connections: msg("Environments"), @@ -784,6 +787,15 @@ const RootStackConfig = createWorkspaceStackNavigator({ screen: ThreadQueueSheet, options: sheetRoute({ detent: 0.65, androidMaxDetent: 0.95 }), }), + WorkflowRun: createNativeStackScreen({ + screen: WorkflowRunRouteScreen, + linking: { path: "workflows/:environmentId/:runId" }, + options: pageRoute(), + }), + WorkflowStep: createNativeStackScreen({ + screen: WorkflowStepSheet, + options: sheetRoute({ detent: 0.6, androidMaxDetent: 0.95 }), + }), ThreadBackgroundWork: createNativeStackScreen({ screen: ThreadBackgroundWorkSheet, options: sheetRoute({ detent: 0.5, androidMaxDetent: 0.9 }), diff --git a/apps/mobile/src/components/ComposerAttachmentStrip.tsx b/apps/mobile/src/components/ComposerAttachmentStrip.tsx index ba7d9790c4120..95a2d928e4c10 100644 --- a/apps/mobile/src/components/ComposerAttachmentStrip.tsx +++ b/apps/mobile/src/components/ComposerAttachmentStrip.tsx @@ -10,6 +10,7 @@ import { Paths } from "expo-file-system"; import { Image, Pressable, ScrollView, View } from "react-native"; import { AppText as Text } from "./ui/AppText"; +import { AppActivityIndicator } from "./ui/AppActivityIndicator"; import { MaterializedPreviewKey, materializedPreviewAtom } from "../lib/composerImagePreview"; import { PierreEntryIcon } from "./PierreEntryIcon"; import { @@ -44,6 +45,8 @@ export interface ComposerAttachmentStripProps { readonly imageSize?: number; readonly imageBorderRadius?: number; readonly removeButtonPlacement?: "overlay" | "gutter"; + /** Pasted images still being prepared, shown as placeholders after the attachments. */ + readonly pendingImageCount?: number; } type ComposerAttachmentThumbnailProps = { @@ -301,7 +304,8 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { const removeButtonPlacement = props.removeButtonPlacement ?? "overlay"; const removeButtonGutter = removeButtonPlacement === "gutter" ? 10 : 0; - if (props.attachments.length === 0) { + const pendingImageCount = props.pendingImageCount ?? 0; + if (props.attachments.length === 0 && pendingImageCount === 0) { return null; } @@ -353,6 +357,21 @@ export function ComposerAttachmentStrip(props: ComposerAttachmentStripProps) { ))} + {Array.from({ length: pendingImageCount }, (_, index) => ( + + + + ))} diff --git a/apps/mobile/src/components/ComposerToolbar.tsx b/apps/mobile/src/components/ComposerToolbar.tsx index 36ed505d27cd0..a901d6fa60b50 100644 --- a/apps/mobile/src/components/ComposerToolbar.tsx +++ b/apps/mobile/src/components/ComposerToolbar.tsx @@ -376,6 +376,7 @@ export function ComposerToolbarButton(props: { {providerInstanceInitials(props.displayName)} diff --git a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx index 017dbdb1456fb..d9f732853dddd 100644 --- a/apps/mobile/src/components/ui/FilePreviewModal.android.tsx +++ b/apps/mobile/src/components/ui/FilePreviewModal.android.tsx @@ -2,7 +2,7 @@ import { T, useGT } from "gt-react-native"; import { Button } from "./Button"; import * as Dialog from "./Dialog"; -import { createContext, useContext, useEffect, useEffectEvent } from "react"; +import { createContext, useContext, useEffect, useEffectEvent, useRef } from "react"; import { Modal, View } from "react-native"; import ImageViewing from "react-native-image-viewing"; import { useSafeAreaInsets } from "react-native-safe-area-context"; @@ -133,14 +133,23 @@ type ImagePreviewProps = { readonly onRequestClose: () => void; }; -const ImagePreviewContext = createContext(null); +const ImagePreviewContext = createContext< + (ImagePreviewProps & { readonly getSaveImageSignal: () => AbortSignal }) | null +>(null); +// Keyed by page so swiping away clears the busy state and aborts pending share preparation. function ImagePreviewHeader(header: { readonly imageIndex: number }) { + return ; +} + +function ImagePreviewPageHeader(header: { readonly imageIndex: number }) { const props = useContext(ImagePreviewContext)!; const source = props.source.images[header.imageIndex]; const gt = useGT(); const insets = useSafeAreaInsets(); - const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose); + const mediaActions = useMediaActions(source?.actionsSource, props.onRequestClose, { + getSaveImageSignal: props.getSaveImageSignal, + }); return ( (null); + const getSaveImageSignal = () => { + if (saveController.current === null) { + saveController.current = new AbortController(); + } + return saveController.current.signal; + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- saves survive a page change but stop when the gallery unmounts + useEffect( + () => () => { + saveController.current?.abort(); + saveController.current = null; + }, + [], + ); return ( - + ({ refreshAssetUrl: vi.fn<(environmentId: string, resource: { url: string }) => Promise>(), alert: vi.fn(), + share: vi.fn(), + download: vi.fn(), previews: [] as unknown[], mounts: 0, presentationFinished: false, })); -vi.mock("../../state/assets", () => ({ refreshAssetUrl: harness.refreshAssetUrl })); +vi.mock("../../state/assets", () => ({ + refreshAssetUrl: harness.refreshAssetUrl, + useRefreshAssetUrl: (environmentId: string, resource: { url: string }) => () => + harness.refreshAssetUrl(environmentId, resource), +})); vi.mock("../../lib/localAttachmentPreview", () => ({ loadLocalAttachmentPreview: vi.fn() })); vi.mock("../../lib/attachmentDownload", () => ({ - downloadAndShareAttachment: vi.fn(), + downloadAndShareAttachment: harness.share, + downloadAttachmentForPreview: harness.download, nativeViewerErrorMessage: () => "", shareLocalAttachment: vi.fn(), })); @@ -30,14 +46,46 @@ vi.mock("./Button", () => ({ Button: () => null })); vi.mock("./SheetHeader", () => ({ SheetHeader: () => null })); vi.mock("./AppText", () => ({ AppText: () => null })); vi.mock("../PdfPreview", () => ({ PdfPreview: () => null })); -vi.mock("../MediaPreviewHeader", () => ({ MediaPreviewHeader: () => null })); -vi.mock("../../state/mediaActions", () => ({ useMediaActions: () => ({ actions: [] }) })); -vi.mock("react-native", () => ({ Modal: () => null, View: () => null })); +vi.mock("../MediaPreviewHeader", () => ({ + MediaPreviewHeader: ({ media }: { media: ReturnType }) => + media.actions + .filter(({ id }) => id === "save" || id === "save-image") + .map(({ id, disabled, run, title }) => ( + + )), +})); +vi.mock("@react-navigation/native", () => ({ useNavigation: () => ({ navigate: vi.fn() }) })); +vi.mock("../../state/session", () => ({ + environmentSession: { sessionStateAtom: (environmentId: string) => environmentId }, +})); +const grant = { authenticated: true, scopes: [AuthFilesystemReadScope] }; +vi.mock("../../state/query", () => ({ + useEnvironmentQuery: () => ({ data: grant, error: null }), +})); +vi.mock("../../state/atom-registry", () => ({ + appAtomRegistry: { get: () => AsyncResult.success(grant) }, +})); +vi.mock("expo", () => ({ requireNativeModule: vi.fn() })); +vi.mock("expo-clipboard", () => ({ setStringAsync: vi.fn() })); +vi.mock("expo-haptics", () => ({ notificationAsync: vi.fn() })); +vi.mock("react-native", () => ({ + Modal: () => null, + Platform: { OS: "android", Version: 35 }, + View: ({ children }: { children: ReactNode }) => children, +})); vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ top: 0 }) })); vi.mock("react-native-image-viewing", () => ({ default: function ImageViewing(props: { images: readonly { uri?: string }[]; imageIndex: number; + HeaderComponent?: ComponentType<{ imageIndex: number }>; }) { useState(() => harness.mounts++); harness.previews.push({ @@ -45,7 +93,17 @@ vi.mock("react-native-image-viewing", () => ({ images: props.images, selectedIndex: props.imageIndex, }); - return null; + const [index, setIndex] = useState(props.imageIndex); + const Header = props.HeaderComponent; + if (!Header) return null; + return ( + <> +
+ {props.images.map(({ uri }, imageIndex) => ( + + ), +})); +vi.mock("../../components/ui/ScreenContent", () => ({ + ScreenContent: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../native/SelectableMarkdownText", () => ({ SelectableMarkdownText: () => null })); +vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) })); +vi.mock("../../state/linkedThread", () => ({ + useConnectLinkedEnvironment: () => ({ state: { phase: "idle" } }), + useLinkedThreadView: vi.fn(), +})); +vi.mock("../../state/peerLinks", () => ({ peerLinkEnvironment: {} })); +vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({}) })); +vi.mock("../files/FileMarkdownPreview", () => ({ useMarkdownPreviewStyles: () => ({}) })); +vi.mock("./ReadOnlyComposerBar", () => ({ + ReadOnlyComposerBar: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("./thread-inspector-header", () => ({ ThreadInspectorHeader: () => null })); +vi.mock("./useOpenLinkedThread", () => ({ useOpenLinkedThread: () => undefined })); + +it.effect( + "shows a page error after Load earlier fails on an already disconnected linked chat", + () => + Effect.gen(function* () { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + const target = { + viaEnvironmentId: EnvironmentId.make("via"), + environmentId: EnvironmentId.make("linked"), + threadId: v2Projection.thread.id, + label: "Linked test environment", + title: null, + }; + const warning = "Linked test environment is not answering this environment"; + const pageError = "Could not load earlier turns. Try again."; + const loadEarlier = () => + [...container.querySelectorAll("button")].find( + (button) => button.textContent === "Load earlier", + )!; + + try { + const unavailable = { _tag: "PeerLinkThreadReadError", reason: "unreachable" }; + const pages = + yield* Queue.unbounded< + Effect.Effect + >(); + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.make({ + kind: "snapshot", + snapshotSequence: 1, + projection: v2Projection, + historyCursor: "before-recent", + hasMoreHistory: true, + } as const).pipe(Stream.concat(Stream.fail(unavailable))), + historyPage: () => Queue.take(pages).pipe(Effect.flatten), + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + + const renderNext = Effect.gen(function* () { + const view = yield* Queue.take(views); + vi.mocked(useLinkedThreadView).mockReturnValue({ + view, + error: view.error ?? null, + retry() {}, + }); + act(() => root.render()); + }); + + yield* renderNext; // Initial snapshot. + yield* renderNext; // Connection warning. + expect(container.textContent).toContain(warning); + expect(container.textContent).not.toContain(pageError); + + act(() => loadEarlier().click()); + yield* renderNext; + yield* Queue.offer(pages, Effect.fail(unavailable)); + yield* renderNext; + expect(loadEarlier().parentElement?.textContent).toContain(pageError); + expect(container.textContent).toContain(warning); + + act(() => loadEarlier().click()); + yield* renderNext; + expect(container.textContent).not.toContain(pageError); + expect(loadEarlier().disabled).toBe(true); + } finally { + act(() => root.unmount()); + vi.unstubAllGlobals(); + } + }).pipe(Effect.scoped), +); diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index 0096c9d576a91..7ec2c4dac2cc8 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -286,6 +286,9 @@ export function LinkedThreadView(props: { const scroll = useRef>(null); // Follows new items only while the reader is already at the end. const atEnd = useRef(true); + const showHistoryError = + view !== null && view.thread.historyCursor !== null && view.history.failed; + const lastLayoutHadHistoryError = useRef(false); const working = projection !== null && isLinkedThreadWorking(projection); const connection = useConnectLinkedEnvironment(target); const connectState = connection.state; @@ -334,7 +337,12 @@ export function LinkedThreadView(props: { atEnd.current = contentSize.height - layoutMeasurement.height - contentOffset.y < 80; }} onContentSizeChange={() => { - if (atEnd.current) scroll.current?.scrollToEnd({ animated: false }); + // A page error can resize the top of a short feed whose reader is also near the end. + const historyErrorChanged = lastLayoutHadHistoryError.current !== showHistoryError; + lastLayoutHadHistoryError.current = showHistoryError; + if (atEnd.current && !historyErrorChanged) { + scroll.current?.scrollToEnd({ animated: false }); + } }} > {view === null || projection === null ? ( @@ -351,7 +359,7 @@ export function LinkedThreadView(props: { ) : ( <> {view.thread.historyCursor !== null ? ( - + + } + />, + ); + const editor = editorIn(screen.container); + await userEvent.click(editor.view.dom, { position: { x: 12, y: 12 } }); + await vi.waitFor(() => expect(editor.view.hasFocus()).toBe(true)); + await userEvent.click(screen.getByRole("button", { name: "Tab" })); + expect(onClick).toHaveBeenCalledOnce(); +}); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 3184ecbb574cb..10e5f68be5b06 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -206,6 +206,8 @@ export interface ComposerPromptEditorProps { contextIds: string[], /** False when only the caret or selection moved. */ textChanged: boolean, + /** True when the change came from undo or redo. */ + fromHistory?: boolean, ) => void; onVisibleSelectionChange?: () => void; onCommandKeyDown?: (key: string, event: KeyboardEvent, isTaskItem?: boolean) => boolean; @@ -1140,6 +1142,7 @@ function ComposerPromptEditorTiptapInner( suppressTrigger, contextIds, previousSnapshot.value !== nextValue, + isHistoryTransaction(transaction), ); }; @@ -1988,7 +1991,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
diff --git a/apps/web/src/components/CustomSnoozeDialog.tsx b/apps/web/src/components/CustomSnoozeDialog.tsx index 727a55f96fd23..f9c5c9423cbbf 100644 --- a/apps/web/src/components/CustomSnoozeDialog.tsx +++ b/apps/web/src/components/CustomSnoozeDialog.tsx @@ -13,6 +13,7 @@ import { CalendarIcon, Settings2Icon } from "lucide-react"; import { Calendar } from "./ui/calendar"; import { weekStartsOn } from "../timestampFormat"; import { useNowMinute } from "../hooks/useNowMinute"; +import { useFormattingLocale } from "../i18n/I18nProvider"; import { Popover, PopoverTrigger, PopoverPopup } from "./ui/popover"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; @@ -65,6 +66,7 @@ export function CustomSnoozeDialogHost() { function CustomSnoozeDialog() { const gt = useGT(); + const locale = useFormattingLocale(); const id = useId(); const navigate = useNavigate(); const [initial] = useState(() => new Date(Date.now() + 3_600_000)); @@ -148,7 +150,7 @@ function CustomSnoozeDialog() { /> } > - {date.toLocaleDateString(undefined, { + {date.toLocaleDateString(locale, { month: "short", day: "numeric", year: "numeric", diff --git a/apps/web/src/components/ProjectCloneToastCoordinator.tsx b/apps/web/src/components/ProjectCloneToastCoordinator.tsx index 846644c537a12..778c195e2d29e 100644 --- a/apps/web/src/components/ProjectCloneToastCoordinator.tsx +++ b/apps/web/src/components/ProjectCloneToastCoordinator.tsx @@ -45,6 +45,8 @@ interface TrackedToast { readonly toastId: ReturnType; readonly renderedKey: string; readonly phase: ProjectCloneSnapshot["phase"]; + readonly startedAt: ProjectCloneSnapshot["startedAt"]; + readonly closed?: true; } function renderKey(clone: ProjectCloneSnapshot): string { @@ -98,6 +100,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI seen.add(clone.projectId); const key = renderKey(clone); const tracked = toasts.current.get(clone.projectId); + const sameAttempt = tracked?.startedAt === clone.startedAt; const name = projectCloneDisplayName(clone); const closeToast = () => { const current = toasts.current.get(clone.projectId); @@ -111,7 +114,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } - if (tracked?.renderedKey === key) continue; + if (sameAttempt && tracked.renderedKey === key) continue; if ( isProjectCloneToastSilenced(ref) && (clone.phase === "running" || clone.phase === "done") @@ -119,6 +122,34 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } + if ( + sameAttempt && + tracked.closed && + (tracked.phase !== "running" || clone.phase !== "failed") + ) { + continue; + } + + const showToast = (options: ReturnType) => { + const rendered = { renderedKey: key, phase: clone.phase, startedAt: clone.startedAt }; + if (tracked && !tracked.closed) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { toastId: tracked.toastId, ...rendered }); + return; + } + + const toastId = toastManager.add({ + ...options, + // Updates to a closing toast are ignored, even before it has been removed. + onClose: () => { + const current = toasts.current.get(clone.projectId); + if (current?.toastId === toastId) { + toasts.current.set(clone.projectId, { ...current, closed: true }); + } + }, + }); + toasts.current.set(clone.projectId, { toastId, ...rendered }); + }; if (clone.phase === "running") { const options = stackedThreadToast({ @@ -136,13 +167,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" }); - } + showToast(options); continue; } @@ -161,13 +186,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" }); - } + showToast(options); continue; } @@ -199,13 +218,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase }); - } + showToast(options); } for (const [projectId, tracked] of toasts.current) { diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index af006833c8134..a17427fcdb54e 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -7,6 +7,8 @@ import { describe, expect, it } from "vite-plus/test"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { + ADD_PROJECT_SCOPE_ITEM_VALUE, + filterSidebarProjectScopeItems, shouldCreateNewThreadInCurrentProject, resolveScopedNewThreadProjectRef, deleteSelectedThreadEntries, @@ -1811,3 +1813,22 @@ describe("resolveScopedNewThreadProjectRef", () => { ).toBeNull(); }); }); + +describe("filterSidebarProjectScopeItems", () => { + it("hides Add project and All projects while searching", () => { + const items = [ + { value: ADD_PROJECT_SCOPE_ITEM_VALUE, label: "Add project" }, + { value: "all", label: "All projects" }, + { value: "p1", label: "project" }, + ]; + const filter = (query: string) => + filterSidebarProjectScopeItems({ + items, + query, + matches: (item, q) => item.label.includes(q), + }).map((item) => item.value); + + expect(filter("")).toEqual([ADD_PROJECT_SCOPE_ITEM_VALUE, "all", "p1"]); + expect(filter("project")).toEqual(["p1"]); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 49109eb4ac2b0..0771ea2e33d5d 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1183,6 +1183,8 @@ export function pullRequestMatchesSearchQuery( return normalizedQuery.split(" ").every((token) => haystack.includes(token)); } +export const ADD_PROJECT_SCOPE_ITEM_VALUE = "add-project"; + export function filterSidebarProjectScopeItems(input: { items: readonly TItem[]; query: string; @@ -1190,7 +1192,12 @@ export function filterSidebarProjectScopeItems item.value !== "all" && input.matches(item, query)); + return input.items.filter( + (item) => + item.value !== "all" && + item.value !== ADD_PROJECT_SCOPE_ITEM_VALUE && + input.matches(item, query), + ); } interface SidebarProjectScopeMenuState { diff --git a/apps/web/src/components/Sidebar.motion.browser.test.ts b/apps/web/src/components/Sidebar.motion.browser.test.ts new file mode 100644 index 0000000000000..2eae3d4f83fb9 --- /dev/null +++ b/apps/web/src/components/Sidebar.motion.browser.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vite-plus/test"; +import { render } from "../../test/render"; +import { createSidebarListMotion } from "./Sidebar.motion"; + +describe("sidebar list motion", () => { + it("slides rows above a removal at the bottom instead of jumping with the scroll clamp", async () => { + await using screen = await render(null); + const viewport = document.createElement("div"); + viewport.dataset.slot = "scroll-area-viewport"; + viewport.style.cssText = "height: 200px; overflow-y: auto; overflow-anchor: none"; + const list = document.createElement("ul"); + list.style.cssText = "position: relative; margin: 0; padding: 0; list-style: none"; + const rows = Array.from({ length: 10 }, () => { + const row = document.createElement("li"); + row.style.height = "64px"; + list.append(row); + return row; + }); + viewport.append(list); + screen.container.append(viewport); + const motion = createSidebarListMotion(list); + using _motion = { [Symbol.dispose]: () => motion.dispose() }; + motion.update(false); + viewport.scrollTop = viewport.scrollHeight; + viewport.dispatchEvent(new Event("scroll")); + const above = rows[7]!; + const before = above.getBoundingClientRect().top; + + rows[8]!.remove(); + motion.update(true); + for (const animation of above.getAnimations()) animation.pause(); + + expect(above.getBoundingClientRect().top).toBe(before); + }); +}); diff --git a/apps/web/src/components/Sidebar.motion.ts b/apps/web/src/components/Sidebar.motion.ts index 0e86c3c9a0e94..da0e7de3201b2 100644 --- a/apps/web/src/components/Sidebar.motion.ts +++ b/apps/web/src/components/Sidebar.motion.ts @@ -22,6 +22,12 @@ export function createSidebarListMotion(parent: HTMLUListElement) { const entering = new Map(); const exiting = new Map(); let released: Map | null = null; + const scroller = parent.closest('[data-slot="scroll-area-viewport"]'); + let scrollTop = scroller?.scrollTop ?? 0; + const trackScroll = () => { + scrollTop = scroller?.scrollTop ?? 0; + }; + scroller?.addEventListener("scroll", trackScroll, { passive: true }); const remainingOffset = (node: HTMLElement) => { const current = running.get(node); @@ -37,7 +43,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { entering.clear(); exiting.clear(); }; - const fadeOut = (node: HTMLElement, position: RowPosition, travel: number) => { + const fadeOut = (node: HTMLElement, position: RowPosition, travel: number, shift: number) => { if (position.height === 0) return; const clone = node.cloneNode(true) as HTMLElement; for (const element of [clone, ...clone.querySelectorAll("*")]) { @@ -56,7 +62,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { clone.inert = true; Object.assign(clone.style, { position: "absolute", - top: `${position.top + remainingOffset(node)}px`, + top: `${position.top + remainingOffset(node) + shift}px`, left: `${position.left}px`, width: `${position.width}px`, height: `${position.height}px`, @@ -153,6 +159,14 @@ export function createSidebarListMotion(parent: HTMLUListElement) { positions !== null && !reducedMotion?.matches && fadeCount <= MAX_FADED_ROWS_PER_UPDATE; + // A removal near the bottom shrinks the list and the browser clamps scrollTop, moving + // every row on screen; offsets include that shift so those rows slide instead of jump. + let shift = 0; + if (scroller !== null) { + const max = scroller.scrollHeight - scroller.clientHeight; + if (scrollTop > max && scroller.scrollTop >= max - 1) + shift = scroller.scrollTop - scrollTop; + } const movedDelta = new Map(); const nextOrder = [...next.keys()]; const oldOrder = positions === null ? [] : [...positions.keys()]; @@ -173,13 +187,13 @@ export function createSidebarListMotion(parent: HTMLUListElement) { else { for (const [node, position] of next) { const previousTop = positions!.get(node)?.top; - if (previousTop === undefined || previousTop === position.top) continue; - movedDelta.set(node, previousTop + remainingOffset(node) - position.top); + if (previousTop === undefined || previousTop + shift === position.top) continue; + movedDelta.set(node, previousTop + remainingOffset(node) - position.top + shift); } for (const [node, position] of positions!) { if (next.has(node)) continue; const delta = ridingDelta(oldOrder, oldOrder.indexOf(node), (n) => next.has(n)); - fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta); + fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta, shift); } } for (const [node, entry] of entering) { @@ -233,6 +247,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { released = null; } positions = next; + if (scroller !== null) scrollTop = scroller.scrollTop; }, release() { suspend(); @@ -246,6 +261,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { suspend, dispose() { suspend(); + scroller?.removeEventListener("scroll", trackScroll); disposed = true; }, }; diff --git a/apps/web/src/components/Sidebar.snooze.ts b/apps/web/src/components/Sidebar.snooze.ts index 34cdc0077cd3d..abe2e3934659d 100644 --- a/apps/web/src/components/Sidebar.snooze.ts +++ b/apps/web/src/components/Sidebar.snooze.ts @@ -9,6 +9,7 @@ import { } from "@t3tools/client-runtime/state/thread-settled"; import { m, type MessageResolver } from "../i18n/messages"; +import { getFormattingLocale } from "../i18n/runtime"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { serverEnvironment } from "../state/server"; import { formatShortTimestamp } from "../timestampFormat"; @@ -52,11 +53,13 @@ export function pickSnoozePreset( } function snoozeOptions(timestampFormat: TimestampFormat, environmentId: EnvironmentId) { + const locale = getFormattingLocale(); const presets = appAtomRegistry.get( serverEnvironment.settingsValueAtom(environmentId), )?.snoozePresets; return { ...(presets ? { presets } : {}), - formatTime: (date: Date) => formatShortTimestamp(date.toISOString(), timestampFormat), + formatTime: (date: Date) => formatShortTimestamp(date.toISOString(), timestampFormat, locale), + locale, }; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 681c6189fa57e..2f28e35ceb0ef 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -72,7 +72,7 @@ import { CheckIcon, ChevronDownIcon, FolderIcon, - ListFilterIcon, + FolderPlusIcon, PlusIcon, SettingsIcon, } from "lucide-react"; @@ -171,7 +171,6 @@ import { resolveThreadRouteTarget, } from "../threadRoutes"; import type { SidebarThreadSummary } from "../types"; -import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { cn } from "~/lib/utils"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; import { ProjectRowActions } from "./ProjectComboboxRow"; @@ -188,6 +187,7 @@ import { buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, deleteSelectedThreadEntries, + ADD_PROJECT_SCOPE_ITEM_VALUE, filterSidebarProjectScopeItems, firstValidTimestampMs, isSidebarNestedLinkClick, @@ -276,7 +276,12 @@ import { type SidebarProviderEntry, type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; -import { SidebarDraftBlock, useSidebarDrafts } from "./sidebar/SidebarDraftBlock"; +import { + draftTerminalLabel, + SidebarDraftBlock, + useDraftTerminalLabels, + useSidebarDrafts, +} from "./sidebar/SidebarDraftBlock"; import { SidebarProjectFolderHeader, sidebarFolderRowId, @@ -435,6 +440,7 @@ function useSidebarThreads(input: { readonly threads: readonly EnvironmentThreadShell[]; readonly delegatedUnderParent: ReadonlySet; readonly routeRowThreadKey: string | null; + readonly departingThreadKey: string | null; // Set in boring mode: the project groups to fold active threads into, in order. readonly folderGroups: readonly SidebarProjectSnapshot[] | null; // Keeps folders with no active threads, so a project the user filtered to or pinned can start one. @@ -449,9 +455,11 @@ function useSidebarThreads(input: { threads, delegatedUnderParent, routeRowThreadKey, + departingThreadKey, folderGroups, keepEmptyFolders: keepEmpty, } = input; + const shelfRouteThreadKey = routeRowThreadKey === departingThreadKey ? null : routeRowThreadKey; // Folders already separate the work, so boring mode has no Working shelf. const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled) && folderGroups === null; @@ -517,11 +525,11 @@ function useSidebarThreads(input: { const visibleSettledThreads = (() => { const visible = listedSettledThreads.slice(0, settledVisibleCount); if ( - routeRowThreadKey !== null && - !visible.some((thread) => threadShellKey(thread) === routeRowThreadKey) + shelfRouteThreadKey !== null && + !visible.some((thread) => threadShellKey(thread) === shelfRouteThreadKey) ) { const routeThread = settledThreads.find( - (thread) => threadShellKey(thread) === routeRowThreadKey, + (thread) => threadShellKey(thread) === shelfRouteThreadKey, ); if (routeThread !== undefined) visible.push(routeThread); } @@ -529,10 +537,10 @@ function useSidebarThreads(input: { })(); const renderedSettledThreads = settledShelfExpanded ? visibleSettledThreads - : routeThreadOnly(visibleSettledThreads, routeRowThreadKey); + : routeThreadOnly(visibleSettledThreads, shelfRouteThreadKey); const visibleSnoozedThreads = snoozedShelfExpanded ? snoozedThreads - : routeThreadOnly(snoozedThreads, routeRowThreadKey); + : routeThreadOnly(snoozedThreads, shelfRouteThreadKey); const visibleWorkingThreads = workingShelfExpanded ? workingThreads : routeThreadOnly(workingThreads, routeRowThreadKey); @@ -840,6 +848,7 @@ function useSidebarLookups() { projectGroups.map((project) => [project.projectKey, project] as const), ); const projectScopeItems = [ + { value: ADD_PROJECT_SCOPE_ITEM_VALUE, label: gt("Add project") }, { value: "all", label: gt("All projects") }, ...pickableProjectGroups(projectGroups).map((project) => ({ value: project.projectKey, @@ -1165,20 +1174,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve setPersistedProjectScopeKeys([]); }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]); const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace); + const [departingThreadKey, setDepartingThreadKey] = useState(null); + if (departingThreadKey !== null && departingThreadKey !== routeThreadKey) { + setDepartingThreadKey(null); + } + const departRouteThread = (threadKey: string) => setDepartingThreadKey(threadKey); + const stayOnRouteThread = (threadKey: string) => + setDepartingThreadKey((current) => (current === threadKey ? null : current)); const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups); - const scratchMachineLabelFor = ( - thread: Pick, - ) => { - if (!showProjectEnvironments) return null; - const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`); - if ( - !project || - !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot) - ) { - return null; - } - return environmentLabelById.get(thread.environmentId) ?? null; - }; // Pinning from a row keeps rows in place while the menu is open. const projectScopeItems = useOrderWhileOpen( lookupProjectScopeItems, @@ -1189,7 +1192,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve projectScopeKeys.length > 1 ? null : (projectScopeItems.find((item) => item.value === (projectScopeKeys[0] ?? "all")) ?? - projectScopeItems[0]!); + projectScopeItems.find((item) => item.value === "all")!); const filteredProjectScopeItems = filterSidebarProjectScopeItems({ items: projectScopeItems, query: projectScopeMenuState.query, @@ -1207,13 +1210,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : { projectIds: scopedProjectRefs.map((projectRef) => projectRef.projectId) }, ); const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null; + const draftTerminalLabels = useDraftTerminalLabels(); const visibleDraftSessionCount = useComposerDraftStore((store) => { let count = 0; for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) { if (session.promotedTo != null) { continue; } - if (!composerDraftHasUserContent(store.draftsByThreadKey[draftKey])) { + if ( + draftTerminalLabel(session, draftTerminalLabels) === null && + !composerDraftHasUserContent(store.draftsByThreadKey[draftKey]) + ) { continue; } if ( @@ -1358,6 +1365,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve threads: listedThreads, delegatedUnderParent, routeRowThreadKey, + departingThreadKey, folderGroups: boringSidebarEnabled ? scopedProjectGroups.length === 0 ? // An archived project keeps a folder for its active threads, below the rest. @@ -1447,7 +1455,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const settledThreadKeysRef = useRef(settledThreadKeys); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); - const { draftIds, routeDraftComposer } = useSidebarDrafts(scopedProjectKeys, routeDraftIdForRows); + const { draftIds, routeDraftComposer } = useSidebarDrafts( + scopedProjectKeys, + routeDraftIdForRows, + draftTerminalLabels, + ); // Draft rows sit above the threads, so jumps and traversal reach them first. // Search hides them, so they drop out while it is open. const listedDraftIds = isSearchingThreads ? EMPTY_DRAFT_IDS : draftIds; @@ -1644,9 +1656,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (settlingThreadKeysRef.current.has(threadKey)) return; settlingThreadKeysRef.current.add(threadKey); const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys); + if (navigateAfterSettle) departRouteThread(threadKey); const result = await settleThread(threadRef); settlingThreadKeysRef.current.delete(threadKey); if (result._tag === "Failure") { + stayOnRouteThread(threadKey); if (!isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); toastManager.add( @@ -1669,6 +1683,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSettle?.(); + } else { + stayOnRouteThread(threadKey); } })(); }; @@ -2202,6 +2218,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve case "settle": { settlingThreadKeysRef.current.add(activeKey); const navigateAfterSettle = planForwardNavigation(activeKey); + if (navigateAfterSettle) departRouteThread(activeKey); const settled = await run(settleThread(threadRef), gt("Failed to settle thread")).finally( () => settlingThreadKeysRef.current.delete(activeKey), ); @@ -2216,6 +2233,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) navigateAfterSettle?.(); + else stayOnRouteThread(activeKey); return; } case "move-active": @@ -2271,9 +2289,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } snoozingThreadKeysRef.current.add(threadKey); const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys); + if (navigateAfterSnooze) departRouteThread(threadKey); const result = await snoozeThread(threadRef, preset.snoozedUntil); snoozingThreadKeysRef.current.delete(threadKey); if (result._tag === "Failure") { + stayOnRouteThread(threadKey); return isAtomCommandInterrupted(result) ? ({ status: "interrupted" } as const) : ({ status: "failure", error: squashAtomCommandFailure(result) } as const); @@ -2288,6 +2308,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSnooze?.(); + } else { + stayOnRouteThread(threadKey); } return { status: "success" } as const; }; @@ -3068,7 +3090,10 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve return; } if (!item) return; - if (item.value === "all") { + if (item.value === ADD_PROJECT_SCOPE_ITEM_VALUE) { + dispatchProjectScopeMenu({ type: "open-changed", open: false }); + openAddProjectCommandPalette(); + } else if (item.value === "all") { setProjectScopeKeys([]); } else if ( eventDetails.event instanceof MouseEvent && @@ -3087,12 +3112,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve 0 - ? gt("Filter threads by project: {projects}", { + ? gt("Projects: {projects}", { projects: scopedProjectGroups .map((project) => project.displayName) .join(", "), }) - : gt("Filter threads by project") + : gt("Projects") } /> } @@ -3117,7 +3142,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) : ( - + )} {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} @@ -3179,6 +3204,16 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve {(item: (typeof projectScopeItems)[number]) => { + if (item.value === ADD_PROJECT_SCOPE_ITEM_VALUE) { + return ( + + + {item.label} + {/* Keeps "Add project" as tall as the project rows. */} + + + ); + } const project = projectGroupByScopeKey.get(item.value) ?? null; const isSelected = project ? projectScopeKeys.includes(item.value) @@ -3254,7 +3289,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } - onNewProject={openAddProjectCommandPalette} onNewThread={handleNewThreadClick} newThreadDisabled={projects.length === 0} newThreadShortcutLabel={newThreadShortcutLabel} @@ -3530,14 +3564,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve jumpLabel={ showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null } - currentEnvironmentId={primaryEnvironmentId} environmentLabel={ environmentLabelById.get(thread.environmentId) ?? null } environmentMachine={ environmentMachineById.get(thread.environmentId) ?? "server" } - scratchMachineLabel={scratchMachineLabelFor(thread)} project={ projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null @@ -3578,6 +3610,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve key="draft-sessions" draftIds={draftIds} routeDraftComposer={routeDraftComposer} + terminalLabels={draftTerminalLabels} jumpLabelByDraftId={draftJumpLabelById} projectByKey={projectByKey} projectDisplayNameByKey={projectDisplayNameByKey} diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 9c5e7fa3d830d..905d9cb2131fe 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -19,7 +19,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; import { msg, T, useGT, useMessages } from "gt-react"; -import { FolderGit2Icon, TerminalIcon } from "lucide-react"; +import { TerminalIcon } from "lucide-react"; import { m, type MessageResolver } from "../i18n/messages"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; @@ -53,7 +53,6 @@ import { } from "./Sidebar.logic"; import type { SidebarThreadSummary } from "../types"; -import { formatWorktreePathForDisplay } from "../worktreeCleanup"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { PULL_REQUEST_STATE_PRESENTATION, @@ -770,41 +769,6 @@ export function ThreadTerminalStatusButton({ ); } -export function ThreadWorktreeIndicator({ - thread, -}: { - thread: Pick; -}) { - const gt = useGT(); - const worktreePath = thread.worktreePath?.trim(); - if (!worktreePath) { - return null; - } - - const displayPath = formatWorktreePathForDisplay(worktreePath); - const tooltip = thread.branch - ? gt("Worktree: {path} ({branch})", { path: displayPath, branch: thread.branch }) - : gt("Worktree: {path}", { path: displayPath }); - - return ( - - - } - > - - - {tooltip} - - ); -} - function ThreadStatusLabel({ status, compact = false, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 5042bf45ed673..30f73a9a2c4c8 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -23,6 +23,7 @@ import { import type { KeybindingCommand, AssistantCitation, + ComposerContextId, ResponseContextRecord, ChatAttachment as ContractChatAttachment, ChatFileAttachment, @@ -120,6 +121,7 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { + type QueuedAttachmentContextBinding, reconcileAttachmentContextReferences, useRetainedContextPayloads, } from "./composerContextUndo"; @@ -133,6 +135,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -212,6 +216,7 @@ import { } from "./ComposerCommandMenu"; import { ComposerAttachButton, + ComposerAttachInput, ComposerAttachmentFileList, ComposerAttachmentMediaRow, ComposerFilePreviewDialog, @@ -251,6 +256,7 @@ import { useNavigate } from "@tanstack/react-router"; import { assistantCitationLabel } from "@t3tools/shared/assistantCitations"; import { assistantCitationNavigation } from "../../lib/assistantCitationNavigation"; import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; import { useManagedPolicy } from "../../state/managedPolicy"; import { hasProviderSetup } from "./ProviderStatusBanner"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; @@ -287,11 +293,15 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; import { + cancelHeldComposerSend, countPreparingComposerImages, + useComposerSendHeld, usePreparingComposerImages, useSubmitAfterPreparingImages, } from "./preparingComposerImages"; +import { HELD_COMPOSER_SEND_BANNER_ID } from "./ComposerHeldSendBanner"; import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; import { promptSuggestionToAccept, usePromptSuggestion } from "./usePromptSuggestion"; @@ -454,8 +464,11 @@ export interface ChatComposerProps { editingQueuedAttachments: ReadonlyArray<{ readonly attachment: ContractChatAttachment; readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; }> | null; + removedEditingQueuedAttachments?: ReadonlyArray | undefined; onRemoveEditingQueuedAttachment: (attachmentId: string) => void; + onRestoreEditingQueuedAttachment?: ((attachment: ContractChatAttachment) => void) | undefined; onCompactContext: () => void; onSend: ( @@ -596,7 +609,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onExpandImage, onFileOpen, editingQueuedAttachments, + removedEditingQueuedAttachments, onRemoveEditingQueuedAttachment, + onRestoreEditingQueuedAttachment, } = props; const { activePendingProgress: incomingPendingProgress, @@ -654,6 +669,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion.id, ) : null; + const queuedEditOwnsComposer = + questionAttachmentTarget === null && pendingUserInputs.length === 0; + const activeEditingQueuedAttachments = queuedEditOwnsComposer ? editingQueuedAttachments : null; + const activeRemovedEditingQueuedAttachments = queuedEditOwnsComposer + ? removedEditingQueuedAttachments + : undefined; const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget; const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget); const questionTakesSnapShots = @@ -735,8 +756,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) uncommittedSnapShotIds, standaloneComposerImages, } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); - const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( - (image) => !image.hidden, + const allPreparingComposerImages = usePreparingComposerImages(attachmentTargetKey); + const preparingComposerImages = allPreparingComposerImages.filter((image) => !image.hidden); + // A message send waits for these itself; an answer waits in the composer below. + const messageHasPreparingImages = + questionAttachmentTarget === null && allPreparingComposerImages.length > 0; + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSend = () => cancelHeldComposerSend(composerDraftTargetKey); + const handleMultipleModelSelectionsChangeStable = useStableCallback( + (next: React.SetStateAction | null>) => { + cancelHeldSend(); + setMultipleModelSelections(next); + }, ); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); @@ -749,33 +780,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, expandImage: (imageId: string) => { - const preview = buildExpandedImagePreview( - composerImages, - imageId, - copyComposerSnapshotStable, - ); + const preview = + buildExpandedImagePreview(composerImages, imageId, copyComposerSnapshotStable) ?? + buildExpandedImagePreview( + (activeEditingQueuedAttachments ?? []).flatMap(({ attachment, url }) => + isQueuedImageAttachment(attachment) && url ? [{ ...attachment, previewUrl: url }] : [], + ), + imageId, + ); if (preview) onExpandImage(preview); }, - openFile: setPreviewFileId, + openFile: (fileId: string) => { + if (composerFiles.some((file) => file.id === fileId)) { + setPreviewFileId(fileId); + return; + } + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (queuedFile && isQueuedFileAttachment(queuedFile)) onFileOpen(queuedFile); + }, openMention: (path: string) => chatOpener?.().openMention(path), expandVideo: (fileId: string) => { const file = composerFiles.find((candidate) => candidate.id === fileId); - if (!file || !isVideoAttachment(file)) return; - const localPreview = buildExpandedImagePreview([file], file.id); - if (localPreview) { - onExpandImage(localPreview); + if (file && isVideoAttachment(file)) { + const localPreview = buildExpandedImagePreview([file], file.id); + if (localPreview) { + onExpandImage(localPreview); + return; + } + if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + return; + } + const persistedPreview = buildAttachmentVideoPreview(environmentId, { + type: "file", + id: file.uploadedAttachmentId, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + }); + if (persistedPreview) onExpandImage(persistedPreview); return; } - if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (!queuedFile || !isQueuedFileAttachment(queuedFile) || !isVideoAttachment(queuedFile)) { return; } - const persistedPreview = buildAttachmentVideoPreview(environmentId, { - type: "file", - id: file.uploadedAttachmentId, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - }); + const persistedPreview = buildAttachmentVideoPreview(environmentId, queuedFile); if (persistedPreview) onExpandImage(persistedPreview); }, openPullRequest: (event: React.MouseEvent, url: string) => { @@ -790,6 +843,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentContexts: composerEnvironmentContexts, images: composerImages, files: composerFiles, + existingAttachments: activeEditingQueuedAttachments ?? undefined, + environmentId, uploadsByImageId, }); const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length; @@ -1073,6 +1128,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const composerEditorRef = useRef(null); const pasteAsTextShortcutUntilRef = useRef(0); const composerFormRef = useRef(null); + const composerAttachInputRef = useRef(null); const composerSurfaceRef = useRef(null); const providerInputRejectedRef = useRef(false); const composerSelectLockRef = useRef(false); @@ -1274,21 +1330,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComplete: Boolean(activePendingResolvedAnswers), } : null; + const hasMessageToSend = composerSendState.hasSendableContent || messageHasPreparingImages; const showResumeAction = - canResume && !composerDraftHasUserContent(composerDraft) && !isEditingQueuedMessage; + canResume && + !composerDraftHasUserContent(composerDraft) && + !messageHasPreparingImages && + !isEditingQueuedMessage; const collapsedComposerPrimaryActionDisabled = phase === "running" || isSendBusy || + composerSendHeld || isSendDisabled || noProviderAvailable || projectSelectionRequired || environmentUnavailable !== null || - (!composerSendState.hasSendableContent && !showResumeAction); - const collapsedComposerPrimaryActionLabel = showResumeAction - ? gt("Resume thread") - : props.resumeCompactionTokens !== null && !props.keepFullHistory - ? gt("Open composer to compact and send") - : gt("Send message"); + (!hasMessageToSend && !showResumeAction); + const collapsedComposerPrimaryActionLabel = composerSendHeld + ? gt("Sending when ready") + : showResumeAction + ? gt("Resume thread") + : props.resumeCompactionTokens !== null && !props.keepFullHistory + ? gt("Open composer to compact and send") + : gt("Send message"); const showMobilePendingAnswerActions = isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null; @@ -1378,12 +1441,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [ - record.kind === "image" && attachment.type === "image" && attachment.source - ? { ...record, source: attachment.source } - : record, - ]; + return [record]; }), + ...(activeEditingQueuedAttachments ?? []).flatMap(({ attachment, contextIds }) => { + if (!isQueuedImageAttachment(attachment) && !isQueuedFileAttachment(attachment)) return []; + return (contextIds ?? []) + .filter((contextId) => wanted.has(contextId)) + .map((contextId) => + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + ); + }), ]; if (records.length === 0) return null; const fragment = encodeComposerContextFragment({ @@ -1432,6 +1503,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments: activeRemovedEditingQueuedAttachments, + onRestoreQueuedAttachment: onRestoreEditingQueuedAttachment, }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers @@ -1637,6 +1710,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], textChanged: boolean, + fromHistory = false, ) => { refreshWorkspaceSnapshotOnTyping(); const trigger = cursorAdjacentToMention @@ -1747,6 +1821,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const attachmentChanges = reconcileAttachmentContextReferences({ referencedContextIds: referenced, files: composerFiles, + queuedAttachments: (activeEditingQueuedAttachments ?? []).map( + ({ attachment, contextIds }) => ({ + attachment, + contextIds: contextIds ?? [], + }), + ), + removedQueuedAttachments: activeRemovedEditingQueuedAttachments ?? [], + fromHistory, images: composerImages, previewAnnotations: composerPreviewAnnotations, retained: retainedContextPayloads, @@ -1766,6 +1848,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (attachmentChanges.filesToRestore.length > 0) { addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); } + for (const attachmentId of attachmentChanges.queuedAttachmentIdsToRemove) { + onRemoveEditingQueuedAttachment(attachmentId); + } + for (const attachment of attachmentChanges.queuedAttachmentsToRestore) { + onRestoreEditingQueuedAttachment?.(attachment); + } setComposerCursor(nextCursor); updateTrigger(trigger); }; @@ -2210,7 +2298,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (activePendingProgress) { return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); } - return composerSendState.hasSendableContent; + return hasMessageToSend; }; const submitComposerRef = useRef< @@ -2296,9 +2384,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) event?.preventDefault(); return false; } - // Sending now would leave a still-compressing image out of the turn, so wait for it. + if (composerSendHeld) { + event?.preventDefault(); + return false; + } + // Sending now would leave a still-compressing image out of the answer, so wait for it. if ( activeThreadId && + questionAttachmentTarget && submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) ) { event?.preventDefault(); @@ -2481,8 +2574,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? promptSuggestion : null; - const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => - composerCommandKeyHandler({ + const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => { + if (key === "Escape" && composerSendHeld && !event.isComposing) { + cancelHeldSend(); + return true; + } + return composerCommandKeyHandler({ keybindings, getShortcutContext, sendShortcut: settings.sendShortcut, @@ -2521,6 +2618,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptSuggestion: offeredPromptSuggestion, dismissPromptSuggestion, })(key, event, isTaskItem); + }; const { stashQueue, @@ -2629,7 +2727,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isSendBusy={isSendBusy} multipleModelsEnabled={routeKind === "draft" && supportsMultipleModels} multipleModelSelections={multipleModelSelections} - onMultipleModelSelectionsChange={setMultipleModelSelections} + onMultipleModelSelectionsChange={handleMultipleModelSelectionsChangeStable} selectedModelSelection={selectedModelSelection} onProviderModelSelect={onProviderModelSelect} activeThreadModelSelection={activeThreadModelSelection} @@ -2727,7 +2825,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const shelfItems = hasBlockingComposerTopDrawer ? bannerItems.filter( (item) => - item.group === "environment" && (item.variant === "error" || item.variant === "warning"), + item.id === HELD_COMPOSER_SEND_BANNER_ID || + (item.group === "environment" && + (item.variant === "error" || item.variant === "warning")), ) : bannerItems; @@ -2928,12 +3028,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const pastedContext = !isLiteralPendingAnswer && (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; + const canAttachFiles = !pastedContext && activeThreadId !== null && files.length > 0; + const htmlImageContent = + canAttachFiles && plainText.length > 0 + ? clipboardHtmlImageContent(event.clipboardData.getData("text/html")) + : "none"; if ( folders.length > 0 || - (!pastedContext && - activeThreadId && - files.length > 0 && - shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment })) + (canAttachFiles && + shouldHandleComposerAttachmentPaste({ + files, + plainText, + bypassAutoAttachment, + htmlIsOnlyImage: htmlImageContent === "only-image", + })) ) { event.preventDefault(); event.stopPropagation(); @@ -2945,6 +3053,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } if (pastedContext) return; + const imagesBesideText = imagesToAttachBesidePastedText({ + files, + plainText, + bypassAutoAttachment, + htmlHasImageAndText: htmlImageContent === "image-and-text", + }); + if (imagesBesideText.length > 0) void addComposerAttachments(imagesBesideText); if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } @@ -3516,15 +3631,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) /> ) : null; const composerAttachButton = showComposerAttachAction ? ( - + composerAttachInputRef.current?.click()} /> ) : null; return (
{ + if ( + event.key === "Escape" && + composerSendHeld && + !event.defaultPrevented && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + cancelHeldSend(); + } + }} onFocusCapture={(event) => { const activeElement = event.target; if ( @@ -3609,6 +3732,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onToggleMenu={toggleStashMenuStable} /> + {showComposerAttachAction ? ( + + ) : null}
@@ -3669,6 +3799,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-64" disabled={collapsedComposerPrimaryActionDisabled} aria-label={collapsedComposerPrimaryActionLabel} + aria-busy={composerSendHeld || isSendBusy || undefined} onPointerDown={(event) => event.preventDefault()} onClick={(event) => { event.stopPropagation(); @@ -3678,7 +3809,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) else submitComposer(); }} > - {showResumeAction ? ( + {composerSendHeld || isSendBusy ? ( +
+
{previewFile ? ( { it("copies an image whose path has a space as Markdown that is still that image", () => { // Raw HTML and sources reach the copy with the space unencoded. const copied = markdownImageCopy("Shot", "/work/my shot.png", undefined); - const [block] = unified().use(remarkParse).parse(copied).children; + const [block] = markdownTree(copied).children; const images = - block?.type === "paragraph" ? block.children.filter((node) => node.type === "image") : []; - expect(images.map((image) => decodeURI(image.url))).toEqual(["/work/my shot.png"]); + block?.type === "element" && block.tagName === "p" + ? block.children.filter((node) => node.type === "element" && node.tagName === "img") + : []; + expect( + images.map((image) => image.type === "element" && decodeURI(String(image.properties.src))), + ).toEqual(["/work/my shot.png"]); }); }); diff --git a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx index 82819be4f53fc..686b16da17ae1 100644 --- a/apps/web/src/components/chat/ComposerAttachmentStrip.tsx +++ b/apps/web/src/components/chat/ComposerAttachmentStrip.tsx @@ -8,7 +8,7 @@ import type { import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { T, useGT, useMessages } from "gt-react"; import { CircleAlertIcon, ImageIcon, PaperclipIcon, PlayIcon, XIcon } from "lucide-react"; -import { type ComponentProps, useLayoutEffect, useRef } from "react"; +import { type ComponentProps, type Ref, useLayoutEffect, useRef } from "react"; import { type ComposerFileAttachment, @@ -731,53 +731,59 @@ export function ComposerQueuedAttachmentRow({ ); } -export function ComposerAttachButton({ +// Kept outside the composer footer: on mobile the picker blurs the editor and the +// footer unmounts, and a detached input never delivers its change event. +export function ComposerAttachInput({ + ref, addComposerAttachments, focusComposer, }: { + readonly ref: Ref; readonly addComposerAttachments: (files: File[]) => Promise; readonly focusComposer: () => void; }) { + return ( + { + const files = Array.from(event.currentTarget.files ?? []); + event.currentTarget.value = ""; + // Inserting a chip refocuses the editor after the draft renders; + // focusing synchronously here would report the editor's stale text + // over the prompt that was just written. + void addComposerAttachments(files).then((inserted) => { + if (!inserted) focusComposer(); + }); + }} + /> + ); +} + +export function ComposerAttachButton({ onOpenPicker }: { readonly onOpenPicker: () => void }) { const gt = useGT(); - const inputRef = useRef(null); return ( - <> - { - const files = Array.from(event.currentTarget.files ?? []); - event.currentTarget.value = ""; - // Inserting a chip refocuses the editor after the draft renders; - // focusing synchronously here would report the editor's stale text - // over the prompt that was just written. - void addComposerAttachments(files).then((inserted) => { - if (!inserted) focusComposer(); - }); - }} - /> - - event.preventDefault()} - onClick={() => inputRef.current?.click()} - aria-label={gt("Attach files")} - /> - } - > - {/* The clip's weight sits in its upper loop; 1px down reads as centered on the row. */} - - - - Attach files - - - + + event.preventDefault()} + onClick={onOpenPicker} + aria-label={gt("Attach files")} + /> + } + > + {/* The clip's weight sits in its upper loop; 1px down reads as centered on the row. */} + + + + Attach files + + ); } diff --git a/apps/web/src/components/chat/ComposerFooterControls.tsx b/apps/web/src/components/chat/ComposerFooterControls.tsx index 1df9cdbd32335..e8cd9134e2a9a 100644 --- a/apps/web/src/components/chat/ComposerFooterControls.tsx +++ b/apps/web/src/components/chat/ComposerFooterControls.tsx @@ -211,6 +211,7 @@ export const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryA alternateShortcutLabel: string | null; voiceInputActive?: boolean; isSendBusy: boolean; + isSendHeld?: boolean; sendDisabledReason: string | null; isEnvironmentUnavailable: boolean; hasSendableContent: boolean; @@ -240,6 +241,7 @@ export const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryA alternateShortcutLabel={props.alternateShortcutLabel} voiceInputActive={props.voiceInputActive ?? false} isSendBusy={props.isSendBusy} + isSendHeld={props.isSendHeld ?? false} sendDisabledReason={props.sendDisabledReason} isEnvironmentUnavailable={props.isEnvironmentUnavailable} isPreparingWorktree={props.isPreparingWorktree} diff --git a/apps/web/src/components/chat/ComposerHeldSendBanner.tsx b/apps/web/src/components/chat/ComposerHeldSendBanner.tsx new file mode 100644 index 0000000000000..1fcd618bce4a6 --- /dev/null +++ b/apps/web/src/components/chat/ComposerHeldSendBanner.tsx @@ -0,0 +1,50 @@ +import { msg, useGT } from "gt-react"; + +import { composerTargetKey, type ComposerThreadTarget } from "../../composerDraftStore"; +import { m, type MessageResolver } from "../../i18n/messages"; +import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; +import type { ComposerBannerStackItem } from "./ComposerBannerStack"; +import { usePreparingComposerImages } from "./preparingComposerImages"; + +export const HELD_COMPOSER_SEND_BANNER_ID = "held-composer-send"; + +function HeldComposerSendStatus({ draftTarget }: { readonly draftTarget: ComposerThreadTarget }) { + const gt = useGT(); + const preparingCount = usePreparingComposerImages(composerTargetKey(draftTarget)).length; + const label = + preparingCount > 0 + ? gt( + "{count, plural, one {Sending once image is ready} other {Sending once {count} images are ready}}", + { count: preparingCount }, + ) + : gt("Sending message"); + return {label}; +} + +/** Shown while a send waits for pasted or dropped images to finish compressing. */ +export function heldComposerSendBannerItem( + input: { + readonly draftTarget: ComposerThreadTarget; + readonly onCancel: () => void; + }, + resolve: MessageResolver = m, +): ComposerBannerStackItem { + return { + id: HELD_COMPOSER_SEND_BANNER_ID, + variant: "info", + icon:
+ + ); +} + +function FeedbackPreview({ preview }: { readonly preview: AgentFeedbackPreview }) { + const m = useMessages(); + + return ( +
+
+ {feedbackPreviewFields(preview, m).map((field) => ( +
+
{field.label}
+
{field.value}
+
+ ))} +
+ {preview.trace !== null ? ( + + + + {feedbackTraceSummary(preview.trace, m)} + + +
    + {feedbackTraceLines(preview.trace, m).map((entry) => ( +
  1. + {entry.line} + {entry.text !== undefined ? ( +

    + {entry.text} +

    + ) : null} +
  2. + ))} +
+
+
+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts index fcee475c2886a..0a45cd6ac5659 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts +++ b/apps/web/src/components/chat/MarkdownCodeBlock.logic.ts @@ -1,5 +1,5 @@ import { Children, isValidElement, type ReactNode } from "react"; -import type { ExtraProps as ReactMarkdownExtraProps } from "react-markdown"; +import type { Element } from "hast"; import type { DiffThemeName } from "../../lib/diffRendering"; @@ -44,11 +44,7 @@ export function extractPreCodeMeta(node: unknown): string | undefined { return typeof meta === "string" && meta.trim().length > 0 ? meta.trim() : undefined; } -export function isClosedCodeFence( - node: ReactMarkdownExtraProps["node"], - text: string, - code: string, -): boolean { +export function isClosedCodeFence(node: Element | undefined, text: string, code: string): boolean { const start = node?.position?.start.offset; const end = node?.position?.end.offset; if (start === undefined || end === undefined) return false; @@ -98,7 +94,7 @@ export function extractCodeBlock( return null; } // With a custom `code` component the child's type is that component, not - // the "code" tag — the hast node react-markdown attaches still names it. + // the "code" tag — the hast node the renderer passes still names it. if (onlyChild.type !== "code" && onlyChild.props.node?.tagName !== "code") { return null; } diff --git a/apps/web/src/components/chat/MarkdownCodeBlock.tsx b/apps/web/src/components/chat/MarkdownCodeBlock.tsx index d6c8a7aaba2eb..726c34cbf029e 100644 --- a/apps/web/src/components/chat/MarkdownCodeBlock.tsx +++ b/apps/web/src/components/chat/MarkdownCodeBlock.tsx @@ -1,4 +1,4 @@ -import { T, useGT } from "gt-react"; +import { useGT } from "gt-react"; import { PlayIcon, WrapTextIcon, CheckIcon, CopyIcon } from "lucide-react"; import { toHtml } from "hast-util-to-html"; import React, { use, useEffect, useState, type ReactNode } from "react"; @@ -18,7 +18,7 @@ import { syntheticFileNameForLanguageId, } from "../../pierre-icons"; import { Button } from "../ui/button"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { SharedTooltipTrigger } from "../ui/shared-tooltip"; import { HighlightedCodeLines } from "./HighlightedCodeLines"; import { createHighlightCacheKey, @@ -115,19 +115,17 @@ function MarkdownCodeBlockTitleContent({ return {language}; } return ( - - - } - > - - - {language} - + + } + > + + ); } @@ -187,22 +185,20 @@ export function MarkdownCodeBlock({ const handleCopy = () => copyToClipboard(code.endsWith("\n") ? code.slice(0, -1) : code); const copyButton = ( - - - } - > - {copied ? : } - - {copyLabel} - + + } + > + {copied ? : } + ); if (diagram) { @@ -231,43 +227,37 @@ export function MarkdownCodeBlock({ aria-label={gt("Code block actions")} > {canWrap ? ( - - setWrapOverride(!wrapped)} - aria-label={wrapLabel} - /> - } - > - - - {wrapLabel} - + setWrapOverride(!wrapped)} + aria-label={wrapLabel} + /> + } + > + + ) : null} {canRun ? ( - - onRunShellCommand(command)} - aria-label={gt("Run in terminal")} - /> - } - > - - - - Run in terminal - - + onRunShellCommand(command)} + aria-label={gt("Run in terminal")} + /> + } + > + + ) : null} {viewToggle} {copyButton} diff --git a/apps/web/src/components/chat/MarkdownDetails.tsx b/apps/web/src/components/chat/MarkdownDetails.tsx index 5ec510c3a4306..b6fa2b1d8d1f1 100644 --- a/apps/web/src/components/chat/MarkdownDetails.tsx +++ b/apps/web/src/components/chat/MarkdownDetails.tsx @@ -1,5 +1,6 @@ import { useGT } from "gt-react"; import { ChevronRightIcon } from "lucide-react"; +import { flushSync } from "react-dom"; import { Children, isValidElement, @@ -12,6 +13,11 @@ import { import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; import { findRevealRef, MarkdownFindContext } from "./markdownFindContext"; +const focusOnMount = (element: HTMLElement | null) => { + if (element && element.ownerDocument.activeElement === element.ownerDocument.body) + element.focus(); +}; + export function MarkdownDetails({ children, open = false, @@ -19,6 +25,7 @@ export function MarkdownDetails({ }: Pick, "children" | "open" | "dir">) { const gt = useGT(); const [isOpen, setIsOpen] = useState(open); + const [armed, setArmed] = useState<"hover" | "focus" | null>(null); const searching = use(MarkdownFindContext); const expanded = isOpen; const revealForFind = () => setIsOpen(true); @@ -36,6 +43,36 @@ export function MarkdownDetails({ : gt("Details", { $context: "fallback title of a collapsible section" }); const content = childNodes.filter((_, index) => index !== summaryIndex); + // Most details stay closed: mount Base UI on hover or focus, before the first click. + if (!armed && !expanded && !searching) { + return ( +
+
+ +
+
+ ); + } + return (
- { - if (nativeDrag.draggable) nativeDrag.onDragStart(event); - else - startPanelLinkDrag( - event, - fileChipPanelLink(panelOpener, panelPath, (path, options) => - onOpenInPanel(path, line, options), - ), - ); - }} - kind={chipKind} - dir="ltr" - render={} - aria-label={labelPrefix === undefined ? undefined : `${labelPrefix}${label}`} - className={MARKDOWN_FILE_LINK_CLASS_NAME} - data-markdown-copy={copyMarkdown} - onClick={(event) => { - if (leavesFileChipClickToBrowser(href, event)) return; - event.preventDefault(); - event.stopPropagation(); - if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { - handleOpenInEditor(); - return; - } - if (useBrowserPrimaryAction) { - handleOpenInBrowser(); - return; - } - handleOpenInFilePreview(); - }} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - labelPrefix={labelPrefix} - theme={theme} - /> - - ) : ( - } - aria-label={gt("File options for {label}", { label: `${labelPrefix ?? ""}${label}` })} - aria-haspopup="menu" - className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} - data-markdown-copy={copyMarkdown} - onClick={handleContextMenu} - onContextMenu={handleContextMenu} - > - - ) : undefined - } - path={iconPath} - environmentId={environmentId} - label={label} - labelPrefix={labelPrefix} - theme={theme} - /> - - ) + const tooltipContent = ( + + ); + const sharedTooltip = useSharedTooltip({ + render: () => tooltipContent, + contentKey: `${iconPath}\u0000${targetPath}`, + variant: "code", + }); + const chip = hasPrimaryAction ? ( + { + if (nativeDrag.draggable) nativeDrag.onDragStart(event); + else + startPanelLinkDrag( + event, + fileChipPanelLink(panelOpener, panelPath, (path, options) => + onOpenInPanel(path, line, options), + ), + ); + }} + kind={chipKind} + dir="ltr" + render={} + aria-label={labelPrefix === undefined ? undefined : `${labelPrefix}${label}`} + className={MARKDOWN_FILE_LINK_CLASS_NAME} + data-markdown-copy={copyMarkdown} + onClick={(event) => { + if (leavesFileChipClickToBrowser(href, event)) return; + event.preventDefault(); + event.stopPropagation(); + if (onOpen && shouldOpenMarkdownFileLinkInEditor(event)) { + handleOpenInEditor(); + return; + } + if (useBrowserPrimaryAction) { + handleOpenInBrowser(); + return; } + handleOpenInFilePreview(); + }} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + labelPrefix={labelPrefix} + theme={theme} + /> + + ) : ( + } + aria-label={gt("File options for {label}", { label: `${labelPrefix ?? ""}${label}` })} + aria-haspopup="menu" + className={cn(MARKDOWN_FILE_LINK_CLASS_NAME, "select-text")} + data-markdown-copy={copyMarkdown} + onClick={handleContextMenu} + onContextMenu={handleContextMenu} + > + : undefined + } + path={iconPath} + environmentId={environmentId} + label={label} + labelPrefix={labelPrefix} + theme={theme} /> + + ); + if (sharedTooltip) return withSharedTooltip(chip, sharedTooltip); + return ( + + - + {tooltipContent} ); diff --git a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx b/apps/web/src/components/chat/MarkdownMath.browser.test.tsx deleted file mode 100644 index ec5b38541ddc4..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.browser.test.tsx +++ /dev/null @@ -1,36 +0,0 @@ -import { expect, it } from "vite-plus/test"; -import { userEvent } from "vite-plus/test/browser"; - -import { render } from "../../../test/render"; -import "../../index.css"; - -import { MarkdownMath } from "./MarkdownMath"; - -it("keeps keyboard scrolling available as a streamed equation outgrows its viewport", async () => { - const equation = (tex: string, width = 180) => ( -
- - - -
- ); - await using screen = await render(equation("x")); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8")); - const scroller = screen.getByLabelText("Scroll display equation"); - await expect.element(scroller).toHaveAttribute("tabindex", "0"); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(scroller).toHaveFocus(); - await userEvent.keyboard("{ArrowRight}"); - await expect.element(scroller).not.toHaveProperty("scrollLeft", 0); - - await screen.rerender(equation("x_1 + x_2 + x_3 + x_4 + x_5 + x_6 + x_7 + x_8", 1000)); - await expect.element(screen.getByLabelText("Scroll display equation")).not.toBeInTheDocument(); - await screen.getByRole("button", { name: "Before equation" }).click(); - await userEvent.keyboard("{Tab}"); - await expect.element(screen.getByRole("button", { name: "After equation" })).toHaveFocus(); -}); diff --git a/apps/web/src/components/chat/MarkdownMath.tsx b/apps/web/src/components/chat/MarkdownMath.tsx deleted file mode 100644 index 8070d64ac3c18..0000000000000 --- a/apps/web/src/components/chat/MarkdownMath.tsx +++ /dev/null @@ -1,81 +0,0 @@ -import { useGT } from "gt-react"; -import { lazy, memo, Suspense, useLayoutEffect, useRef, useState } from "react"; - -import { observeResize } from "../../lib/observeResize"; - -import { RenderErrorBoundary } from "../RenderErrorBoundary"; - -const MathTypeset = lazy(() => import("./MathTypeset")); - -/** - * One formula from `remark-math`. Shows its TeX until KaTeX loads, and - * keeps showing it when KaTeX cannot parse it, such as mid-stream. Copying - * any part of a formula copies its whole TeX source. - */ -export const MarkdownMath = memo(function MarkdownMath(props: { - tex: string; - display: boolean; - focusable?: boolean; -}) { - const gt = useGT(); - const viewportRef = useRef(null); - const contentRef = useRef(null); - const [overflows, setOverflows] = useState(false); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes formula DOM width to make overflowing equations keyboard scrollable - useLayoutEffect(() => { - const viewport = viewportRef.current; - const content = contentRef.current; - if (!viewport || !content || props.focusable === false) return; - const measure = () => setOverflows(viewport.scrollWidth > viewport.clientWidth); - measure(); - // Typesetting and streamed TeX can change content width without resizing the viewport. - return observeResize([viewport, content], measure); - }, [props.focusable]); - const scrollable = props.focusable !== false && overflows; - const tex = props.tex.trim(); - const source = props.display ? `\\[\n${tex}\n\\]` : `\\(${tex}\\)`; - const fallback = {source}; - return ( - - - - - - - - - - - - ); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.test.ts b/apps/web/src/components/chat/MathTypeset.logic.test.ts deleted file mode 100644 index 634f5146475ac..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import katex from "katex"; -import { describe, expect, it } from "vite-plus/test"; - -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -describe("escapeLiteralPercents", () => { - it.each([ - ["\\text{3.18% yield}", "\\text{3.18\\% yield}"], - ["\\text{100%% yield}", "\\text{100\\%\\% yield}"], - ["6\\% + 2\\%", "6\\% + 2\\%"], - ["x\\\\%", "x\\\\\\%"], - ["x % note\n+ 1", "x % note\n+ 1"], - ["% note\n\\text{2%}", "% note\n\\text{2\\%}"], - ["x &= 1 % +9%\n\\text{2%}", "x &= 1 % +9%\n\\text{2\\%}"], - ["\\verb|50%|+\\text{2%}", "\\verb|50%|+\\text{2\\%}"], - ["\\verb*%a%b%+c%", "\\verb*%a%b\\%+c\\%"], - ["\\verb|50%+\\text{2%}", "\\verb|50%+\\text{2%}"], - ])("repairs %j", (tex, expected) => { - expect(escapeLiteralPercents(tex)).toBe(expected); - }); - - it("lets the reported multiline equation typeset", () => { - const tex = - "R_e=\\underbrace{\\frac{1.0176}{32}}_{\\text{3.18% dividend yield}}\n+\\underbrace{6\\%}_{\\text{growth}}\n=\\boxed{9.18\\%}"; - expect(() => katex.renderToString(tex, { throwOnError: true })).toThrow(); - expect(() => - katex.renderToString(escapeLiteralPercents(tex), { throwOnError: true }), - ).not.toThrow(); - }); -}); diff --git a/apps/web/src/components/chat/MathTypeset.logic.ts b/apps/web/src/components/chat/MathTypeset.logic.ts deleted file mode 100644 index 04111ab4a70b4..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.logic.ts +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Escapes each `%` written right after other text, as in `\text{3.18% yield}`. - * A `%` at a line start or after whitespace stays a comment. Skips escapes and - * `\verb` like KaTeX's lexer, in one linear pass. - */ -export function escapeLiteralPercents(tex: string): string { - let repaired = ""; - let copied = 0; - let index = 0; - while (index < tex.length) { - const char = tex[index]; - if (char === "\\") { - if (tex.startsWith("\\verb", index)) { - const starred = tex[index + 5] === "*"; - const delimiter = tex[index + (starred ? 6 : 5)]; - if (delimiter !== undefined && (starred || !/[*a-zA-Z]/.test(delimiter))) { - const bodyStart = index + (starred ? 7 : 6); - let close = bodyStart; - while (close < tex.length && ![delimiter, "\n", "\r"].includes(tex[close]!)) close++; - // KaTeX rejects a \verb that does not close on its own line. - if (tex[close] !== delimiter) return tex; - index = close + 1; - continue; - } - } - // A control symbol such as `\%` or `\\` is two characters. - index += 2; - } else if (char === "%" && index > 0 && !/\s/.test(tex[index - 1]!)) { - repaired += `${tex.slice(copied, index)}\\%`; - copied = ++index; - } else if (char === "%") { - const newline = tex.indexOf("\n", index); - index = newline === -1 ? tex.length : newline + 1; - } else { - index++; - } - } - return copied === 0 ? tex : repaired + tex.slice(copied); -} diff --git a/apps/web/src/components/chat/MathTypeset.tsx b/apps/web/src/components/chat/MathTypeset.tsx deleted file mode 100644 index e70b9787e2161..0000000000000 --- a/apps/web/src/components/chat/MathTypeset.tsx +++ /dev/null @@ -1,50 +0,0 @@ -import katex from "katex"; -import "katex/dist/katex.min.css"; -import type { ReactNode } from "react"; - -import { mathMacros } from "../../fork/mathMacros"; -import { LRUCache } from "../../lib/lruCache"; -import { escapeLiteralPercents } from "./MathTypeset.logic"; - -// Virtualized threads remount messages while scrolling; cached markup keeps -// that from typesetting the same formulas again. "" records a parse error. -const typesetCache = new LRUCache(1000, 4 * 1024 * 1024); - -function typeset(tex: string, display: boolean): string { - const key = `${display ? "display" : "inline"}:${tex}`; - const cached = typesetCache.get(key); - if (cached !== null) return cached; - const options = { - displayMode: display, - output: "htmlAndMathml" as const, - throwOnError: true, - // No \href, \url, \htmlClass, or other commands that emit active HTML. - trust: false, - strict: "ignore" as const, - maxSize: 20, - maxExpand: 1000, - }; - let html = ""; - try { - html = katex.renderToString(tex, { ...options, macros: mathMacros() }); - } catch { - const repaired = escapeLiteralPercents(tex); - if (repaired !== tex) { - try { - html = katex.renderToString(repaired, { ...options, macros: mathMacros() }); - } catch { - // Unfinished or unsupported TeX stays readable as its source. - } - } - } - typesetCache.set(key, html, (key.length + html.length) * 2); - return html; -} - -/** KaTeX lives in this lazily loaded chunk, so it is only fetched once a formula renders. */ -export default function MathTypeset(props: { tex: string; display: boolean; fallback: ReactNode }) { - const html = typeset(props.tex, props.display); - if (!html) return props.fallback; - // KaTeX escapes the TeX it renders, and `trust: false` keeps it from emitting links or attributes. - return ; -} diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 608a8b4e33c8d..49428f7c87c0c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -44,11 +44,10 @@ import { type PendingApproval, deriveTimelineEntriesFromVisibleTurnItems, } from "../../session-logic"; -import type { Root } from "mdast"; import { ViewedImagesTimelineRow } from "./TimelineWorkEntryRow"; -import { remarkThoughtPreview, THOUGHT_PREVIEW_MAX_LENGTH } from "./TimelineWorkEntryRow.logic"; +import { THOUGHT_PREVIEW_MAX_LENGTH, thoughtPreviewMarkdown } from "./TimelineWorkEntryRow.logic"; +import { wordsHast } from "~/markdown/wordsHast"; import { TimelineRowCtx } from "./timelineRowContext"; -import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; import { searchableMessageSegments } from "@t3tools/shared/threadFindText"; import { countThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { collectThreadFindRanges } from "./threadFindHighlights"; @@ -2146,49 +2145,22 @@ describe("compact reasoning math", () => { ["hard \nbreak\\\nagain", [["text", "hard break again"]]], ["
only html
", [["text", "Reasoning"]]], ])("keeps formulas while flattening compact reasoning previews: %j", (source, expected) => { - const tree = parseMarkdownWithMath(source); - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children.map((node) => [node.type, "value" in node ? node.value : null])).toEqual( - expected, - ); - }); - - it("stops reading the tree once the preview is full", () => { - const beyondCap = (): string => { - throw new Error("read beyond cap"); - }; - const head = "x".repeat(THOUGHT_PREVIEW_MAX_LENGTH - 2); - const tree: Root = { - type: "root", - children: [ - { - type: "paragraph", - children: [ - { type: "text", value: head }, - { type: "strong", children: [{ type: "text", value: "yz beyond" }] }, - { - type: "inlineMath", - get value() { - return beyondCap(); - }, - }, - ], - }, - { - type: "paragraph", - children: [ - { - type: "text", - get value() { - return beyondCap(); - }, - }, - ], - }, - ], - }; - remarkThoughtPreview("Reasoning")(tree); - expect(tree.children).toEqual([{ type: "text", value: `${head}yz` }]); + const tree = wordsHast(source, { + math: true, + breaks: false, + escapeHtml: false, + insights: false, + extensions: thoughtPreviewMarkdown("Reasoning"), + }); + expect( + tree.children.map((node) => + node.type === "text" + ? ["text", node.value] + : node.type === "element" && node.children[0]?.type === "element" + ? ["inlineMath", String(node.children[0].properties.ariaLabel).trim()] + : [node.type, null], + ), + ).toEqual(expected); }); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 0a703a675f0ac..f1726cbbb92b2 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -1785,7 +1785,7 @@ describe("deriveMessagesTimelineRows", () => { expect(rows.at(-1)).toMatchObject({ kind: "thinking" }); }); - it("does not show Thinking once the open run's provider turn has ended", () => { + it("does not show Thinking once the provider turn has ended or its reply is streaming", () => { const input = { timelineEntries: [ { @@ -1821,6 +1821,29 @@ describe("deriveMessagesTimelineRows", () => { latestRun: { ...input.latestRun, turnEnded: true }, }); expect(ended.some((row) => row.kind === "thinking")).toBe(false); + + const streamingReply = deriveMessagesTimelineRows({ + ...input, + timelineEntries: [ + ...input.timelineEntries, + { + id: "assistant-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:05Z", + message: { + id: "assistant" as never, + role: "assistant" as const, + text: "Here is the first paragraph of the answer", + runId: "turn-1" as never, + createdAt: "2026-01-01T00:00:05Z", + updatedAt: "2026-01-01T00:00:06Z", + streaming: true, + }, + }, + ], + }); + expect(streamingReply.at(-1)?.id).toBe("assistant-entry"); + expect(streamingReply.some((row) => row.kind === "thinking")).toBe(false); }); it("keeps a promptless restart in one active visual response", () => { @@ -4548,7 +4571,6 @@ it("keeps the working header in place across worktree setup handoff", () => { "worktree-setup", "working", "message", - "thinking", ]); const stage = (id: "agent" | "setup-script", status: "done" | "running") => @@ -4744,7 +4766,29 @@ describe("failed turn transcript", () => { ); expect(work.at(-1)?.detail).toBe("The provider stopped this turn.\nRetry later."); expect(work.at(-1)?.createdAt).toBe("2026-09-20T12:00:00.000Z"); - if (isLatest) return; + if (isLatest) { + // The recovery notice hides the failure row; the run's work stays grouped. + const noticeRows = deriveMessagesTimelineRows({ + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: items.filter((row) => row.item.type !== "error"), + optimisticMessages: [], + }), + latestRun: { + runId, + status: "failed", + startedAt: DateTime.formatIso(at), + completedAt: DateTime.formatIso(at), + }, + usageLimitRunId: runId, + isWorking: false, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect(noticeRows.find((row) => row.kind === "work-toggle")).toEqual( + expect.objectContaining({ hiddenCount: 3, expanded: false }), + ); + return; + } const entriesWithoutTools = deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems: items.filter((row) => row.item.type !== "command_execution"), optimisticMessages: [], diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 4756c4fbbea8c..7fb3ffba14d95 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -14,7 +14,7 @@ import { IDLE_COMPACTION_TITLES, } from "@t3tools/client-runtime/user-message"; import type { HandoffTimelineRun } from "@t3tools/client-runtime/handoff"; -import { renderCodexDirectivesForCopy } from "@t3tools/shared/codexMarkdownDirectives"; +import { renderCodexDirectivesForCopy } from "~/markdown/markdownText"; import { commandDisplayText, commandProgramName, @@ -1058,8 +1058,9 @@ function failedTimelineRunIds( function itemizedFailedRunIds( entries: ReadonlyArray, failedRunIds: ReadonlySet, + usageLimitRunId: RunId | null, ) { - const usageLimited = new Set(); + const usageLimited = new Set(usageLimitRunId ? [usageLimitRunId] : []); const otherFailures = new Set(); for (const entry of entries) { const item = timelineEntryFailedItem(entry); @@ -1614,6 +1615,8 @@ export function deriveMessagesTimelineRows( timelineEntries: ReadonlyArray; pendingApprovalRequestIds?: ReadonlySet; latestRun?: TimelineLatestRun | null; + /** The usage-limited run whose failure row the recovery notice replaces. */ + usageLimitRunId?: RunId | null; runningRunId?: RunId | null; expandedRunIds?: ReadonlySet; expandedAttemptIds?: ReadonlySet; @@ -1666,7 +1669,11 @@ export function deriveMessagesTimelineRows( const nextRows: MessagesTimelineRow[] = []; const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries); const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null); - const itemizedRunIds = itemizedFailedRunIds(timelineEntries, failedRunIds); + const itemizedRunIds = itemizedFailedRunIds( + timelineEntries, + failedRunIds, + input.usageLimitRunId ?? null, + ); const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries); const retainedAssistantReplyIds = retainedAssistantReplyEntryIds(timelineEntries); const supersededFoldsByAnchorEntryId = deriveSupersededAttemptFolds( @@ -2379,6 +2386,11 @@ export function deriveMessagesTimelineRows( } } + const latestTimelineEntry = timelineEntries.at(-1); + const replyIsStreaming = + latestTimelineEntry?.kind === "message" && + latestTimelineEntry.message.role === "assistant" && + latestTimelineEntry.message.streaming; const hasWorkingRow = nextRows.some((row) => row.kind === "working"); if (input.isWorking && !hasWorkingRow && activeTurnHeaderIndex === timelineEntries.length) { appendWorkingRow(); @@ -2386,6 +2398,7 @@ export function deriveMessagesTimelineRows( if ( input.isWorking && input.latestRun?.turnEnded !== true && + !replyIsStreaming && !setupOwnsWorkingSlot && !hasActiveCompaction && !compactionOnlyRunFinished && diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 1dd98645139d7..2bcdd663da63f 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -263,6 +263,7 @@ interface MessagesTimelineProps { listRef: React.RefObject; timelineEntries: ReadonlyArray; latestRun: TimelineLatestRun | null; + usageLimitRunId?: RunId | null; /** The run the screen reader announcer follows; see announcedRun. */ announcedRun?: { readonly runId: RunId; readonly status: TimelineLatestRun["status"] } | null; /** See isDetailBehindShell. */ @@ -293,6 +294,8 @@ interface MessagesTimelineProps { readonly sideChat?: boolean; /** Where it runs, when that is another environment. */ readonly environmentLabel?: string; + /** What this thread is to it, when not its subagent or side chat: `Step of`, say. */ + readonly relation?: { readonly label: string; readonly actionLabel: string }; readonly open?: () => void; } | null; workflowOpening?: WorkflowOpening | null; @@ -390,6 +393,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ findNavigationId = 0, repliesChosen = false, latestRun, + usageLimitRunId = null, announcedRun = null, detailBehindShell = false, runningRunId = null, @@ -761,6 +765,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ timelineEntries, pendingApprovalRequestIds, latestRun, + usageLimitRunId, runningRunId, expandedRunIds: visibleExpandedRunIds, expandedAttemptIds: visibleExpandedAttemptIds, @@ -1234,13 +1239,14 @@ const ConversationTimeline = memo(function ConversationTimeline({
diff --git a/apps/web/src/components/chat/ProposedPlanCard.tsx b/apps/web/src/components/chat/ProposedPlanCard.tsx index 292a6ef9d84cd..0109db3dee3b5 100644 --- a/apps/web/src/components/chat/ProposedPlanCard.tsx +++ b/apps/web/src/components/chat/ProposedPlanCard.tsx @@ -213,7 +213,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({ threadRef={threadRef} isStreaming={false} headingLevelOffset={3} - // Fork: selects the agent-text single-tilde list, so a plan's "1~2" keeps its tilde. + // Fork: agent text, so a plan's "1~2" keeps its tilde. assistantReply /> ) : ( @@ -224,7 +224,7 @@ export const ProposedPlanCard = memo(function ProposedPlanCard({ threadRef={threadRef} isStreaming={false} headingLevelOffset={3} - // Fork: selects the agent-text single-tilde list, so a plan's "1~2" keeps its tilde. + // Fork: agent text, so a plan's "1~2" keeps its tilde. assistantReply /> )} diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index d8318b7279e7d..20ea71f88adcd 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -10,6 +10,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { parseGoalCommand, type ChatAttachment as ContractChatAttachment, @@ -272,7 +273,9 @@ export function QueuedRunsControl({ const previewText = isAttachmentOnlyBootstrapPrompt(item.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(item.text, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(item.text, (reference) => reference.label), + ), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; // The server decides on the agent's text, and a goal command can stop the turn. diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 99c53d48d4f61..b1c91814d5c50 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -147,9 +147,14 @@ export function RightPanelSurfaceContent(props: { getShortcutContext={props.getShortcutContext} shortcutsEnabled={visible && props.activeSurfaceId === surface.id} key={`${scopedThreadKey(threadRef)}:${surface.id}`} - environmentId={props.environmentId} + environmentId={ + (surface.environmentId as EnvironmentId | undefined) ?? props.environmentId + } onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, @@ -211,12 +216,24 @@ export function RightPanelSurfaceContent(props: { threadRef={threadRef} onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, ...(reference.host ? { host: reference.host } : {}), }); }} + onSelectIssue={({ host, ...reference }) => { + useRightPanelStore.getState().openIssue(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), + ...reference, + ...(host ? { host } : {}), + }); + }} /> ); case "pull-requests": diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 052a5742b7aab..666ce784b3afc 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -236,6 +236,48 @@ it("opens an idle child beside the thread, and in its place with the modifier", expect(panel().surfaces).toHaveLength(1); }); +it("keeps focus on the list when Show more pages reveal the last rows", async () => { + setup(); + const projection = makeThreadProjectionFixture(); + const environmentId = EnvironmentId.make("local"); + const { updatedAt } = projection.thread; + state.projection = { + ...projection, + subagents: Array.from({ length: 7 }, (_, index) => ({ + id: NodeId.make(`agent-${index}`), + threadId: projection.thread.id, + runId: null, + parentNodeId: NodeId.make("parent"), + origin: "app_owned", + createdBy: "agent", + driver: "codex", + providerInstanceId: projection.thread.providerInstanceId, + providerThreadId: null, + childThreadId: ThreadId.make(`omitted-child-${index}`), + nativeTaskRef: null, + prompt: `Inspect the change part ${index}`, + title: `Agent ${index}`, + model: null, + status: "completed", + result: null, + startedAt: null, + completedAt: updatedAt, + updatedAt, + })), + }; + await using screen = await render( + , + ); + await screen.getByRole("button", { name: /Previous agents/ }).click(); + await screen.getByRole("button", { name: "Show 1 more" }).click(); + await expect.element(screen.getByRole("list", { name: "Related threads" })).toHaveFocus(); +}); + it("shows a lineage thread's full title in its tooltip", async () => { setup(); const longTitle = "Compare the lineage tooltip against a title that the row truncates"; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 9675a21620d32..b005fa877b745 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -121,19 +121,28 @@ function ThreadLineageRowList(props: { readonly children: ReactNode; }) { const gt = useGT(); + const listRef = useRef(null); + const showMore = () => { + const exhausting = props.hiddenCount <= THREAD_LINEAGE_PAGE_COUNT; + props.onShowMore(); + // The button unmounts on the final page; focus the list so focus isn't dropped. + if (exhausting) listRef.current?.focus({ preventScroll: true }); + }; return ( <> {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
    {props.children}
{props.hiddenCount > 0 ? (
)} diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index 2a487b1f237de..ac43d667d80ca 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.test.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.test.ts @@ -13,6 +13,7 @@ import { composerFileAttachmentMimeType, fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, + imagesToAttachBesidePastedText, normalizeComposerImageFileMimeType, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; @@ -121,10 +122,32 @@ describe("composer attachment files", () => { ).toBe(true); }); - it("leaves an image-and-text clipboard to the text path under Paste as Text", () => { + it("leaves a Word image-and-text clipboard to the text path, with or without Paste as Text", () => { const image = new File(["png"], "image.png", { type: "image/png" }); const input = { files: [image], plainText: "Hello from Word", bypassAutoAttachment: true }; expect(shouldHandleComposerAttachmentPaste(input)).toBe(false); + // A plain paste of the same Word clipboard keeps the text too. + expect(shouldHandleComposerAttachmentPaste({ ...input, bypassAutoAttachment: false })).toBe( + false, + ); + // Firefox's Copy Image adds the image URL as text and only an as HTML; the image attaches. + expect( + shouldHandleComposerAttachmentPaste({ + files: [image], + plainText: "https://example.com/image.png", + htmlIsOnlyImage: true, + }), + ).toBe(true); + // Finder adds a copied file's name as text. + expect(shouldHandleComposerAttachmentPaste({ files: [image], plainText: "image.png" })).toBe( + true, + ); + // A QQ or WeChat message has its text beside an in the HTML: the image attaches too. + const message = { files: [image], plainText: "Look at this", htmlHasImageAndText: true }; + expect(shouldHandleComposerAttachmentPaste(message)).toBe(false); + expect(imagesToAttachBesidePastedText(message)).toEqual([image]); + expect(imagesToAttachBesidePastedText({ ...message, htmlHasImageAndText: false })).toEqual([]); + expect(imagesToAttachBesidePastedText({ ...message, bypassAutoAttachment: true })).toEqual([]); }); it("preserves text when the clipboard also includes generic image files", () => { diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 041db7193d2e2..538d2dfd67304 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -239,30 +239,65 @@ export function attachmentsToReleaseOnUploadCapabilityLoss( ); } +function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { + const names = new Set(files.map((file) => file.name)); + return text + .split(/\r?\n/) + .filter((line) => line.length > 0) + .every((line) => names.has(line)); +} + +/** + * A browser's Copy Image puts only an in text/html; a chat message (QQ, WeChat) puts its text + * beside the ; rich text sources (Word, Pages) put only the text there. + */ +export function clipboardHtmlImageContent(html: string): "only-image" | "image-and-text" | "none" { + if (html.length === 0) return "none"; + const body = new DOMParser().parseFromString(html, "text/html").body; + if (body.querySelector("img") === null) return "none"; + return (body.textContent ?? "").trim().length === 0 ? "only-image" : "image-and-text"; +} + +function isPastedImageFile(file: File): boolean { + const classification = classifyComposerAttachmentFile(file); + return classification === "image" || classification === "unsupported-image"; +} + +/** The images of a message copied with its text: they attach while the text pastes as text. */ +export function imagesToAttachBesidePastedText(input: { + readonly files: ReadonlyArray; + readonly plainText: string; + readonly bypassAutoAttachment?: boolean; + readonly htmlHasImageAndText: boolean; +}): File[] { + if (input.bypassAutoAttachment || input.plainText.length === 0 || !input.htmlHasImageAndText) { + return []; + } + return input.files.filter(isPastedImageFile); +} + export function shouldHandleComposerAttachmentPaste(input: { readonly files: ReadonlyArray; readonly plainText: string; readonly bypassAutoAttachment?: boolean; + readonly htmlIsOnlyImage?: boolean; }): boolean { // Paste as Text keeps the text even when the source also put an image of it on the clipboard. if (input.bypassAutoAttachment && input.plainText.length > 0) return false; if ( - input.files.some((file) => { - if (isDngFile(file)) return true; - const classification = classifyComposerAttachmentFile(file); - return ( - classification === "image" || - classification === "unsupported-image" || - isSvgAttachment({ name: file.name, mimeType: file.type }) - ); - }) + input.files.some( + (file) => isDngFile(file) || isSvgAttachment({ name: file.name, mimeType: file.type }), + ) ) { return true; } - - if (input.plainText.length > 0) { - return false; + const hasImage = input.files.some(isPastedImageFile); + if (input.plainText.length === 0) { + return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } - - return input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); + // Rich text sources (Word, Pages) add a picture of the text. Copy Image adds the image URL as + // text beside an , and a Finder copy adds the file names. + return ( + hasImage && (input.htmlIsOnlyImage === true || isOnlyFileNames(input.plainText, input.files)) + ); } diff --git a/apps/web/src/components/chat/composerContextUndo.test.ts b/apps/web/src/components/chat/composerContextUndo.test.ts index a763b47a0d6d7..c493aa2dfc8fd 100644 --- a/apps/web/src/components/chat/composerContextUndo.test.ts +++ b/apps/web/src/components/chat/composerContextUndo.test.ts @@ -1,4 +1,8 @@ -import type { PreviewAnnotationPayload } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + type PreviewAnnotationPayload, +} from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import type { ComposerImageAttachment } from "../../composerDraftStore"; @@ -37,7 +41,7 @@ const annotation = { } satisfies PreviewAnnotationPayload; function retention(): RetainedAttachmentContextPayloads { - return { files: new Map(), previewAnnotations: new Map() }; + return { files: new Map(), previewAnnotations: new Map(), restoredQueuedImageIds: new Set() }; } describe("reconcileAttachmentContextReferences", () => { @@ -88,4 +92,65 @@ describe("reconcileAttachmentContextReferences", () => { }), ]); }); + + it("drops a queued file with its chip, keeps a queued image, and lets undo and redo restore and remove either", () => { + const file = { + attachment: { + type: "file" as const, + id: ChatAttachmentId.make("server-file"), + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + contextIds: [ComposerContextId.make("file_local")], + }; + const queuedImage = { + attachment: { + type: "image" as const, + id: ChatAttachmentId.make("server-image"), + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }, + contextIds: [ComposerContextId.make("image_local")], + }; + const base = { files: [], images: [], previewAnnotations: [], retained: retention() }; + + const deleted = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [file, queuedImage], + }); + expect(deleted.queuedAttachmentIdsToRemove).toEqual([file.attachment.id]); + + const undone = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(["file_local", "image_local"]), + removedQueuedAttachments: [file, queuedImage], + }); + expect(undone.queuedAttachmentsToRestore).toEqual([file.attachment, queuedImage.attachment]); + + const redone = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [file, queuedImage], + fromHistory: true, + }); + expect(redone.queuedAttachmentIdsToRemove).toEqual([ + file.attachment.id, + queuedImage.attachment.id, + ]); + + reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(["image_local"]), + removedQueuedAttachments: [queuedImage], + }); + const backspaced = reconcileAttachmentContextReferences({ + ...base, + referencedContextIds: new Set(), + queuedAttachments: [queuedImage], + }); + expect(backspaced.queuedAttachmentIdsToRemove).toEqual([]); + }); }); diff --git a/apps/web/src/components/chat/composerContextUndo.ts b/apps/web/src/components/chat/composerContextUndo.ts index fd2a0cde59341..4c96ec12b70fc 100644 --- a/apps/web/src/components/chat/composerContextUndo.ts +++ b/apps/web/src/components/chat/composerContextUndo.ts @@ -1,4 +1,6 @@ import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, PreviewAnnotationPayload, ThreadContextRecord, @@ -9,15 +11,23 @@ import type { ComposerFileAttachment, ComposerImageAttachment } from "../../comp import { fileContextReference, previewAnnotationContextId } from "../../lib/composerContextRecords"; import type { TerminalContextDraft } from "../../lib/terminalContext"; import type { ReviewCommentContext } from "../../reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; interface RetainedPreviewAnnotation { annotation: PreviewAnnotationPayload; image: ComposerImageAttachment | undefined; } +export interface QueuedAttachmentContextBinding { + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; +} + export interface RetainedAttachmentContextPayloads { files: Map; previewAnnotations: Map; + /** Queued images brought back because their chip reappeared. */ + restoredQueuedImageIds: Set; } export interface RetainedContextPayloads extends RetainedAttachmentContextPayloads { @@ -35,6 +45,7 @@ function createRetainedContextPayloads(): RetainedContextPayloads { environments: new Map(), files: new Map(), previewAnnotations: new Map(), + restoredQueuedImageIds: new Set(), }; } @@ -61,12 +72,19 @@ export function useRetainedContextPayloads(draftTargetKey: string): RetainedCont export function reconcileAttachmentContextReferences(input: { referencedContextIds: ReadonlySet; files: ReadonlyArray; + /** Attachments of a queued message being edited, and those removed during the edit. */ + queuedAttachments?: ReadonlyArray; + removedQueuedAttachments?: ReadonlyArray; + /** The change came from undo or redo. */ + fromHistory?: boolean; images: ReadonlyArray; previewAnnotations: ReadonlyArray; retained: RetainedAttachmentContextPayloads; }): { filesToRemove: string[]; filesToRestore: ComposerFileAttachment[]; + queuedAttachmentIdsToRemove: string[]; + queuedAttachmentsToRestore: ChatAttachment[]; annotationIdsToRemove: string[]; annotationsToRestore: RetainedPreviewAnnotation[]; } { @@ -86,6 +104,23 @@ export function reconcileAttachmentContextReferences(input: { return file ? [file] : []; }); + const isReferenced = (entry: QueuedAttachmentContextBinding) => + entry.contextIds.some((contextId) => input.referencedContextIds.has(contextId)); + const restoredImageIds = input.retained.restoredQueuedImageIds; + const queuedAttachmentIdsToRemove = (input.queuedAttachments ?? []).flatMap((entry) => { + if (entry.contextIds.length === 0 || isReferenced(entry)) return []; + if (isQueuedFileAttachment(entry.attachment)) return [entry.attachment.id]; + // Like draft images, a queued image outlives its deleted chip, unless undo or redo + // takes away a chip whose return had brought the image back. + const wasRestored = restoredImageIds.delete(entry.attachment.id); + return wasRestored && input.fromHistory ? [entry.attachment.id] : []; + }); + const queuedAttachmentsToRestore = (input.removedQueuedAttachments ?? []).flatMap((entry) => { + if (!isReferenced(entry)) return []; + if (isQueuedImageAttachment(entry.attachment)) restoredImageIds.add(entry.attachment.id); + return [entry.attachment]; + }); + const imagesById = new Map(input.images.map((image) => [image.id, image])); const liveAnnotationContextIds = new Set( input.previewAnnotations.map((annotation) => previewAnnotationContextId(annotation.id)), @@ -106,5 +141,12 @@ export function reconcileAttachmentContextReferences(input: { return retained ? [retained] : []; }); - return { filesToRemove, filesToRestore, annotationIdsToRemove, annotationsToRestore }; + return { + filesToRemove, + filesToRestore, + queuedAttachmentIdsToRemove, + queuedAttachmentsToRestore, + annotationIdsToRemove, + annotationsToRestore, + }; } diff --git a/apps/web/src/components/chat/markdownIslands.test.ts b/apps/web/src/components/chat/markdownIslands.test.ts new file mode 100644 index 0000000000000..f328c9ea51251 --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.test.ts @@ -0,0 +1,50 @@ +import type { Root } from "hast"; +import { renderToStaticMarkup } from "react-dom/server"; +import { createElement, Fragment } from "react"; +import { describe, expect, it } from "vite-plus/test"; + +import { renderHastWithIslands } from "./markdownIslands"; + +describe("renderHastWithIslands", () => { + it("writes SVG attributes by their SVG names in static HTML", () => { + const tree: Root = { + type: "root", + children: [ + { + type: "element", + tagName: "p", + properties: {}, + children: [ + { + type: "element", + tagName: "svg", + properties: { viewBox: "0 0 1 1" }, + children: [ + { + type: "element", + tagName: "text", + properties: { fontSize: "700", strokeWidth: "2" }, + children: [{ type: "text", value: "x" }], + }, + ], + }, + ], + }, + ], + }; + const html = renderToStaticMarkup( + createElement( + Fragment, + null, + renderHastWithIslands(tree, { + components: {}, + variant: "", + isIsland: () => false, + staticElement: (node) => node, + }), + ), + ); + expect(html).toContain('x'); + expect(html).toContain('viewBox="0 0 1 1"'); + }); +}); diff --git a/apps/web/src/components/chat/markdownIslands.ts b/apps/web/src/components/chat/markdownIslands.ts new file mode 100644 index 0000000000000..8c434daf099ce --- /dev/null +++ b/apps/web/src/components/chat/markdownIslands.ts @@ -0,0 +1,214 @@ +import type { Element, ElementContent, Properties, Root, RootContent } from "hast"; +import { find, html as htmlSchema, svg as svgSchema } from "property-information"; +import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; +import { createElement, Fragment as ReactFragment, type ReactNode } from "react"; +import { Fragment, jsx, jsxs } from "react/jsx-runtime"; + +export interface MarkdownIslandOptions { + readonly components: Partial; + /** Elements that need their React component; everything else renders as static HTML. */ + readonly isIsland: (node: Element) => boolean; + /** What a static element's component would have added, or the node itself when nothing. */ + readonly staticElement: (node: Element) => Element; + /** Separates static HTML that `staticElement` renders differently, such as a heading offset. */ + readonly variant: string; +} + +const VOID_ELEMENTS = new Set( + "area base br col embed hr img input link meta source track wbr".split(" "), +); + +const jsxOptions = (components: Partial) => + ({ + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + }) as const; + +// Static HTML depends only on the cached, immutable tree and the variant. +const innerHtmlCache = new WeakMap(); + +function transformStatic( + node: ElementContent, + staticElement: MarkdownIslandOptions["staticElement"], +): ElementContent { + if (node.type !== "element") return node; + const element = staticElement(node); + let children: ElementContent[] | undefined; + for (let index = 0; index < element.children.length; index++) { + const child = element.children[index]!; + const next = transformStatic(child, staticElement); + if (next !== child) { + children ??= element.children.slice(); + children[index] = next; + } + } + return children ? { ...element, children } : element; +} + +function innerHtml(node: Element, options: MarkdownIslandOptions): string { + const cached = innerHtmlCache.get(node); + if (cached?.variant === options.variant) return cached.html; + let html = ""; + for (const child of node.children) { + html += serialize(transformStatic(child, options.staticElement)); + } + innerHtmlCache.set(node, { variant: options.variant, html }); + return html; +} + +interface AttributeInfo { + readonly name: string; + readonly boolean: boolean; + readonly separator: string; +} + +const attributeInfo = new Map(); + +// SVG names its attributes differently (`fontSize` is `font-size`), so its lookups key apart. +function infoFor(property: string, inSvg: boolean): AttributeInfo { + const key = inSvg ? `svg:${property}` : property; + let info = attributeInfo.get(key); + if (!info) { + const found = find(inSvg ? svgSchema : htmlSchema, property); + info = { + name: found.attribute, + boolean: found.boolean || found.overloadedBoolean, + separator: found.commaSeparated ? ", " : " ", + }; + attributeInfo.set(key, info); + } + return info; +} + +const escapeText = (value: string) => + value.includes("&") || value.includes("<") || value.includes(">") + ? value.replace(/&/g, "&").replace(//g, ">") + : value; +const escapeAttribute = (value: string) => + value.includes("&") || value.includes('"') + ? value.replace(/&/g, "&").replace(/"/g, """) + : value; + +/** HTML for the elements and text this pipeline builds; the DOM matches hast-util-to-html's. */ +function serialize(node: ElementContent, inSvg = false): string { + if (node.type === "text") return escapeText(node.value); + if (node.type !== "element") return ""; + const svg = inSvg || node.tagName === "svg"; + let html = `<${node.tagName}`; + const { properties } = node; + for (const key in properties) { + const value = properties[key]; + if (value === null || value === undefined || value === false || Number.isNaN(value)) continue; + const info = infoFor(key, svg); + if (info.boolean && value) { + html += ` ${info.name}`; + continue; + } + const text = Array.isArray(value) + ? value.join(info.separator) + : value === true + ? "" + : String(value); + html += ` ${info.name}="${escapeAttribute(text)}"`; + } + html += ">"; + if (VOID_ELEMENTS.has(node.tagName)) return html; + for (const child of node.children) html += serialize(child, svg); + return `${html}`; +} + +/** React props for an element, converted as hast-util-to-jsx-runtime converts them. */ +function shallowProps(node: Element, components: Partial): Record { + const element = toJsxRuntime( + { ...node, children: [] }, + { ...jsxOptions(components), components: {}, passNode: false }, + ) as { props: Record }; + const { children: _children, ...props } = element.props; + return props; +} + +interface Plan { + readonly islands: Set; + /** Elements with an island somewhere below them. */ + readonly ancestors: Set; +} + +function renderContent( + node: RootContent, + key: number, + options: MarkdownIslandOptions, + plan: Plan, +): ReactNode { + if (node.type === "text") return node.value; + if (node.type !== "element") return null; + if (plan.islands.has(node)) { + return createElement( + ReactFragment, + { key }, + toJsxRuntime(node, jsxOptions(options.components)), + ); + } + const element = options.staticElement(node); + const props: Record = { ...shallowProps(element, options.components), key }; + if (plan.ancestors.has(node)) { + return createElement( + element.tagName, + props, + ...element.children.map((child, index) => renderContent(child, index, options, plan)), + ); + } + if (element.children.length > 0 && !VOID_ELEMENTS.has(element.tagName)) { + props.dangerouslySetInnerHTML = { __html: innerHtml(node, options) }; + } + return createElement(element.tagName, props); +} + +/** + * Renders a hast tree with React only on the path to elements that need a component: subtrees + * without one become static HTML, which the browser builds without React reconciling each node. + */ +export function renderHastWithIslands(tree: Root, options: MarkdownIslandOptions): ReactNode { + // The same elements again let React skip the block; islands still follow their context. + let signature = options.variant; + const plan: Plan = { islands: new Set(), ancestors: new Set() }; + const visit = (node: Root | Element): boolean => { + let below = false; + for (const child of node.children) { + if (child.type !== "element") continue; + const island = options.isIsland(child); + signature += island ? "1" : "0"; + if (island) { + plan.islands.add(child); + below = true; + continue; + } + if (visit(child)) { + plan.ancestors.add(child); + below = true; + } + } + return below; + }; + visit(tree); + const cached = renderedTrees.get(tree); + if (cached?.signature === signature && cached.components === options.components) { + return cached.node; + } + const node = tree.children.map((child, index) => renderContent(child, index, options, plan)); + renderedTrees.set(tree, { signature, components: options.components, node }); + return node; +} + +const renderedTrees = new WeakMap< + Root, + { signature: string; components: Partial; node: ReactNode } +>(); + +export function withProperties(node: Element, properties: Properties): Element { + return { ...node, properties: { ...node.properties, ...properties } }; +} diff --git a/apps/web/src/components/chat/markdownRenderer.test.tsx b/apps/web/src/components/chat/markdownRenderer.test.tsx index f15fe49584aea..a9a60c545b37b 100644 --- a/apps/web/src/components/chat/markdownRenderer.test.tsx +++ b/apps/web/src/components/chat/markdownRenderer.test.tsx @@ -1,88 +1,41 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; import { describe, expect, it } from "vite-plus/test"; -import { createIncrementalMarkdownPlugin } from "../../markdown-incremental"; import { createMarkdownRenderer } from "./markdownRenderer"; // Visible in the markup, so every URL attribute must pass through it. const urlTransform = (url: string) => `${url}#seen`; describe("createMarkdownRenderer", () => { - const render = createMarkdownRenderer({ - remarkPlugins: CHAT_MARKDOWN_REMARK_PLUGINS, - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, + const renderer = createMarkdownRenderer({ + markdown: { math: false, breaks: false, escapeHtml: false, insights: false, extensions: {} }, components: {}, urlTransform, }); + const render = (text: string) => renderer.element(renderer.parse(text)); + const renderAndRemember = (text: string) => { + const entry = renderer.parse(text); + renderer.remember(text, entry); + return renderer.element(entry); + }; - it.each([ - '# Title\n\nText with `code`, **bold**, [a link](https://example.com "t") and https://bare.example.com.', - "![shot](./shot.png) and [file](file:///C:/repo/a.ts) and [bad](javascript:alert(1))", - "
More\n\nHidden bold \n\n
", - "| a | b |\n| - | - |\n|
| [x](#frag) |\n\n- [ ] task\n- [x] done", - '```ts title="a.ts"\nconst a = 1;\n```\n\n> [!WARNING]\n> careful
bare', - "Footnote[^1] and ~~strike~~\n\n[^1]: the note", - // Each GFM construct the parser skips when its text cannot match, next to one that can. - "Mail me@example.com, see www.example.com and HTTPS://example.com/a, not [x](https://y.z).", - "a.b-c_d+e@x.io and @user\n\n`me@x.io` ", - "A table without pipes\n:--", - "> | quoted |\n> | - |\n> | body |\n\n- [ ] open\n- [X] done", - "Escaped www\\.example.com and me@example.com", - "\ufeffA byte order mark\n\n| a |\n| - |\n| b |", - "> - | a |\r\n> | - |\r\n> | me@x.io |\r\n\n-\t[ ] tab\n\n ~~lazy~~", - ])("renders what react-markdown renders: %j", (source) => { - const expected = renderToStaticMarkup( - - {source} - , + it("passes every URL attribute through the transform", () => { + const html = renderToStaticMarkup( + render('![shot](./shot.png) and [a link](https://example.com "t") and '), ); - const element = render(source); - expect(renderToStaticMarkup(element)).toBe(expected); - render.remember(source, element); - expect(render(source)).toBe(element); + expect(html).toContain('src="./shot.png#seen"'); + expect(html).toContain('href="https://example.com#seen"'); + expect(html).toContain('src="b.png#seen"'); }); - it("renders what react-markdown renders while a reply streams through the incremental parser", () => { - const reply = - "```ts\nconst a = 1;\n```\n\n| a | b |\n| - | - |\n| me@x.io | www.x.io |\n\nDone ~~now~~."; - // As ChatMarkdown streams: one incremental plugin for the reply, a fresh renderer per update. - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 1; end <= reply.length; end++) { - const source = reply.slice(0, end); - const streamed = createMarkdownRenderer({ - remarkPlugins: [...CHAT_MARKDOWN_REMARK_PLUGINS, incremental], - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, - components: {}, - urlTransform, - })(source); - expect(renderToStaticMarkup(streamed)).toBe( - renderToStaticMarkup( - - {source} - , - ), - ); - } + it("reuses a remembered message's element", () => { + const element = renderAndRemember("# Title\n\nText with `code` and **bold**."); + expect(render("# Title\n\nText with `code` and **bold**.")).toBe(element); }); it("keeps cached messages when one far larger than the cache is rendered", () => { - const element = render("Kept *message*"); - render.remember("Kept *message*", element); - const large = "x".repeat(600_000); - render.remember(large, render(large)); + const element = renderAndRemember("Kept *message*"); + renderAndRemember("x".repeat(600_000)); expect(render("Kept *message*")).toBe(element); }); }); diff --git a/apps/web/src/components/chat/markdownRenderer.ts b/apps/web/src/components/chat/markdownRenderer.ts index 9637d68e8f158..c2aa499a9583d 100644 --- a/apps/web/src/components/chat/markdownRenderer.ts +++ b/apps/web/src/components/chat/markdownRenderer.ts @@ -3,18 +3,13 @@ import { toJsxRuntime, type Components } from "hast-util-to-jsx-runtime"; import { urlAttributes } from "html-url-attributes"; import type { ReactElement } from "react"; import { Fragment, jsx, jsxs } from "react/jsx-runtime"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { type PluggableList, unified } from "unified"; -import { VFile } from "vfile"; -import { remarkParseWithoutUnusedSyntax } from "./markdownSyntaxGates"; +import { wordsHast, type WordsHastOptions } from "../../markdown/wordsHast"; export type MarkdownUrlTransform = (url: string, key: string, node: Element) => string; interface MarkdownRendererOptions { - readonly remarkPlugins: PluggableList; - readonly rehypePlugins: PluggableList; + readonly markdown: WordsHastOptions; readonly components: Partial; readonly urlTransform: MarkdownUrlTransform; } @@ -23,7 +18,11 @@ interface MarkdownRendererOptions { // reuses one instead of parsing again. Parsing is most of the cost of rendering markdown. // An element and the hast it keeps hold about 20 bytes per source character, so ~10 MB. const MAX_CACHED_CHARS = 500_000; -const rendered = new Map(); +interface Rendered { + readonly tree: Root; + element?: ReactElement; +} +const rendered = new Map(); let cachedChars = 0; let nextRendererId = 0; @@ -31,10 +30,10 @@ let nextRendererId = 0; const ENTRY_OVERHEAD_CHARS = 200; const entrySize = (key: string) => key.length + ENTRY_OVERHEAD_CHARS; -function remember(key: string, element: ReactElement) { +function remember(key: string, entry: Rendered) { // One huge message would otherwise evict everything else. if (entrySize(key) > MAX_CACHED_CHARS / 4) return; - rendered.set(key, element); + rendered.set(key, entry); cachedChars += entrySize(key); for (const oldest of rendered.keys()) { if (cachedChars <= MAX_CACHED_CHARS) break; @@ -43,32 +42,18 @@ function remember(key: string, element: ReactElement) { } } -/** Renders markdown as react-markdown does, with one processor per plugin set. */ +/** Renders markdown with Words, keeping one parse cache per option set. */ export function createMarkdownRenderer({ - remarkPlugins, - rehypePlugins, + markdown, components, urlTransform, }: MarkdownRendererOptions) { - const processor = unified() - .use(remarkParse) - .use(remarkParseWithoutUnusedSyntax) - .use(remarkPlugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(rehypePlugins) - .freeze(); const keyPrefix = `${nextRendererId++}\u0000`; - // Literal raw HTML that survived the rehype plugins, and URL attributes, as react-markdown treats them. + // URL attributes, as react-markdown transformed them. const prepare = (node: Nodes) => { if (!("children" in node)) return; - const { children } = node; - for (let index = 0; index < children.length; index++) { - const child = children[index]!; - if (child.type === "raw") { - children[index] = { type: "text", value: child.value }; - continue; - } + for (const child of node.children) { if (child.type !== "element") continue; const { properties } = child; for (const key in properties) { @@ -82,7 +67,7 @@ export function createMarkdownRenderer({ } }; - const render = (text: string): ReactElement => { + const parse = (text: string): Rendered => { const key = keyPrefix + text; const cached = rendered.get(key); if (cached !== undefined) { @@ -91,24 +76,27 @@ export function createMarkdownRenderer({ rendered.set(key, cached); return cached; } - const file = new VFile(text); - const tree = processor.runSync(processor.parse(file), file) as Root; + const tree = wordsHast(text, markdown); prepare(tree); - return toJsxRuntime(tree, { - Fragment, - components, - ignoreInvalidStyle: true, - jsx, - jsxs, - passKeys: true, - passNode: true, - }); + return { tree }; }; - return Object.assign(render, { - remember(text: string, element: ReactElement) { + return { + /** A cached entry, or a fresh one that `remember` can keep. Cached trees are shared, so callers must not change them. */ + parse, + element: (entry: Rendered): ReactElement => + (entry.element ??= toJsxRuntime(entry.tree, { + Fragment, + components, + ignoreInvalidStyle: true, + jsx, + jsxs, + passKeys: true, + passNode: true, + })), + remember(text: string, entry: Rendered) { const key = keyPrefix + text; - if (!rendered.has(key)) remember(key, element); + if (!rendered.has(key)) remember(key, entry); }, - }); + }; } diff --git a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx b/apps/web/src/components/chat/markdownStreamBlocks.test.ts similarity index 81% rename from apps/web/src/components/chat/markdownStreamBlocks.test.tsx rename to apps/web/src/components/chat/markdownStreamBlocks.test.ts index 38ecff7666508..b89940489ec32 100644 --- a/apps/web/src/components/chat/markdownStreamBlocks.test.tsx +++ b/apps/web/src/components/chat/markdownStreamBlocks.test.ts @@ -1,32 +1,19 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, - remarkAssistantInsights, -} from "@t3tools/shared/markdownPipeline"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkMath from "remark-math"; -import type { PluggableList } from "unified"; +import { toHtml } from "hast-util-to-html"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { splitMarkdownBlocks } from "./markdownStreamBlocks"; -import { rehypeHeadingIds } from "./markdownFragments"; - -const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]]; // Whitespace between top-level blocks collapses in the rendered message. const renderMarkdown = (source: string, math = false) => - renderToStaticMarkup( - - {source} - , + toHtml( + wordsHast(source, { + math, + breaks: false, + escapeHtml: false, + insights: source.includes("★ Insight"), + extensions: {}, + }), ) .replace(/>\s+<") .trim(); diff --git a/apps/web/src/components/chat/markdownSyntaxGates.ts b/apps/web/src/components/chat/markdownSyntaxGates.ts deleted file mode 100644 index 57587a51b9d13..0000000000000 --- a/apps/web/src/components/chat/markdownSyntaxGates.ts +++ /dev/null @@ -1,204 +0,0 @@ -import type { Nodes as MdastNodes } from "mdast"; -import { - type Extension as MdastExtension, - fromMarkdown, - type Options as FromMarkdownOptions, - type Transform, -} from "mdast-util-from-markdown"; -import { combineExtensions } from "micromark-util-combine-extensions"; -import type { Construct, Extension, TokenizeContext } from "micromark-util-types"; -import type { Processor } from "unified"; - -// A table needs a delimiter row: dashes with a `|` or `:`, after any `>` or indent. -// One character class per pattern: overlapping ones backtrack quadratically on a run of dashes. -const DELIMITER_LINE = /^[ \t>|:-]+$/gm; -const isDelimiterRow = (line: string) => line.includes("-") && /[|:]/.test(line); -const NEXT_LINE = /[^\r\n]*(?:\r\n?|\n)([^\r\n]*)/y; - -function hasDelimiterRow(text: string) { - for (const [line] of text.matchAll(DELIMITER_LINE)) if (isDelimiterRow(line)) return true; - return false; -} -const PROTOCOL = /https?:\/\//iy; -const WWW = /www\./iy; -const EMAIL_ATEXT = /[\w+.-]*@/y; - -const matchesAt = (pattern: RegExp, text: string, offset: number) => { - pattern.lastIndex = offset; - return pattern.test(text); -}; - -interface Gate { - readonly names: ReadonlyArray; - /** False when the construct cannot match anywhere in the text. */ - readonly inText: (text: string) => boolean; - /** False when it cannot start at this offset, which keeps micromark from trying it there. */ - readonly at?: (context: TokenizeContext, text: string, offset: number) => boolean; -} - -// micromark tries these at every candidate character: email autolinks at every word, tables -// at every line. That is most of what GFM adds to a parse, and most texts cannot match them. -const GATES: ReadonlyArray = [ - { - names: ["emailAutolink"], - inText: (text) => text.includes("@"), - at: (_, text, offset) => matchesAt(EMAIL_ATEXT, text, offset), - }, - { - names: ["protocolAutolink"], - inText: (text) => /https?:\/\//i.test(text), - at: (_, text, offset) => matchesAt(PROTOCOL, text, offset), - }, - { - names: ["wwwAutolink"], - inText: (text) => /www\./i.test(text), - at: (_, text, offset) => matchesAt(WWW, text, offset), - }, - { - names: ["table"], - inText: hasDelimiterRow, - at: (context, text, offset) => { - NEXT_LINE.lastIndex = offset; - const nextLine = NEXT_LINE.exec(text)?.[1]; - return (nextLine !== undefined && hasDelimiterRow(nextLine)) || continuesTable(context); - }, - }, - { names: ["strikethrough"], inText: (text) => text.includes("~") }, - { - names: ["gfmFootnoteCall", "gfmPotentialFootnoteCall", "gfmFootnoteDefinition"], - inText: (text) => text.includes("[^"), - }, - { names: ["tasklistCheck"], inText: (text) => /\[[\sxX]\]/.test(text) }, -]; - -// A body row follows the head or another row. Mirrors `start` in micromark-extension-gfm-table's -// lib/syntax.js: recheck it when that package changes. -function continuesTable({ events }: TokenizeContext) { - let index = events.length - 1; - while (index > -1 && /^(?:lineEnding|linePrefix)$/.test(events[index]![1].type)) index--; - // The table extension's token types are not in micromark's map unless its types are loaded. - const tail: string | undefined = events[index]?.[1].type; - return tail === "tableHead" || tail === "tableRow"; -} - -let parsing = ""; -const gated = new WeakMap(); - -function gatedConstruct(construct: Construct, gate: Gate): Construct { - const at = gate.at; - if (!at) return construct; - let wrapped = gated.get(construct); - if (!wrapped) { - const { previous, tokenize } = construct; - wrapped = { - ...construct, - tokenize(effects, ok, nok) { - return at(this, parsing, this.now().offset) ? tokenize.call(this, effects, ok, nok) : nok; - }, - ...(previous && { - previous(code) { - return previous.call(this, code) && at(this, parsing, this.now().offset); - }, - }), - }; - gated.set(construct, wrapped); - } - return wrapped; -} - -type ConstructMap = Record; - -function gateExtension(extension: Extension, absent: ReadonlySet): Extension { - const gateOf = (name: string | undefined) => - GATES.find((gate) => name && gate.names.includes(name)); - const result: Record = {}; - for (const [field, value] of Object.entries(extension)) { - if (field === "disable" || field === "attentionMarkers" || !value) { - result[field] = value; - continue; - } - const map: ConstructMap = {}; - for (const [code, entry] of Object.entries(value as ConstructMap)) { - const kept = (Array.isArray(entry) ? entry : [entry]).flatMap((construct) => { - const gate = construct && gateOf(construct.name); - if (!construct || !gate) return construct ? [construct] : []; - return absent.has(gate) ? [] : [gatedConstruct(construct, gate)]; - }); - if (kept.length > 0) map[code] = Array.isArray(entry) ? kept : kept[0]; - } - result[field] = map; - } - return result as Extension; -} - -type MdastExtensions = NonNullable; - -// Merged once, as mdast-util-from-markdown merges them on every call: lists in order, handlers by key. -function mergeMdastExtensions(extensions: MdastExtensions): MdastExtension { - const merged = { - canContainEols: [] as string[], - enter: {}, - exit: {}, - transforms: [] as Transform[], - }; - for (const extension of extensions.flat()) { - merged.canContainEols.push(...(extension.canContainEols ?? [])); - Object.assign(merged.enter, extension.enter); - Object.assign(merged.exit, extension.exit); - // GFM looks for autolink literals again in the decoded text outside links, so `www\.x.io` - // links too. Most texts have URLs only in link destinations and code, where it finds nothing. - for (const transform of extension.transforms ?? []) { - merged.transforms.push( - extension.enter?.literalAutolink - ? (tree) => (hasAutolinkText(tree) ? transform(tree) : undefined) - : transform, - ); - } - } - return merged; -} - -const AUTOLINK_TEXT = /@|https?:\/\/|www\./i; - -function hasAutolinkText(node: MdastNodes): boolean { - if (node.type === "text") return AUTOLINK_TEXT.test(node.value); - if (node.type === "link" || node.type === "linkReference" || !("children" in node)) return false; - return node.children.some(hasAutolinkText); -} - -/** - * Parses as remark-parse does, without the syntax extension constructs that cannot match the - * text. Same tree, in about half the time. - */ -function attachParserWithoutUnusedSyntax(this: Processor) { - const data = this.data(); - const byMask = new Map(); - let mdastExtensions: MdastExtension[] | undefined; - this.parser = (document) => { - let mask = 0; - GATES.forEach((gate, index) => { - if (!gate.inText(document)) mask |= 1 << index; - }); - let extensions = byMask.get(mask); - if (!extensions) { - const absent = new Set(GATES.filter((_, index) => mask & (1 << index))); - extensions = [ - combineExtensions( - (data.micromarkExtensions ?? []).map((extension) => gateExtension(extension, absent)), - ), - ]; - byMask.set(mask, extensions); - } - mdastExtensions ??= [mergeMdastExtensions(data.fromMarkdownExtensions ?? [])]; - const outer = parsing; - // Gates read micromark offsets, which skip a leading byte order mark. - parsing = document.charCodeAt(0) === 0xfeff ? document.slice(1) : document; - try { - return fromMarkdown(document, { ...data.settings, extensions, mdastExtensions }); - } finally { - parsing = outer; - } - }; -} - -export const remarkParseWithoutUnusedSyntax = attachParserWithoutUnusedSyntax; diff --git a/apps/web/src/components/chat/markdownTextDirection.ts b/apps/web/src/components/chat/markdownTextDirection.ts index ffdbde76c1148..a4c78d3342754 100644 --- a/apps/web/src/components/chat/markdownTextDirection.ts +++ b/apps/web/src/components/chat/markdownTextDirection.ts @@ -1,4 +1,4 @@ -import { textDirection } from "~/textDirection"; +import { LETTER, RTL_LETTER, textDirection } from "~/textDirection"; type HastNode = { type?: string; @@ -57,11 +57,32 @@ function isolateInlineCode(node: HastNode): void { */ export function rehypeTextDirection() { return (tree: HastNode) => { - for (const block of tree.children ?? []) { - if (block.type !== "element" || block.tagName === "pre") continue; - const dir = textDirection(proseText(block)); - if (dir) block.properties = { ...block.properties, dir }; - } + blockTextDirections(tree); isolateInlineCode(tree); }; } + +/** Each top-level block's direction, from its prose; an RTL letter decides as textDirection does. */ +function blockTextDirections(tree: HastNode) { + for (const block of tree.children ?? []) { + if (block.type !== "element" || block.tagName === "pre") continue; + const dir = scriptOf(block) === "rtl" ? textDirection(proseText(block)) : scriptOf(block); + if (dir) block.properties = { ...block.properties, dir }; + } +} + +/** "rtl" when any prose letter is right-to-left; otherwise what textDirection would say. */ +function scriptOf(node: HastNode): "rtl" | "ltr" | undefined { + let found: "ltr" | undefined; + const visit = (current: HastNode): boolean => { + if (current.type === "text") { + const value = current.value ?? ""; + if (RTL_LETTER.test(value)) return true; + if (!found && LETTER.test(value)) found = "ltr"; + return false; + } + if (current.tagName === "code") return false; + return (current.children ?? []).some(visit); + }; + return visit(node) ? "rtl" : found; +} diff --git a/apps/web/src/components/chat/preparingComposerImages.test.ts b/apps/web/src/components/chat/preparingComposerImages.test.ts new file mode 100644 index 0000000000000..29a0f80f52386 --- /dev/null +++ b/apps/web/src/components/chat/preparingComposerImages.test.ts @@ -0,0 +1,58 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { EnvironmentId, ProviderDriverKind, ThreadId } from "@t3tools/contracts"; +import { expect, it } from "vite-plus/test"; + +import { composerTargetKey, useComposerDraftStore } from "../../composerDraftStore"; +import { + addPreparingComposerImages, + cancelHeldComposerSend, + cancelPreparingComposerImages, + holdComposerSend, + joinPreparedImagesToDraft, + removePreparingComposerImages, +} from "./preparingComposerImages"; + +function preparingImage(id: string) { + return { id, name: `${id}.png`, file: new File(["png"], `${id}.png`), hidden: false }; +} + +it("holds a message send until its images join the draft, and cancels on edit, cancel, or new paste", async () => { + const draftTarget = scopeThreadRef(EnvironmentId.make("environment-held"), ThreadId.make("held")); + const target = composerTargetKey(draftTarget); + const drafts = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => { + cancelPreparingComposerImages(target); + drafts.clearComposerContent(draftTarget); + }, + }; + drafts.setPrompt(draftTarget, "check"); + expect(holdComposerSend(draftTarget)).toBeNull(); + + // Two pastes compress separately; the first joining the draft is not an edit. + addPreparingComposerImages(target, [preparingImage("first")]); + addPreparingComposerImages(target, [preparingImage("second")]); + const held = holdComposerSend(draftTarget); + await expect(holdComposerSend(draftTarget)).resolves.toEqual({ status: "cancelled" }); + removePreparingComposerImages(target, new Set(["first"])); + joinPreparedImagesToDraft(() => drafts.setPrompt(draftTarget, "check first")); + removePreparingComposerImages(target, new Set(["second"])); + await expect(held).resolves.toEqual({ status: "ready" }); + + for (const cancel of [ + () => drafts.setPrompt(draftTarget, "check again"), + () => + drafts.setProviderModelOptions(draftTarget, ProviderDriverKind.make("codex"), [ + { id: "reasoningEffort", value: "high" }, + ]), + () => cancelHeldComposerSend(target), + () => addPreparingComposerImages(target, [preparingImage("added-mid-wait")]), + () => removePreparingComposerImages(target, new Set(["later"]), { cancelSubmission: true }), + ]) { + addPreparingComposerImages(target, [preparingImage("later")]); + const cancelled = holdComposerSend(draftTarget); + cancel(); + await expect(cancelled).resolves.toEqual({ status: "cancelled" }); + cancelPreparingComposerImages(target); + } +}); diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index 47d24ab5f7a89..951e7f661221c 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -3,7 +3,13 @@ import type { ScopedThreadRef } from "@t3tools/contracts"; import { useEffect, useRef } from "react"; import { create } from "zustand"; +import { + composerTargetKey, + type ComposerThreadTarget, + useComposerDraftStore, +} from "../../composerDraftStore"; import { useStableCallback } from "../../hooks/useStableCallback"; +import { composerDraftContentChanged } from "./composerSend.logic"; export interface PreparingComposerImage { readonly id: string; @@ -69,6 +75,9 @@ export function addPreparingComposerImages( targetKey: string, images: ReadonlyArray, ): void { + if (images.length > 0) { + heldSends.get(targetKey)?.({ status: "cancelled" }); + } usePreparingComposerImageStore.setState((state) => ({ byTargetKey: { ...state.byTargetKey, @@ -116,8 +125,89 @@ export function removePreparingComposerImages( // Bumped on cancel so a send held for the cancelled images is dropped rather than released. const cancelGenerations = new Map(); +export type HeldComposerSendResult = + | { readonly status: "ready" } + | { readonly status: "cancelled" }; + +const heldSends = new Map void>(); +const useHeldSendStore = create<{ readonly targetKeys: Readonly> }>(() => ({ + targetKeys: {}, +})); +let preparedImagesJoiningDraft = false; + function invalidatePendingSubmit(targetKey: string) { cancelGenerations.set(targetKey, (cancelGenerations.get(targetKey) ?? 0) + 1); + heldSends.get(targetKey)?.({ status: "cancelled" }); +} + +/** Whether a send from the target's draft is waiting on its images to finish preparing. */ +export function useComposerSendHeld(targetKey: string): boolean { + return useHeldSendStore((state) => state.targetKeys[targetKey] === true); +} + +export function cancelHeldComposerSend(targetKey: string): void { + heldSends.get(targetKey)?.({ status: "cancelled" }); +} + +/** Inserts finished images into the draft without counting as an edit to a held send. */ +export function joinPreparedImagesToDraft(insert: () => T): T { + preparedImagesJoiningDraft = true; + try { + return insert(); + } finally { + preparedImagesJoiningDraft = false; + } +} + +/** + * Holds a send made while the draft still has images compressing. Resolves ready once they join + * the draft, or cancelled if the draft is edited or the send cancelled. Null means nothing needs + * to wait. Lives outside the composer so leaving the thread still completes the send. + */ +export function holdComposerSend( + draftTarget: ComposerThreadTarget, +): Promise | null { + const targetKey = composerTargetKey(draftTarget); + if (countPreparingComposerImages(targetKey) === 0) return null; + if (heldSends.has(targetKey)) return Promise.resolve({ status: "cancelled" }); + return new Promise((resolve) => { + let draft = useComposerDraftStore.getState().getComposerDraft(draftTarget); + const settle = (result: HeldComposerSendResult) => { + if (heldSends.get(targetKey) !== settle) return; + heldSends.delete(targetKey); + stopWatchingImages(); + stopWatchingDraft(); + useHeldSendStore.setState((state) => { + const targetKeys = { ...state.targetKeys }; + delete targetKeys[targetKey]; + return { targetKeys }; + }); + resolve(result); + }; + heldSends.set(targetKey, settle); + const stopWatchingImages = usePreparingComposerImageStore.subscribe((state) => { + if (state.byTargetKey[targetKey]) return; + // Let joinPreparedImagesToDraft finish inserting compressed images in this tick first. + queueMicrotask(() => settle({ status: "ready" })); + }); + const stopWatchingDraft = useComposerDraftStore.subscribe((state) => { + const next = state.getComposerDraft(draftTarget); + if ( + !preparedImagesJoiningDraft && + (composerDraftContentChanged(draft, next) || + draft?.modelSelectionByProvider !== next?.modelSelectionByProvider || + draft?.activeProvider !== next?.activeProvider || + draft?.runtimeMode !== next?.runtimeMode || + draft?.interactionMode !== next?.interactionMode) + ) { + settle({ status: "cancelled" }); + } + draft = next; + }); + useHeldSendStore.setState((state) => ({ + targetKeys: { ...state.targetKeys, [targetKey]: true }, + })); + }); } /** Drops every image still preparing for the target, so its compression result is discarded. */ diff --git a/apps/web/src/components/chat/queuedMessageEdit.test.ts b/apps/web/src/components/chat/queuedMessageEdit.test.ts index f67d1843c38be..0ebfdacdbb607 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.test.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.test.ts @@ -1,4 +1,11 @@ -import { EnvironmentId, MessageId, ThreadId, TurnItemId } from "@t3tools/contracts"; +import { + ChatAttachmentId, + ComposerContextId, + EnvironmentId, + MessageId, + ThreadId, + TurnItemId, +} 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"; @@ -10,11 +17,37 @@ import { } from "../../composerDraftStore"; import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue"; import { environmentContextRecord, responseContextRecord } from "../../lib/composerContextRecords"; -import { prepareQueuedEditAttachments, recoverQueuedMessageEdit } from "./queuedMessageEdit"; +import { formatInlineContextReference } from "../../lib/composerContextReferences"; +import { + matchRestorableQueuedAttachment, + prepareQueuedEditAttachments, + recoverQueuedMessageEdit, +} from "./queuedMessageEdit"; const environmentId = EnvironmentId.make("remote-environment"); const threadTarget = scopeThreadRef(environmentId, ThreadId.make("thread:edit")); const editTarget = DraftId.make("queued-edit:test"); +const originalMessage = { + editTarget, + threadTarget, + originalText: "Original message", + originalReplyTo: null, +}; +const reply = responseContextRecord({ + citation: { + version: 1, + environmentId, + threadId: ThreadId.make("thread:edit"), + messageId: MessageId.make("message:answer"), + text: "Done.", + start: 0, + end: 5, + prefix: "", + suffix: "", + }, + itemId: TurnItemId.make("item:answer"), + subagents: [], +}); const file: ComposerFileAttachment = { type: "file", id: "file:report", @@ -89,9 +122,7 @@ describe("queued message file edits", () => { uploadEnvironmentId: EnvironmentId.make("other-environment"), }; store.addFiles(editTarget, [file, elsewhere]); - expect( - recoverQueuedMessageEdit({ editTarget, threadTarget, originalText: "Original message" }), - ).toBe("kept"); + expect(recoverQueuedMessageEdit(originalMessage)).toBe("kept"); expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Original message"); // An upload this environment cannot reach comes back as a file to reattach, not a dropped chip. const { uploadedAttachmentId: _id, uploadEnvironmentId: _env, ...reattach } = elsewhere; @@ -107,28 +138,11 @@ describe("queued message file edits", () => { "Other", ); const machine = environmentContextRecord(EnvironmentId.make("environment-vps"), "vps"); - const reply = responseContextRecord({ - citation: { - version: 1, - environmentId, - threadId: ThreadId.make("thread:edit"), - messageId: MessageId.make("message:answer"), - text: "Done.", - start: 0, - end: 5, - prefix: "", - suffix: "", - }, - itemId: TurnItemId.make("item:answer"), - subagents: [], - }); store.addThreadContexts(editTarget, [thread]); store.addEnvironmentContexts(editTarget, [machine]); store.setReplyTo(editTarget, reply); const editedPrompt = store.getComposerDraft(editTarget)!.prompt; - expect( - recoverQueuedMessageEdit({ editTarget, threadTarget, originalText: "Original message" }), - ).toBe("kept"); + expect(recoverQueuedMessageEdit(originalMessage)).toBe("kept"); expect(store.getComposerDraft(editTarget)).toBeNull(); expect(store.getComposerDraft(threadTarget)).toMatchObject({ prompt: editedPrompt, @@ -138,14 +152,43 @@ describe("queued message file edits", () => { }); }); + it.each([ + { + edit: "added reply", + originalReplyTo: null, + replyTo: reply, + originalText: "", + result: "kept", + }, + { edit: "removed reply", originalReplyTo: reply, replyTo: null, result: "kept" }, + { + edit: "unchanged reply", + originalReplyTo: reply, + replyTo: structuredClone(reply), + result: "clean", + }, + ])( + "reports $result for a queued edit with $edit", + ({ originalReplyTo, replyTo, originalText = "Original message", result }) => { + const store = useComposerDraftStore.getState(); + store.setPrompt(editTarget, originalText); + store.setReplyTo(editTarget, replyTo); + expect( + recoverQueuedMessageEdit({ editTarget, threadTarget, originalText, originalReplyTo }), + ).toBe(result); + expect(store.getComposerDraft(editTarget)).toBeNull(); + expect(store.getComposerDraft(threadTarget)).toEqual( + result === "kept" ? expect.objectContaining({ prompt: originalText, replyTo }) : null, + ); + }, + ); + it("reports a removed queued attachment as an edit when the run leaves", () => { const store = useComposerDraftStore.getState(); store.setPrompt(editTarget, "Original message"); expect( recoverQueuedMessageEdit({ - editTarget, - threadTarget, - originalText: "Original message", + ...originalMessage, removedExistingAttachment: true, }), ).toBe("kept"); @@ -154,8 +197,7 @@ describe("queued message file edits", () => { // An attachment-only message leaves nothing to put back in the composer. expect( recoverQueuedMessageEdit({ - editTarget, - threadTarget, + ...originalMessage, originalText: "", removedExistingAttachment: true, }), @@ -163,6 +205,85 @@ describe("queued message file edits", () => { expect(store.getComposerDraft(threadTarget)).toBeNull(); }); + it("strips existing queued attachment references when recovering an edit into the thread draft", () => { + const store = useComposerDraftStore.getState(); + const chip = formatInlineContextReference({ + kind: "image", + contextId: "image_queued-1", + label: "image.png", + }); + store.setPrompt(editTarget, `Check ${chip} closely`); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `Check ${chip}`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("kept"); + expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Check closely"); + expect(store.getComposerDraft(editTarget)).toBeNull(); + + store.clearComposerContent(threadTarget); + store.setPrompt(editTarget, chip); + expect( + recoverQueuedMessageEdit({ + ...originalMessage, + originalText: `${chip} note`, + existingAttachmentContextIds: ["image_queued-1"], + }), + ).toBe("discarded"); + expect(store.getComposerDraft(threadTarget)).toBeNull(); + }); + + it("matches a removed queued attachment for same-environment paste while rejecting other environments or payloads", () => { + const fileId = ChatAttachmentId.make("server-file-1"); + const contextId = ComposerContextId.make("file_local-1"); + const removedAttachment = { + type: "file" as const, + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + const record = { + version: 1 as const, + kind: "file" as const, + contextId, + label: "notes.txt", + attachmentId: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }; + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toEqual({ attachment: removedAttachment, contextId }); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: EnvironmentId.make("other-environment"), + record, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + + expect( + matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId: environmentId, + record: { ...record, attachmentId: ChatAttachmentId.make("different-file") }, + removedQueuedAttachments: [{ attachment: removedAttachment, contextIds: [contextId] }], + }), + ).toBeNull(); + }); + it("does not overwrite a separate draft when the queued run leaves", () => { const store = useComposerDraftStore.getState(); store.setPrompt(threadTarget, "Separate draft"); @@ -172,9 +293,7 @@ describe("queued message file edits", () => { [file.id]: { status: "ready", environmentId, attachmentId: uploadedFile.id }, }, }); - expect(recoverQueuedMessageEdit({ editTarget, threadTarget, originalText: "" })).toBe( - "discarded", - ); + expect(recoverQueuedMessageEdit({ ...originalMessage, originalText: "" })).toBe("discarded"); expect(store.getComposerDraft(threadTarget)?.prompt).toBe("Separate draft"); expect(store.getComposerDraft(editTarget)).toBeNull(); expect(readAttachmentUpload(file.id)).toBeUndefined(); diff --git a/apps/web/src/components/chat/queuedMessageEdit.ts b/apps/web/src/components/chat/queuedMessageEdit.ts index c3f14d6fe2247..ca58777dcb44a 100644 --- a/apps/web/src/components/chat/queuedMessageEdit.ts +++ b/apps/web/src/components/chat/queuedMessageEdit.ts @@ -1,5 +1,15 @@ import { resolveQueuedEditExit } from "@t3tools/client-runtime/queued-run-edit"; -import type { ChatAttachment } from "@t3tools/contracts"; +import type { + ChatAttachment, + ChatFileAttachment, + ChatImageAttachment, + ComposerContextId, + ComposerContextRecord, + EnvironmentId, + OrchestrationMessageContext, + ResponseContextRecord, +} from "@t3tools/contracts"; +import * as Equal from "effect/Equal"; import { composerDraftHasUserContent, useComposerDraftStore, @@ -10,6 +20,68 @@ import { import { msg } from "gt-react"; import { m } from "../../i18n/messages"; import { releaseDraftAttachments } from "../../lib/attachmentUploadQueue"; +import { + attachmentContextRecord, + isSameComposerContextPayload, +} from "../../lib/composerContextRecords"; +import { removeInlineContextReference } from "../../lib/composerContextReferences"; + +export function isQueuedImageAttachment( + attachment: ChatAttachment, +): attachment is ChatImageAttachment { + return attachment.type === "image"; +} + +export function isQueuedFileAttachment( + attachment: ChatAttachment, +): attachment is ChatFileAttachment { + return attachment.type === "file"; +} + +export function attachmentContextIdsForRecord( + context: OrchestrationMessageContext | undefined, + attachment: Pick, +): ComposerContextId[] { + return (context?.records ?? []).flatMap((record) => + record.kind === attachment.type && + "attachmentId" in record && + record.attachmentId === attachment.id + ? [record.contextId] + : [], + ); +} + +export function matchRestorableQueuedAttachment(input: { + readonly environmentId: EnvironmentId; + readonly sourceEnvironmentId: EnvironmentId | null; + readonly record: Extract; + readonly removedQueuedAttachments: ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly contextIds: ReadonlyArray; + }>; +}): { readonly attachment: ChatAttachment; readonly contextId: ComposerContextId } | null { + if (input.sourceEnvironmentId !== input.environmentId) return null; + const match = input.removedQueuedAttachments.find( + ({ attachment, contextIds }) => + (isQueuedImageAttachment(attachment) || isQueuedFileAttachment(attachment)) && + attachment.type === input.record.kind && + contextIds.some((contextId) => + isSameComposerContextPayload( + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + input.record, + ), + ), + ); + if (!match || match.contextIds.length === 0) return null; + const contextId = + match.contextIds.find((candidate) => candidate === input.record.contextId) ?? + match.contextIds[0]!; + return { attachment: match.attachment, contextId }; +} /** Staged attachments upload as soon as they are added, so a dropped edit must release them. */ export function discardQueuedEditDraft(target: ComposerThreadTarget): void { @@ -28,21 +100,38 @@ export function recoverQueuedMessageEdit(input: { readonly editTarget: ComposerThreadTarget; readonly threadTarget: ComposerThreadTarget; readonly originalText: string; + readonly originalReplyTo: ResponseContextRecord | null; readonly removedExistingAttachment?: boolean; + readonly existingAttachmentContextIds?: ReadonlyArray; }): "kept" | "discarded" | "clean" { const store = useComposerDraftStore.getState(); const draft = store.getComposerDraft(input.editTarget); + const strippedPrompt = + draft && (input.existingAttachmentContextIds?.length ?? 0) > 0 + ? input.existingAttachmentContextIds!.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + draft.prompt, + ) + : draft?.prompt; + const recoveredDraft = + draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt + ? { ...draft, prompt: strippedPrompt } + : draft; const recovery = resolveQueuedEditExit({ editChanged: input.removedExistingAttachment === true || + !Equal.equals(draft?.replyTo ?? null, input.originalReplyTo) || (draft !== null && (draft.prompt !== input.originalText || draft.images.length > 0 || draft.files.length > 0)), // A cleared edit has nothing to put back, so it can only be discarded. threadDraftEmpty: - composerDraftHasUserContent(draft) && + composerDraftHasUserContent(recoveredDraft) && !composerDraftHasUserContent(store.getComposerDraft(input.threadTarget)), }); if (recovery === "kept") { + if (draft && strippedPrompt !== undefined && strippedPrompt !== draft.prompt) { + store.setPrompt(input.editTarget, strippedPrompt); + } store.moveComposerContent(input.editTarget, input.threadTarget); store.clearComposerContent(input.editTarget); } else { diff --git a/apps/web/src/components/chat/threadFindHighlights.ts b/apps/web/src/components/chat/threadFindHighlights.ts index ab19f2e96e9dc..d7b601163d1d0 100644 --- a/apps/web/src/components/chat/threadFindHighlights.ts +++ b/apps/web/src/components/chat/threadFindHighlights.ts @@ -1,6 +1,6 @@ import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import { useEffect, useEffectEvent, useRef } from "react"; -import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindText"; +import { THREAD_FIND_BLOCK_TAGS } from "@t3tools/shared/threadFindBlockTags"; import { observeResize } from "~/lib/observeResize"; diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.ts index 757b675f29525..9e9de82984f81 100644 --- a/apps/web/src/components/chat/timelineMinimapItems.ts +++ b/apps/web/src/components/chat/timelineMinimapItems.ts @@ -4,10 +4,9 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { Nodes } from "mdast"; -import remarkGfm from "remark-gfm"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Nodes } from "hast"; + +import { markdownTree } from "~/markdown/wordsHast"; import type { MessagesTimelineRow } from "./MessagesTimeline.logic"; @@ -58,53 +57,51 @@ function resolveFinalAssistantTextForTurn( return finalAssistantText; } -const markdownPreviewParser = unified() - .use(remarkParse) - .use(remarkGfm, { singleTilde: false }) - .freeze(); - -const INLINE_PARENT_TYPES = new Set([ - "paragraph", - "heading", - "tableCell", - "emphasis", +// Elements whose children run together; every other element is separated by a space. +const INLINE_PARENTS = new Set([ + "p", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "td", + "th", + "em", "strong", - "delete", - "link", - "linkReference", + "del", + "a", + "code", + "span", + "sup", + "sub", ]); function markdownNodeText(node: Nodes): string { - if (node.type === "html") { - return node.value - .replace(/|$)/g, "") - .replace(/<\/?([a-z][\w-]*)(?:[^"'<>]|"[^"]*"|'[^']*')*>/gi, (_, tag: string) => - /^(?:address|article|aside|blockquote|br|dd|details|div|dl|dt|figcaption|figure|footer|h[1-6]|header|hr|li|main|nav|ol|p|pre|section|summary|table|tbody|td|th|thead|tr|ul)$/i.test( - tag, - ) - ? " " - : "", - ); - } - if (node.type === "break") return " "; - if ("value" in node) return node.value; - if (node.type === "image" || node.type === "imageReference") return node.alt ?? ""; - if (!("children" in node)) return ""; - const separator = INLINE_PARENT_TYPES.has(node.type) ? "" : " "; + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "br") return " "; + if (node.type === "element" && node.tagName === "img") return String(node.properties.alt ?? ""); + if (node.type !== "element" && node.type !== "root") return ""; + const separator = node.type === "element" && INLINE_PARENTS.has(node.tagName) ? "" : " "; const text = node.children.map(markdownNodeText).join(separator); // A thread autolink's only text is its URL. - return node.type === "link" && parseThreadLinkHref(text) !== null ? "a thread" : text; + return node.type === "element" && node.tagName === "a" && parseThreadLinkHref(text) !== null + ? "a thread" + : text; } /** Markdown as one line of the text it renders, without markup or link targets. */ export function markdownPlainText(markdown: string): string { - return markdownNodeText(markdownPreviewParser.parse(markdown)).replace(/\s+/g, " ").trim(); + return markdownNodeText(markdownTree(markdown, { singleTilde: false })) + .replace(/\s+/g, " ") + .trim(); } // The tooltip shows a few lines; bound parsing work for long messages and streaming responses. function markdownMinimapPreview(markdown: string | null) { if (markdown === null) return null; - const compact = markdownNodeText(markdownPreviewParser.parse(markdown.slice(0, 1_500))) + const compact = markdownNodeText(markdownTree(markdown.slice(0, 1_500), { singleTilde: false })) .replace(/\s+/g, " ") .trim(); return compact.length > 0 ? compact : null; diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.ts b/apps/web/src/components/chat/useComposerAttachmentIntake.ts index cfd8fde657713..08b362b866e1a 100644 --- a/apps/web/src/components/chat/useComposerAttachmentIntake.ts +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.ts @@ -57,6 +57,7 @@ import { addPreparingComposerImages, getPreparingComposerImages, isPreparingComposerImage, + joinPreparedImagesToDraft, movedPreparingImageThread, removePreparingComposerImages, } from "./preparingComposerImages"; @@ -338,16 +339,19 @@ export function useComposerAttachmentIntake(input: { })); const unrestoredImageNames: string[] = []; const draftStore = useComposerDraftStore.getState(); - const storedImageIds = new Set( - movedThread - ? draftStore.addImages(movedThread, nextImages, { - onCapacityExceeded: (image) => unrestoredImageNames.push(image.name), - }) - : nextImages.length === 1 && nextImages[0] - ? addComposerImage(nextImages[0]) - : nextImages.length > 1 - ? addComposerImagesToDraft(nextImages) - : [], + const storedImageIds = joinPreparedImagesToDraft( + () => + new Set( + movedThread + ? draftStore.addImages(movedThread, nextImages, { + onCapacityExceeded: (image) => unrestoredImageNames.push(image.name), + }) + : nextImages.length === 1 && nextImages[0] + ? addComposerImage(nextImages[0]) + : nextImages.length > 1 + ? addComposerImagesToDraft(nextImages) + : [], + ), ); // Keep the placeholders until the draft decides whether the recovered images fit, // so a held send can be cancelled before the last placeholder disappears. @@ -365,10 +369,12 @@ export function useComposerAttachmentIntake(input: { } if (storedImages.length > 0 && imageAttachmentsGetChips && !movedThread) { insertedAny = - insertAttachmentReferences( - storedImages.map(imageContextReference), - undefined, - pendingInsertion, + joinPreparedImagesToDraft(() => + insertAttachmentReferences( + storedImages.map(imageContextReference), + undefined, + pendingInsertion, + ), ) || insertedAny; } // Only failures are reported here. Success must not pass `null`: by diff --git a/apps/web/src/components/chat/useComposerContextImport.ts b/apps/web/src/components/chat/useComposerContextImport.ts index 61d0abd7319a6..458f39dc98638 100644 --- a/apps/web/src/components/chat/useComposerContextImport.ts +++ b/apps/web/src/components/chat/useComposerContextImport.ts @@ -10,6 +10,7 @@ import * as Schema from "effect/Schema"; import type { RefObject } from "react"; import type { ChatComposerProps } from "./ChatComposer"; import { + type ChatAttachment, type ComposerContextClipboardFragment, type ComposerContextRecord, type EnvironmentId, @@ -59,6 +60,8 @@ import { useAtomCommand } from "../../state/use-atom-command"; import { useAtomQueryRunner } from "~/state/use-atom-query-runner"; import { useStableCallback } from "../../hooks/useStableCallback"; import { countPreparingComposerImages } from "./preparingComposerImages"; +import type { QueuedAttachmentContextBinding } from "./composerContextUndo"; +import { matchRestorableQueuedAttachment } from "./queuedMessageEdit"; const isUnreachable = Schema.is( Schema.Union([ConnectionTransientError, ConnectionBlockedError, EnvironmentRpcUnavailableError]), @@ -94,6 +97,8 @@ export function useComposerContextImport(input: { readonly promptRef: RefObject; readonly pendingThreadImportsRef: RefObject>; readonly addComposerFilesToDraft: (files: ComposerFileAttachment[]) => string[]; + readonly removedQueuedAttachments?: ReadonlyArray | undefined; + readonly onRestoreQueuedAttachment?: ((attachment: ChatAttachment) => void) | undefined; }) { const { environmentId, @@ -112,6 +117,8 @@ export function useComposerContextImport(input: { promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments, + onRestoreQueuedAttachment, } = input; const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); @@ -433,6 +440,19 @@ export function useComposerContextImport(input: { case "image": case "file": { if (skippedDependentAttachmentIds.has(record.contextId)) break; + if (questionAttachmentTarget === null && !conflicts) { + const restored = matchRestorableQueuedAttachment({ + environmentId, + sourceEnvironmentId, + record, + removedQueuedAttachments: removedQueuedAttachments ?? [], + }); + if (restored) { + onRestoreQueuedAttachment?.(restored.attachment); + rewritten.set(record.contextId, restored.contextId); + break; + } + } if (sourceEnvironmentId === null && !conflicts) { rewritten.set(record.contextId, record.contextId); break; diff --git a/apps/web/src/components/chat/useComposerSelection.ts b/apps/web/src/components/chat/useComposerSelection.ts index 77fdd4a459df2..af8c3a3007fb0 100644 --- a/apps/web/src/components/chat/useComposerSelection.ts +++ b/apps/web/src/components/chat/useComposerSelection.ts @@ -25,10 +25,12 @@ import { threadHasStarted, } from "../../lib/chatThreadActions"; import { + composerTargetKey, type DraftThreadEnvMode, isSameModel, useComposerDraftStore, } from "../../composerDraftStore"; +import { cancelHeldComposerSend } from "./preparingComposerImages"; import { getStartedThreadModelChangeBlockReason, deriveLockedProvider, @@ -96,6 +98,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { const handleRuntimeModeChange = (mode: RuntimeMode) => { if (mode === runtimeMode) return; + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); setComposerDraftRuntimeMode(composerDraftTarget, mode); if (isLocalDraftThread) { setDraftThreadContext(composerDraftTarget, { runtimeMode: mode }); @@ -135,6 +138,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { options?: { focusComposer?: boolean }, ) => { if (!activeThread) return; + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId); const resolvedDriverKind = entry?.driver ?? null; if ( @@ -240,6 +244,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { const onProviderModelSelectStable = useStableCallback(onProviderModelSelect); const onEnvModeChange = (mode: DraftThreadEnvMode) => { if (multipleModelSelections !== null) return; + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); if (canOverrideServerThreadEnvMode) { if (activeThread) setPendingServerThreadEnvModeEntry({ threadId: activeThread.id, mode }); scheduleComposerFocus(); @@ -263,6 +268,7 @@ export function useComposerSelection(input: ComposerSelectionInput) { // re-renders the branch toolbar and thread details panel with it. const activeThreadId = activeThread?.id; const onStartFromOriginChange = (nextStartFromOrigin: boolean) => { + cancelHeldComposerSend(composerTargetKey(composerDraftTarget)); if (canOverrideServerThreadEnvMode && activeThreadId !== undefined) { setPendingServerThreadStartFromOriginByThreadId((current) => current[activeThreadId] === nextStartFromOrigin diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index cb43ec689a743..9aec077e0140a 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -73,7 +73,7 @@ import { recordPromptSent } from "../GitHubStarPrompt"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { writeTextToClipboard } from "~/hooks/useCopyToClipboard"; import { newMessageId, newThreadId } from "~/lib/utils"; -import { useNewThreadHandler } from "../../hooks/useHandleNewThread"; +import { readPendingWorkspaceDefault, useNewThreadHandler } from "../../hooks/useHandleNewThread"; import { buildThreadRouteParams } from "../../threadRoutes"; import { beginBackgroundDraftSubmissionByRef, @@ -83,6 +83,7 @@ import { restoreFailedDraftThread, checkoutPullRequestUrlToLink, composerDraftHasUserContent, + composerTargetKey, type ComposerFileAttachment, type ComposerImageAttachment, type DraftThreadEnvMode, @@ -125,6 +126,7 @@ import { startAttachmentUpload, } from "../../lib/attachmentUploadQueue"; import { appAtomRegistry } from "../../rpc/atomRegistry"; +import { countPreparingComposerImages, holdComposerSend } from "./preparingComposerImages"; import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; import { useLinkedEnvironments } from "../../state/peerLinks"; import { readEnvironmentScope } from "../../state/session"; @@ -437,12 +439,13 @@ export function useComposerSend(input: ComposerSendInput) { e?.preventDefault(); // What the user pressed send on; uploads below can take a while, and a redirect must not // decline approvals for a draft that changed meanwhile. - const promptAtSend = detachedOverride ? detachedOverride.prompt : promptRef.current; + let promptAtSend = detachedOverride ? detachedOverride.prompt : promptRef.current; if ( usageLimitsOffered && usageLimitsKey !== null && !directAnnotation && !draftHasNonPromptContent(composerDraftTarget) && + countPreparingComposerImages(composerTargetKey(composerDraftTarget)) === 0 && isUsageLimitsCommand(promptAtSend) ) { if (openUsageLimits()) { @@ -455,9 +458,11 @@ export function useComposerSend(input: ComposerSendInput) { return; } - const sendCtx = detachedOverride + // Read before any wait; the composer on screen may belong to another thread after it. + let sendCtx = detachedOverride ? detachedOverride.sendContext : composerRef.current?.getSendContext(); + const isCurrentRouteThread = () => currentRouteThreadKeyRef.current === routeThreadKey; // `/side` beats an open question and a plan follow-up, which would send the text to main. const sideChatCommand = sendCtx && !directAnnotation && !queuedRunEdit.isEditing @@ -553,6 +558,27 @@ export function useComposerSend(input: ComposerSendInput) { ); return; } + const heldForImages = directAnnotation ? null : holdComposerSend(composerDraftTarget); + if (heldForImages) { + if ((await heldForImages).status === "cancelled") return; + const draftAfterHold = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget); + if (!draftAfterHold) return; + // A dictation sent after leaving the thread carries its transcript outside the draft. + promptAtSend = detachedOverride ? detachedOverride.prompt : draftAfterHold.prompt; + if (sendCtx) { + sendCtx = { + ...sendCtx, + prompt: promptAtSend, + images: draftAfterHold.images, + files: draftAfterHold.files, + terminalContexts: draftAfterHold.terminalContexts, + previewAnnotations: draftAfterHold.previewAnnotations, + reviewComments: draftAfterHold.reviewComments, + threadContexts: draftAfterHold.threadContexts, + environmentContexts: draftAfterHold.environmentContexts, + }; + } + } const startDraftAttachmentUploads = ( attachments: ReadonlyArray, ) => { @@ -1053,7 +1079,6 @@ export function useComposerSend(input: ComposerSendInput) { effort: ctxSelectedPromptEffort, text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, }); - const isCurrentRouteThread = () => currentRouteThreadKeyRef.current === routeThreadKey; if ( isCurrentRouteThread() && composerRef.current?.validateProviderInput(outgoingMessageText) === false @@ -1107,6 +1132,7 @@ export function useComposerSend(input: ComposerSendInput) { if (turnUsesAttachmentUploads) startDraftAttachmentUploads(composerAttachmentsSnapshot); if ( + isCurrentRouteThread() && multipleModelSelections === null && shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) && activeThreadKey @@ -1322,7 +1348,7 @@ export function useComposerSend(input: ComposerSendInput) { } if (sendQueuesBehindSetup) { setSetupQueueSendThreadKey(activeThreadKey); - } else { + } else if (isCurrentRouteThread()) { beginLocalDispatch({ preparingWorktree: multipleModelSelections !== null || Boolean(baseBranchForWorktree), submissionIntent: @@ -1738,13 +1764,12 @@ export function useComposerSend(input: ComposerSendInput) { setDockedDraftHeroThreadKey((currentThreadKey) => currentThreadKey === activeThreadKey ? null : currentThreadKey, ); - if (!sendQueuesBehindSetup) resetLocalDispatch(); + if (!sendQueuesBehindSetup && isCurrentRouteThread()) resetLocalDispatch(); } }; const onSendLatest = useStableCallback(onSend); - const onSendWithRouting = async (...args: Parameters) => { - args[0]?.preventDefault(); + const sendWithEnvironmentRefresh = async (...args: Parameters) => { const refresh = args[3] || sendInFlightRef.current || readPendingEnvironmentChange() !== null ? null @@ -1756,6 +1781,18 @@ export function useComposerSend(input: ComposerSendInput) { }); if (ready) return onSendLatest(...args); }; + const sendWithEnvironmentRefreshLatest = useStableCallback(sendWithEnvironmentRefresh); + const onSendWithRouting = async (...args: Parameters) => { + args[0]?.preventDefault(); + const workspaceDefault = + draftId && !sendInFlightRef.current ? readPendingWorkspaceDefault(draftId) : null; + if (workspaceDefault === null) return sendWithEnvironmentRefresh(...args); + sendInFlightRef.current = true; + await workspaceDefault.finally(() => { + sendInFlightRef.current = false; + }); + return sendWithEnvironmentRefreshLatest(...args); + }; // No load-balancing refresh: it bails once the draft is no longer displayed, which is the // only time a detached send runs, so the draft keeps the environment it was dictated for. const captureDetachedSend = useStableCallback(() => onSend); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index a88da51cce16e..5ad406da5ef91 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -2,6 +2,7 @@ import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { EnvironmentId, ChatAttachmentId, + ComposerContextId, MessageId, RunId, ThreadId, @@ -363,22 +364,83 @@ describe("useQueuedRunEdit", () => { expect(draft?.environmentContexts).toEqual([machine]); }); - it("saves only the thread mentions still in the edited message", async () => { + it("saves only the thread mentions and attachments 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 removedImageId = ChatAttachmentId.make("server-image-removed"); + const keptFileId = ChatAttachmentId.make("server-file-kept"); + const removedImageContextId = ComposerContextId.make("image_local-removed"); + const keptFileContextId = ComposerContextId.make("file_local-kept"); + const removedImage = { + type: "image" as const, + id: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFile = { + type: "file" as const, + id: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; + const removedImageRecord = { + version: 1 as const, + kind: "image" as const, + contextId: removedImageContextId, + label: "image.png", + attachmentId: removedImageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + }; + const keptFileRecord = { + version: 1 as const, + kind: "file" as const, + contextId: keptFileContextId, + label: "legacy.pdf", + attachmentId: keptFileId, + name: "legacy.pdf", + mimeType: "application/pdf", + sizeBytes: 40, + }; 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] } }]; + const text = [ + formatInlineContextReference(threadContextReference(kept)), + formatInlineContextReference(threadContextReference(removed)), + formatInlineContextReference({ + kind: "image", + contextId: removedImageContextId, + label: "image.png", + }), + ].join(" and "); + const messages = [ + { + id: messageId, + text, + context: { version: 1, records: [kept, removed, removedImageRecord, keptFileRecord] }, + }, + ]; await using _screen = await render(view(THREAD_A, "queued", hook, messages)); - await act(() => requireHook(hook).beginEdit({ runId: RUN, messageId, text, attachments: [] })); + await act(() => + requireHook(hook).beginEdit({ + runId: RUN, + messageId, + text, + attachments: [removedImage, keptFile], + }), + ); const target = requireHook(hook).draftTarget; - await act(() => useComposerDraftStore.getState().setThreadContexts(target, [kept])); + await act(() => { + useComposerDraftStore.getState().setThreadContexts(target, [kept]); + requireHook(hook).removeEditingAttachment(removedImageId); + }); const draft = useComposerDraftStore.getState().getComposerDraft(target); + expect(draft?.prompt).not.toContain(removedImageContextId); await requireHook(hook).saveEdit( { ...savedContent(draft?.prompt ?? ""), threadContexts: draft?.threadContexts ?? [] }, () => {}, @@ -387,7 +449,11 @@ describe("useQueuedRunEdit", () => { expect(mocks.editQueuedRun).toHaveBeenCalledWith( expect.objectContaining({ input: expect.objectContaining({ - edit: expect.objectContaining({ context: { version: 1, records: [kept] } }), + text: draft?.prompt, + edit: expect.objectContaining({ + attachments: [keptFile], + context: { version: 1, records: [keptFileRecord, kept] }, + }), }), }), ); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index 61907b93cfb22..a33fd9177635c 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -69,6 +69,7 @@ import type { ChatComposerHandle } from "./ChatComposer"; import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles"; import { composerDraftContentChanged } from "./composerSend.logic"; import { + attachmentContextIdsForRecord, discardQueuedEditDraft, prepareQueuedEditAttachments, recoverQueuedMessageEdit, @@ -80,10 +81,9 @@ interface EditingQueuedRun { readonly runId: RunId; readonly messageId: MessageId; readonly originalText: string; + readonly originalAttachments: ReadonlyArray; readonly existingAttachments: ReadonlyArray; readonly context?: OrchestrationMessageContext | undefined; - /** Removing a server attachment changes the message even when the draft looks untouched. */ - readonly removedExistingAttachment?: true; } // Keyed by the route thread, so an edit survives navigating away and back. @@ -238,13 +238,34 @@ export function useQueuedRunEdit(input: { const urlByAttachmentId = new Map( imageResources.map((resource, index) => [resource.attachmentId, imageUrls[index] ?? null]), ); + const originalReferencedContextIds = + editing === null ? null : new Set(collectInlineContextIds(editing.originalText)); + const attachmentContextIds = (attachment: ChatAttachment) => + editing === null + ? [] + : attachmentContextIdsForRecord(editing.context, attachment).filter((contextId) => + originalReferencedContextIds!.has(contextId), + ); const editingAttachments = editing === null ? null : editing.existingAttachments.map((attachment) => ({ attachment, url: urlByAttachmentId.get(attachment.id) ?? null, + contextIds: attachmentContextIds(attachment), })); + const existingAttachmentIds = new Set( + (editing?.existingAttachments ?? []).map((attachment) => attachment.id), + ); + const removedEditingAttachments = + editing === null + ? [] + : editing.originalAttachments + .filter((attachment) => !existingAttachmentIds.has(attachment.id)) + .map((attachment) => ({ + attachment, + contextIds: attachmentContextIds(attachment), + })); const focusComposerSoon = () => { window.requestAnimationFrame(() => composerRef.current?.focusAtEnd()); @@ -290,6 +311,7 @@ export function useQueuedRunEdit(input: { runId: request.runId, messageId: request.messageId, originalText: text, + originalAttachments: request.attachments, existingAttachments: request.attachments, context, }, @@ -312,7 +334,14 @@ export function useQueuedRunEdit(input: { editTarget: queuedRunEditDraftId(routeThreadRef, edit.runId), threadTarget: threadDraftTarget, originalText: edit.originalText, - removedExistingAttachment: edit.removedExistingAttachment === true, + originalReplyTo: reply ?? null, + removedExistingAttachment: + edit.existingAttachments.length < edit.originalAttachments.length, + existingAttachmentContextIds: (edit.context?.records ?? []).flatMap((record) => + (record.kind === "image" || record.kind === "file") && "attachmentId" in record + ? [record.contextId] + : [], + ), }); if (recovery === "clean") return; const title = appAtomRegistry.get( @@ -344,13 +373,39 @@ export function useQueuedRunEdit(input: { focusComposerSoon(); }); const removeEditingAttachment = useStableCallback((attachmentId: string) => { + const removed = editing?.existingAttachments.find( + (attachment) => attachment.id === attachmentId, + ); + const contextIds = removed ? attachmentContextIdsForRecord(editing?.context, removed) : []; queuedRunEdits.update(editKey, (current) => ({ ...current, - removedExistingAttachment: true, existingAttachments: current.existingAttachments.filter( (attachment) => attachment.id !== attachmentId, ), })); + if (editing !== null && contextIds.length > 0) { + const target = queuedRunEditDraftId(routeThreadRef, editing.runId); + const store = useComposerDraftStore.getState(); + const currentPrompt = store.getComposerDraft(target)?.prompt ?? ""; + const nextPrompt = contextIds.reduce( + (prompt, contextId) => removeInlineContextReference(prompt, contextId).prompt, + currentPrompt, + ); + if (nextPrompt !== currentPrompt) store.setPrompt(target, nextPrompt); + } + }); + const restoreEditingAttachment = useStableCallback((attachment: ChatAttachment) => { + queuedRunEdits.update(editKey, (current) => { + const keptIds = new Set([ + ...current.existingAttachments.map((entry) => entry.id), + attachment.id, + ]); + // Filtering the originals keeps the restored attachment in its original position. + return { + ...current, + existingAttachments: current.originalAttachments.filter((entry) => keptIds.has(entry.id)), + }; + }); }); // The same move as the queued row's "Send now" while a turn runs. @@ -477,9 +532,11 @@ export function useQueuedRunEdit(input: { isSaving, draftTarget, editingAttachments, + removedEditingAttachments, beginEdit, cancelEdit, removeEditingAttachment, + restoreEditingAttachment, saveEdit, }; } diff --git a/apps/web/src/components/composerContextPresentation.test.ts b/apps/web/src/components/composerContextPresentation.test.ts index 77b0a5fb7815e..641e190ef86a3 100644 --- a/apps/web/src/components/composerContextPresentation.test.ts +++ b/apps/web/src/components/composerContextPresentation.test.ts @@ -1,8 +1,16 @@ -import { ThreadId } from "@t3tools/contracts"; +import { ChatAttachmentId, ComposerContextId, EnvironmentId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { buildMessageContext } from "~/lib/composerContextRecords"; -import { composerContextRecordsFromDraft } from "./composerContextPresentation"; +import { composerFileNeedsReattach } from "~/composerDraftStore"; +import { + attachmentContextRecord, + buildMessageContext, + isSameComposerContextPayload, +} from "~/lib/composerContextRecords"; +import { + composerContextRecordsFromDraft, + uploadedContextRecordFromDraft, +} from "./composerContextPresentation"; describe("composerContextRecordsFromDraft", () => { it("resolves each wire reference to its own backing draft even when producer ids collide", () => { @@ -53,4 +61,88 @@ describe("composerContextRecordsFromDraft", () => { expect(draftRecords.get(record.contextId)?.kind).toBe(record.kind); } }); + + it("resolves existing queued attachments under their original wire context ids", () => { + const environmentId = EnvironmentId.make("env-1"); + const imageContextId = ComposerContextId.make("image_local-shot"); + const fileContextId = ComposerContextId.make("file_local-notes"); + const imageId = ChatAttachmentId.make("server-shot"); + const fileId = ChatAttachmentId.make("server-notes"); + const source = { + kind: "snap-shot" as const, + capturedAt: "2026-11-22T14:00:00.000Z", + appName: "Safari", + windowTitle: "Example", + }; + const imageAttachment = { + type: "image" as const, + id: imageId, + name: "image.png", + mimeType: "image/png", + sizeBytes: 67, + source, + }; + const draftRecords = composerContextRecordsFromDraft({ + terminalContexts: [], + environmentId, + existingAttachments: [ + { + attachment: imageAttachment, + url: "http://127.0.0.1/assets/server-shot", + contextIds: [imageContextId], + }, + { + attachment: { + type: "file", + id: fileId, + name: "notes.txt", + mimeType: "text/plain", + sizeBytes: 12, + }, + url: null, + contextIds: [fileContextId], + }, + ], + }); + + const imageEntry = draftRecords.get(imageContextId); + expect(imageEntry).toMatchObject({ + kind: "image", + record: { + id: imageId, + name: "image.png", + previewUrl: "http://127.0.0.1/assets/server-shot", + source, + }, + }); + const uploadedImageRecord = uploadedContextRecordFromDraft(imageEntry!); + expect(uploadedImageRecord).toMatchObject({ + kind: "image", + contextId: imageContextId, + attachmentId: imageId, + source, + }); + expect( + isSameComposerContextPayload( + uploadedImageRecord!, + attachmentContextRecord({ + attachment: imageAttachment, + attachmentId: imageId, + contextId: imageContextId, + }), + ), + ).toBe(true); + + const fileEntry = draftRecords.get(fileContextId); + expect(fileEntry?.kind).toBe("file"); + if (fileEntry?.kind === "file") { + expect(composerFileNeedsReattach(fileEntry.record)).toBe(false); + expect(fileEntry.record.uploadEnvironmentId).toBe(environmentId); + } + expect(uploadedContextRecordFromDraft(fileEntry!)).toMatchObject({ + kind: "file", + contextId: fileContextId, + attachmentId: fileId, + }); + }); }); diff --git a/apps/web/src/components/composerContextPresentation.tsx b/apps/web/src/components/composerContextPresentation.tsx index d6ff0c7fee415..4c629e002068d 100644 --- a/apps/web/src/components/composerContextPresentation.tsx +++ b/apps/web/src/components/composerContextPresentation.tsx @@ -1,9 +1,12 @@ import ChatMarkdown from "./ChatMarkdown"; import { isSvgAttachment } from "@t3tools/shared/image"; -import { CHAT_USER_MARKDOWN_REMARK_PLUGINS } from "@t3tools/shared/markdownPipeline"; +import { USER_TEXT_MARKDOWN } from "../fork/forkMarkdown"; import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview"; import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, + EnvironmentId, PreviewAnnotationPayload, ThreadContextRecord, } from "@t3tools/contracts"; @@ -41,6 +44,7 @@ import { } from "~/lib/composerContextRecords"; import type { TerminalContextDraft } from "~/lib/terminalContext"; import type { ReviewCommentContext } from "~/reviewCommentContext"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./chat/queuedMessageEdit"; import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts"; import { EnvironmentContextChip } from "./EnvironmentContextChip"; import { ThreadContextChip } from "./ThreadContextChip"; @@ -61,6 +65,11 @@ import { UnresolvedChip, } from "./contextChipParts"; +export interface ComposerImageContextAttachment extends Omit { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; +} + export type ComposerDraftContextRecord = | { kind: "terminal"; record: TerminalContextDraft } | { kind: "review-comment"; record: ReviewCommentContext } @@ -69,8 +78,18 @@ export type ComposerDraftContextRecord = record: PreviewAnnotationPayload; screenshot?: ComposerImageAttachment | undefined; } - | { kind: "image"; record: ComposerImageAttachment; upload?: AttachmentUploadState | undefined } - | { kind: "file"; record: ComposerFileAttachment; upload?: AttachmentUploadState | undefined } + | { + kind: "image"; + record: ComposerImageContextAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } + | { + kind: "file"; + record: ComposerFileAttachment; + upload?: AttachmentUploadState | undefined; + contextId?: ComposerContextId | undefined; + } | { kind: "thread"; record: ThreadContextRecord } | { kind: "environment"; record: EnvironmentContextRecord }; @@ -85,7 +104,7 @@ export const EMPTY_COMPOSER_CONTEXT_RECORDS: ComposerDraftContextRecords = new M export function uploadedContextRecordFromDraft(entry: ComposerDraftContextRecord) { if (entry.kind !== "image" && entry.kind !== "file") return null; - return uploadedAttachmentContextRecord(entry.record, entry.upload); + return uploadedAttachmentContextRecord(entry.record, entry.upload, entry.contextId); } export const ComposerContextRecordsContext = createContext( @@ -100,9 +119,44 @@ export function composerContextRecordsFromDraft(input: { environmentContexts?: ReadonlyArray; images?: ReadonlyArray; files?: ReadonlyArray; + existingAttachments?: + | ReadonlyArray<{ + readonly attachment: ChatAttachment; + readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; + }> + | undefined; + environmentId?: EnvironmentId | undefined; uploadsByImageId?: Readonly>; }): ComposerDraftContextRecords { const records = new Map(); + for (const entry of input.existingAttachments ?? []) { + for (const contextId of entry.contextIds ?? []) { + if (isQueuedImageAttachment(entry.attachment)) { + records.set(contextId, { + kind: "image", + contextId, + record: { + ...entry.attachment, + previewUrl: entry.url ?? "", + file: null, + uploadedAttachmentId: entry.attachment.id, + }, + }); + } else if (isQueuedFileAttachment(entry.attachment)) { + records.set(contextId, { + kind: "file", + contextId, + record: { + ...entry.attachment, + file: null, + uploadedAttachmentId: entry.attachment.id, + ...(input.environmentId ? { uploadEnvironmentId: input.environmentId } : {}), + }, + }); + } + } + } for (const record of input.images ?? []) { records.set(imageContextReference(record).contextId, { kind: "image", @@ -184,7 +238,7 @@ function useUploadStatusSuffix( } function attachmentTooltip( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: Pick, upload: AttachmentUploadState | undefined, resolve: MessageResolver, ): string { @@ -194,7 +248,7 @@ function attachmentTooltip( } function ImageContextChip(props: { - record: ComposerImageAttachment; + record: ComposerImageContextAttachment; upload: AttachmentUploadState | undefined; }) { const actions = use(ComposerContextActionsContext); @@ -377,7 +431,7 @@ function ComposerReviewCommentDetails({ comment }: { comment: ReviewCommentConte text={comment.text.trim()} cwd={undefined} // Fork: "1~2" keeps its tilde before sending, as in the user's message. - extraRemarkPlugins={CHAT_USER_MARKDOWN_REMARK_PLUGINS} + extensions={USER_TEXT_MARKDOWN} /> ) : null} {comment.diff.trim() ? ( diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index 2322ef9ec14be..7cadea82ba2a9 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -582,8 +582,14 @@ describe("large text preview recovery", () => { environmentId={EnvironmentId.make("test")} threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }} absolutePath="/repo/large.txt" + draftCwd={null} name="large.txt" delimiter={null} + markdownCwd={null} + copyContents={{ current: null }} + preview="" + // Past the highlighted-source cap, so the worker-backed viewer under test renders. + sizeBytes={128 * 1024 * 1024} workspaceMutationId={mutation} revealLine={null} revealRequestId={0} @@ -1963,7 +1969,9 @@ it("mounts a bounded set of saved notebook outputs as the reader scrolls", async ); expect(screen.container.querySelectorAll("iframe").length).toBeLessThanOrEqual(16); const first = screen.container.querySelector("iframe")!; + const firstOutput = first.parentElement!; expect(first.srcdoc).toContain("saved 0-0"); + await vi.waitFor(() => expect(first.clientHeight).toBeGreaterThan(0)); const viewport = screen.container.querySelector(".scrollbar-gutter-both")!; await act(() => { viewport.scrollTop = viewport.scrollHeight; @@ -1977,12 +1985,27 @@ it("mounts a bounded set of saved notebook outputs as the reader scrolls", async expect(first.isConnected).toBe(false); }); expect(screen.container.querySelectorAll("iframe").length).toBeLessThanOrEqual(16); + const reservedHeight = firstOutput.getBoundingClientRect().height; + using cleanup = new DisposableStack(); + const pending = new AbortController(); + cleanup.defer(() => pending.abort()); + // Hold the remounted frame in its loading state until it scrolls away again. + firstOutput.addEventListener("load", (event) => event.stopPropagation(), { + capture: true, + signal: pending.signal, + }); await act(() => { viewport.scrollTop = 0; }); - await vi.waitFor(() => - expect(screen.container.querySelector("iframe")?.srcdoc).toContain("saved 0-0"), - ); + await vi.waitFor(() => { + expect(firstOutput.querySelector("iframe")?.srcdoc).toContain("saved 0-0"); + expect(firstOutput.getBoundingClientRect().height).toBe(reservedHeight); + }); + await act(() => { + viewport.scrollTop = viewport.scrollHeight; + }); + await vi.waitFor(() => expect(firstOutput.querySelector("iframe")).toBeNull()); + expect(firstOutput.getBoundingClientRect().height).toBe(reservedHeight); }); it.each([ diff --git a/apps/web/src/components/files/ChunkedMarkdown.tsx b/apps/web/src/components/files/ChunkedMarkdown.tsx new file mode 100644 index 0000000000000..2564e40389c96 --- /dev/null +++ b/apps/web/src/components/files/ChunkedMarkdown.tsx @@ -0,0 +1,106 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { LegendList } from "@legendapp/list/react"; +import type { KeyboardEventHandler } from "react"; + +import { Spinner } from "~/components/ui/spinner"; +import { FileMarkdownPreview } from "./FileMarkdownPreview"; +import { + LARGE_MARKDOWN_CHUNK_MAX_CHARS, + type MarkdownChunk, + withMarkdownDefinitions, +} from "@t3tools/shared/markdownChunks"; + +const ESTIMATED_LINE_PX = 24; + +interface ChunkItem { + readonly index: number; + readonly start: number; + readonly chunk: MarkdownChunk; +} + +/** Renders Markdown pieces in a virtualized list; task offsets are file offsets. */ +export function ChunkedMarkdown(props: { + readonly chunks: readonly MarkdownChunk[]; + /** Link definitions from the whole file, so references resolve across pieces. */ + readonly definitions: string; + /** Shows a spinner after the last chunk while more of the file streams in. */ + readonly loading?: boolean; + readonly cwd: string; + readonly relativePath: string; + readonly threadRef: ScopedThreadRef; + readonly workspaceMutationId: string | null; + readonly onKeyDown?: KeyboardEventHandler; + readonly onTaskListChange?: + | ((input: { readonly markerOffset: number; readonly checked: boolean }) => void) + | undefined; +}) { + const { chunks, onTaskListChange } = props; + const items: ChunkItem[] = []; + let start = 0; + let lines = 0; + for (const [index, chunk] of chunks.entries()) { + items.push({ index, start, chunk }); + lines += chunk.lines; + start += chunk.text.length + 1; + } + return ( +
{ + // Select All only reaches rendered pieces; copying all of it copies the whole file. + const list = event.currentTarget.firstElementChild; + if (!list || !window.getSelection()?.containsNode(list)) return; + event.preventDefault(); + event.clipboardData.setData("text/plain", chunks.map((chunk) => chunk.text).join("\n")); + }} + > + + data={items} + extraData={props.definitions} + keyExtractor={(item) => String(item.index)} + estimatedItemSize={(lines / Math.max(items.length, 1)) * ESTIMATED_LINE_PX} + drawDistance={800} + recycleItems={false} + className="h-full scrollbar-gutter-both" + contentContainerClassName="py-5" + ListFooterComponent={ + props.loading ? ( +
+ +
+ ) : null + } + renderItem={({ item }) => ( +
+ {item.chunk.text.length > LARGE_MARKDOWN_CHUNK_MAX_CHARS ? ( + // One block this long (a huge fence or HTML block) is too slow to parse. +
+                {item.chunk.text}
+              
+ ) : ( + + onTaskListChange({ + markerOffset: item.start + input.markerOffset, + checked: input.checked, + })) + } + /> + )} +
+ )} + /> +
+ ); +} diff --git a/apps/web/src/components/files/DocumentPages.tsx b/apps/web/src/components/files/DocumentPages.tsx index 2e19f0dbf65cc..4fa5a70f0a0e9 100644 --- a/apps/web/src/components/files/DocumentPages.tsx +++ b/apps/web/src/components/files/DocumentPages.tsx @@ -75,6 +75,7 @@ export default function DocumentPages(props: { readonly html: string; readonly name: string; readonly output?: boolean; + readonly estimatedOutputHeight?: number; readonly details?: string; }) { const gt = useGT(); @@ -88,7 +89,7 @@ export default function DocumentPages(props: { // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Theme values invalidate the palette read from the host DOM. }, [theme, resolvedTheme, themeHalves]); const [zoom, setZoom] = useState(1); - const [outputHeight, setOutputHeight] = useState(0); + const [outputHeight, setOutputHeight] = useState(); const stopObserving = useRef<(() => void) | null>(null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Disconnect the iframe body's resize observer when the document unmounts. useEffect(() => () => stopObserving.current?.(), []); @@ -135,11 +136,16 @@ export default function DocumentPages(props: { stopObserving.current?.(); const body = event.currentTarget.contentDocument?.body; if (!body) return; - const measure = () => setOutputHeight(Math.ceil(body.getBoundingClientRect().height)); + const measure = () => { + const height = Math.ceil(body.getBoundingClientRect().height); + if (height > 0) setOutputHeight(height); + }; stopObserving.current = observeResize(body, measure); measure(); }} - style={props.output ? { height: outputHeight } : undefined} + style={ + props.output ? { height: outputHeight ?? props.estimatedOutputHeight ?? 0 } : undefined + } className={props.output ? "block w-full border-0" : "min-h-0 flex-1 border-0"} /> diff --git a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx index 8d069fc766d38..1924cbb941cf9 100644 --- a/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.browser.test.tsx @@ -162,6 +162,10 @@ describe("FileBrowserPanel", () => { row.click(); await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(1)); + + // The selection stays put, so reopening the selected file must not depend on a selection change. + row.click(); + await vi.waitFor(() => expect(onOpenFile).toHaveBeenCalledTimes(2)); }); it("keeps an expanded folder open when a very large listing rebuilds the tree", async () => { diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 64e1f87765427..f3303cc6e8603 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -663,6 +663,32 @@ export default function FileBrowserPanel({ model={model} aria-label={gt("{projectName} files", { projectName })} className="min-h-0 flex-1 overflow-hidden" + onClickCapture={(event) => { + if ( + event.defaultPrevented || + event.button !== 0 || + event.ctrlKey || + event.metaKey || + event.shiftKey || + event.altKey || + dragMention.isDragInProgress() + ) { + return; + } + // Pierre emits no change for its sole selected row; read before the click to avoid double opens. + const selected = model.getSelectedPaths(); + const path = selected.length === 1 ? selected[0] : undefined; + if (!path || entryKindsRef.current.get(path) !== "file") return; + const clickedSelectedRow = event.nativeEvent + .composedPath() + .some( + (node) => + node instanceof HTMLElement && node.getAttribute("data-item-path") === path, + ); + if (!clickedSelectedRow) return; + treeSelectionPathRef.current = path; + onOpenFile(panelPath(path)); + }} style={pierreTreeStyle(resolvedTheme)} onPointerOver={titleClippedPierreTreeRow} /> diff --git a/apps/web/src/components/files/FileMarkdownPreview.tsx b/apps/web/src/components/files/FileMarkdownPreview.tsx index 19df3f6687058..a4b4957201792 100644 --- a/apps/web/src/components/files/FileMarkdownPreview.tsx +++ b/apps/web/src/components/files/FileMarkdownPreview.tsx @@ -10,6 +10,7 @@ export function FileMarkdownPreview(props: { readonly text: string; readonly threadRef: ScopedThreadRef; readonly workspaceMutationId: string | null; + readonly className?: string; readonly onTaskListChange?: | ((input: { readonly markerOffset: number; readonly checked: boolean }) => void) | undefined; @@ -30,7 +31,7 @@ export function FileMarkdownPreview(props: { imageBaseDir={imageBaseDir} threadRef={props.threadRef} workspaceMutationId={props.workspaceMutationId} - className="mx-auto max-w-4xl px-6 py-5" + className={props.className ?? "mx-auto max-w-4xl px-6 py-5"} onTaskListChange={props.onTaskListChange} /> ); diff --git a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx index c40d1c5a5eeb5..69dd6f9d36c44 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -564,17 +564,28 @@ describe("source file scroll", () => { }); describe("rendered Markdown task saves", () => { - it("keeps a truncated read read-only without queuing a replacement", async () => { + it("renders the whole file of a truncated read, read-only", async () => { using _settings = setup(); + state.assetUrl = { + _tag: "Success", + url: "/assets/tasks.md", + expiresAt: Number.MAX_SAFE_INTEGER, + }; + const realFetch = globalThis.fetch; + using _fetch = vi + .spyOn(globalThis, "fetch") + .mockImplementation((input, init) => + new URL(String(input), location.href).pathname === "/assets/tasks.md" + ? Promise.resolve( + new Response("- [ ] Keep the rest of this file\n\nPast the first megabyte\n"), + ) + : realFetch(input, init), + ); await using screen = await render(markdownPreview(true)); - using _timers = fakeTimers(); + await expect.element(screen.getByText("Past the first megabyte")).toBeVisible(); const checkbox = screen.container.querySelector('input[type="checkbox"]')!; - expect(checkbox).not.toBeNull(); expect(checkbox.disabled).toBe(true); - expect(checkbox.readOnly).toBe(true); await act(async () => checkbox.click()); - await vi.advanceTimersByTimeAsync(500); - expect(checkbox.checked).toBe(false); expect(state.optimistic).toBeNull(); expect(state.writeFile).not.toHaveBeenCalled(); }); @@ -582,6 +593,8 @@ describe("rendered Markdown task saves", () => { it("still toggles and saves tasks from a complete read", async () => { using _settings = setup(); await using screen = await render(markdownPreview(false)); + // The virtualized list mounts its pieces after measuring the viewport. + await expect.element(screen.getByRole("checkbox")).toBeInTheDocument(); using _timers = fakeTimers(); const checkbox = screen.container.querySelector('input[type="checkbox"]')!; expect(checkbox).not.toBeNull(); diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 4b736d8b6622e..c2b6aa0b306d7 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -158,6 +158,11 @@ describe("document preview contents", () => { "A\tB\u2003C\u2002D\u2005E\u200dF\u200cG\u200bH\u200eI\u200fJ", ], ["a Unicode fallback", String.raw`{\rtf1 Jean\u8209\_Luc}`, "Jean\u2011Luc"], + [ + "visible text around hidden character formatting", + String.raw`{\rtf1 A{\v hidden{\v0 B}hidden}C\v hidden\v0 D\v hidden\plain E}`, + "ABCDE", + ], ["a tracked replacement", String.raw`{\rtf1 aaa{\deleted bbb}{\revised BBB}ccc}`, "aaaBBBccc"], [ "text after a deletion reset", @@ -232,6 +237,9 @@ Third}`; expect(html(textEdit.replaceAll("\n", "\r\n"))).toEqual(expected); const lineBreak = html(String.raw`{\rtf1\ansi First line\line Second line}`); expect(lineBreak).toEqual(["

First line
Second line

"]); + expect(html(String.raw`{\rtf1\ansi{\v\line\line\line}First line\line Second line}`)).toEqual( + lineBreak, + ); expect(html(String.raw`{\rtf1\ansi First line\uc0\u8232 Second line}`)).toEqual(lineBreak); expect(html(String.raw`{\rtf1\ansi First line\u8232?Second line{\deleted\u8232?}}`)).toEqual( lineBreak, diff --git a/apps/web/src/components/files/FilePreviewPanel.tsx b/apps/web/src/components/files/FilePreviewPanel.tsx index 014bb1d3accac..97f1a710bf4dc 100644 --- a/apps/web/src/components/files/FilePreviewPanel.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.tsx @@ -26,9 +26,7 @@ import { import { useAtomMount, useAtomValue } from "@effect/atom-react"; import { Atom } from "effect/reactivity"; import { - DEFAULT_TOKENIZE_MAX_LENGTH, VirtualizedFile, - getFiletypeFromFileName, type File as FileInstance, type FileContents, type PostRenderPhase, @@ -40,9 +38,9 @@ import { type EditorFactory, type EditorOptions, } from "@pierre/diffs/edit"; -import type { WorkerPoolManager } from "@pierre/diffs/worker"; -import { EditProvider, File, Virtualizer, useWorkerPool } from "@pierre/diffs/react"; +import { EditProvider, File, Virtualizer } from "@pierre/diffs/react"; import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; +import { useEditableAfterHighlight } from "./useEditableAfterHighlight"; import { useFilesystemReadAccess } from "~/state/filesystem"; import { isAtomCommandInterrupted, @@ -58,7 +56,9 @@ import { useEffectEvent, useRef, useState, + type ComponentProps, type KeyboardEvent as ReactKeyboardEvent, + type RefObject, } from "react"; import { isBrowserPreviewFile, openFileInPreview } from "~/browser/openFileInPreview"; @@ -101,7 +101,8 @@ import FileBrowserPanel from "./FileBrowserPanel"; import { FileExplorerPane } from "./FileExplorerPane"; import { FileBreadcrumbs } from "./FileBreadcrumbs"; import { breadcrumbPathOf, retainedBreadcrumbTrail, trailChildOf } from "./filePath"; -import { FileMarkdownPreview } from "./FileMarkdownPreview"; +import { ChunkedMarkdown } from "./ChunkedMarkdown"; +import { splitMarkdown } from "@t3tools/shared/markdownChunks"; import { type FileCommentAnnotationEntry, type FileCommentAnnotationGroup, @@ -125,6 +126,8 @@ import SourceFilePreview from "./ReadOnlySourcePreview"; import { pathReadingKey, useFileReadingPosition } from "./fileReadingPosition"; import type { FileSurface } from "../../fork/workArea/workArea.logic"; import { inChatOrigin, useChatFileOpener } from "../../fork/workArea/chatFileOpener"; +import LargeFilePreview from "./LargeFilePreview"; +import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; import { resolveCenteredFileLineScrollTop } from "./fileLineReveal"; import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; import { projectFileCacheKey } from "./fileContentRevision"; @@ -135,7 +138,7 @@ import { shouldShowFileExplorer, workspaceAssetResource, } from "./filePreviewMode"; -import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskList"; +import { setMarkdownTaskChecked } from "@t3tools/shared/markdownTaskEdits"; import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions"; import { revisionedQuery } from "~/state/revisionedQuery"; import { @@ -862,43 +865,6 @@ function editableFileContents( }; } -function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) { - if (workerPool?.isWorkingPool() !== true) return false; - if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false; - let lines = 1; - for ( - let index = file.contents.indexOf("\n"); - index !== -1; - index = file.contents.indexOf("\n", index + 1) - ) { - lines += 1; - } - return lines <= DEFAULT_TOKENIZE_MAX_LENGTH; -} - -/** Enable editing only after worker highlighting renders; active edit sessions highlight on the main - * thread. */ -function useEditableAfterHighlight(file: FileContents) { - const workerPool = useWorkerPool(); - const [highlightedFile, setHighlightedFile] = useState(null); - const needsHighlight = needsWorkerHighlight(workerPool, file); - const ready = !needsHighlight || highlightedFile === file; - - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- primes the worker pool's highlight cache for this file and falls back to plain text if it fails - useEffect(() => { - if (ready || workerPool === undefined) return; - workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file)); - }, [file, ready, workerPool]); - - const onPostRender = (renderedFile: FileContents | undefined, phase: PostRenderPhase) => { - if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return; - // Cache results arrive just before instance rendering; seeing the cache during render means rows are - // highlighted. - if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file); - }; - return { ready, onPostRender }; -} - interface EditableFileSurfaceProps { environmentId: EnvironmentId; projectId?: ProjectId | undefined; @@ -1239,30 +1205,27 @@ function RenderedMarkdownSurface({ }) { const saveTarget = { environmentId, cwd, relativePath }; useFileSaveSession(saveTarget, onPendingChange); + const onTaskListChange = readOnly + ? undefined + : ({ markerOffset, checked }: { readonly markerOffset: number; readonly checked: boolean }) => { + const currentContents = + getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ?? contents; + const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked); + if (nextContents === currentContents) return; + setProjectFileQueryData(environmentId, cwd, relativePath, nextContents); + changeFileSaveSession(saveTarget, nextContents); + }; return ( - - { - const currentContents = - getOptimisticProjectFileQueryData(environmentId, cwd, relativePath)?.contents ?? - contents; - const nextContents = setMarkdownTaskChecked(currentContents, markerOffset, checked); - if (nextContents === currentContents) return; - setProjectFileQueryData(environmentId, cwd, relativePath, nextContents); - changeFileSaveSession(saveTarget, nextContents); - } - } - /> - + ); } @@ -1432,7 +1395,8 @@ export default function FilePreviewPanel({ revealLine === null || reading.renderedAllowed || (handledReveal?.path === relativePath && handledReveal.requestId === reading.revealKey); - const renderMarkdown = isMarkdown && renderMarkdownPreferred && revealHandled; + const markdownRenderable = isMarkdown && (file.data?.byteLength ?? 0) <= FULL_TEXT_MAX_BYTES; + const renderMarkdown = markdownRenderable && renderMarkdownPreferred && revealHandled; const renderMermaid = isMermaid && renderMermaidPreferred && revealHandled; const renderBrowserFile = isPdf || (isHtml && renderBrowserFilePreferred && revealHandled); const renderTable = tableDelimiter !== null && renderTablePreferred && revealHandled; @@ -1446,7 +1410,10 @@ export default function FilePreviewPanel({ ? ("html" as const) : null; const canToggleRendered = - previewPath !== null && attachment === undefined && renderedMode !== null; + previewPath !== null && + attachment === undefined && + renderedMode !== null && + (!isMarkdown || markdownRenderable); const showsRawText = previewPath !== null && file.data !== null && @@ -1477,6 +1444,15 @@ export default function FilePreviewPanel({ file.data.contents.length > 0 ? file.data.contents : null; + const showsLargeText = + previewPath !== null && + attachment === undefined && + !isMedia && + !renderBrowserFile && + !isDocument && + !renderMermaid && + file.data?.truncated === true; + const copyLargeText = useRef<(() => Promise) | null>(null); const { copyToClipboard, isCopied } = useCopyToClipboard({ target: namedClipboardTarget(previewPath ?? ""), onError: (error) => @@ -1730,6 +1706,16 @@ export default function FilePreviewPanel({ {isCopied ? : } ) : null} + {showsLargeText && absolutePath && relativePath ? ( + + ) : null} {canOpenInBrowser ? ( {gt( "{count, plural, one {Preview limited to the first 1 MB of a {formatted} byte file.} other {Preview limited to the first 1 MB of a {formatted} byte file.}}", @@ -1842,21 +1828,20 @@ export default function FilePreviewPanel({ title={relativePath} workspaceMutationId={workspaceMutationId} /> - ) : relativePath && - absolutePath && - file.data?.truncated && - !isDocument && - !draft && - !isMarkdown && - !isMermaid && - !isHtml ? ( + ) : relativePath && absolutePath && showsLargeText ? ( import("./LargeTextViewer")); +// A draft has no thread yet, so its download is scoped to the draft's workspace instead. +function largeFileResource( + threadRef: ScopedThreadRef, + absolutePath: string, + draftCwd: string | null, +): AssetResource { + return draftCwd === null + ? { + _tag: "media-file", + threadId: threadRef.threadId, + path: absolutePath, + disposition: "attachment", + } + : { + _tag: "draft-workspace-file", + cwd: draftCwd, + path: absolutePath, + disposition: "attachment", + }; +} + +/** Copy and save for a file past the 1 MB preview, which the panel holds only in its viewer. */ +function LargeFileActions(props: { + environmentId: EnvironmentId; + threadRef: ScopedThreadRef; + absolutePath: string; + draftCwd: string | null; + name: string; + copyContents: RefObject<(() => Promise) | null>; +}) { + const gt = useGT(); + const { copyToClipboard, isCopied } = useCopyToClipboard({ + target: namedClipboardTarget(props.name), + }); + const [saving, setSaving] = useState(false); + const refreshAssetUrl = useAssetUrlRefresh( + props.environmentId, + largeFileResource(props.threadRef, props.absolutePath, props.draftCwd), + ); + const showError = (cause: unknown) => { + toastManager.add({ + type: "error", + title: gt("Could not read file"), + description: thrownErrorMessage(cause, m) ?? gt("Try again."), + }); + }; + return ( + <> + { + const copy = props.copyContents.current; + if (!copy) return; + void copy() + .then((text) => copyToClipboard(text, undefined)) + .catch(showError); + }} + > + {isCopied ? : } + + { + setSaving(true); + void (async () => { + const url = await refreshAssetUrl(); + if (!url) throw new Error(gt("Reconnect to the environment and try again.")); + const response = await fetch(url); + if (!response.ok) throw new Error(gt("The file could not be loaded. Try again.")); + const downloadUrl = URL.createObjectURL(await response.blob()); + setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000); + const anchor = document.createElement("a"); + anchor.href = downloadUrl; + anchor.download = props.name.split(/[\\/]/).at(-1) || props.name; + anchor.click(); + })() + .catch(showError) + .finally(() => setSaving(false)); + }} + > + + + + ); +} + export function WorkspaceLargeTextPreview(props: { environmentId: EnvironmentId; threadRef: ScopedThreadRef; absolutePath: string; + /** The draft's workspace while the thread does not exist yet. */ + draftCwd: string | null; name: string; delimiter: "," | "\t" | null; + /** Renders the file as Markdown resolving links against this workspace; null shows source. */ + markdownCwd: string | null; + copyContents: RefObject<(() => Promise) | null>; + /** The first megabyte already read, shown until the whole file arrives. */ + preview: string; + sizeBytes: number; + onPostRender?: ComponentProps["onPostRender"]; workspaceMutationId: string | null; revealLine: number | null; revealRequestId: number; wordWrap: boolean; }) { - const resource = { - _tag: "media-file", - threadId: props.threadRef.threadId, - path: props.absolutePath, - disposition: "attachment", - } as const; + const resource = largeFileResource(props.threadRef, props.absolutePath, props.draftCwd); const gt = useGT(); - const copyContents = useRef<(() => Promise) | null>(null); - const { copyToClipboard, isCopied } = useCopyToClipboard({ - target: namedClipboardTarget(props.name), - }); - const [saving, setSaving] = useState(false); const [revision, setRevision] = useState(0); const showError = (cause: unknown) => { toastManager.add({ @@ -2068,78 +2138,30 @@ export function WorkspaceLargeTextPreview(props: { }} /> ); - if (assetUrl._tag !== "Success" || loaded === null) - return ( -
- Loading… -
- ); + if (assetUrl._tag !== "Success" || loaded === null) return ; const src = `${loaded.url}${loaded.url.includes("?") ? "&" : "?"}revision=${encodeURIComponent(loaded.revision)}`; + const retry = () => { + void refreshAssetUrl() + .then(() => setRevision((value) => value + 1)) + .catch(showError); + }; return ( - <> -
- - Full file - - { - const copy = copyContents.current; - if (!copy) return; - void copy() - .then((text) => copyToClipboard(text, undefined)) - .catch(showError); - }} - > - {isCopied ? : } - - { - setSaving(true); - void (async () => { - const url = await refreshAssetUrl(); - if (!url) throw new Error(gt("Reconnect to the environment and try again.")); - const response = await fetch(url); - if (!response.ok) throw new Error(gt("The file could not be loaded. Try again.")); - const downloadUrl = URL.createObjectURL(await response.blob()); - setTimeout(() => URL.revokeObjectURL(downloadUrl), 30_000); - const anchor = document.createElement("a"); - anchor.href = downloadUrl; - anchor.download = props.name.split(/[\\/]/).at(-1) || props.name; - anchor.click(); - })() - .catch(showError) - .finally(() => setSaving(false)); - }} - > - - -
- - Loading… -
- } - > - { - void refreshAssetUrl() - .then(() => setRevision((value) => value + 1)) - .catch(showError); - }} - src={src} - delimiter={props.delimiter} - revealLine={props.revealLine} - revealRequestId={props.revealRequestId} - wordWrap={props.wordWrap} - /> - - + ); } diff --git a/apps/web/src/components/files/LargeFilePreview.tsx b/apps/web/src/components/files/LargeFilePreview.tsx new file mode 100644 index 0000000000000..21590a1ea2b11 --- /dev/null +++ b/apps/web/src/components/files/LargeFilePreview.tsx @@ -0,0 +1,125 @@ +import type { ScopedThreadRef } from "@t3tools/contracts"; +import { DEFAULT_TOKENIZE_MAX_LENGTH } from "@pierre/diffs"; +import type { FileOptions } from "@pierre/diffs/react"; +import { useGT } from "gt-react"; +import { lazy, Suspense, useImperativeHandle, type RefObject } from "react"; + +import { ChunkedMarkdown } from "./ChunkedMarkdown"; +import { FileSurfaceLoading } from "./fileSurfaceChrome"; +import { useFullFileMarkdown, useFullFileText } from "./fullFileText"; +import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; +import SourceFilePreview from "./ReadOnlySourcePreview"; + +const LargeTextViewer = lazy(() => import("./LargeTextViewer")); + +/** + * A file past the 1 MB read, shown like any other file once its full text arrives. Tables, and + * files too large to hold or lay out, use the worker-backed plain viewer. + */ +export default function LargeFilePreview(props: { + readonly src: string; + readonly name: string; + /** The first megabyte already read. */ + readonly preview: string; + readonly sizeBytes: number; + readonly delimiter: "," | "\t" | null; + /** Renders the file as Markdown resolving links against this workspace; null shows source. */ + readonly markdownCwd: string | null; + readonly threadRef: ScopedThreadRef; + readonly workspaceMutationId: string | null; + readonly copyContents: RefObject<(() => Promise) | null>; + readonly onRetry: () => void; + readonly onPostRender?: FileOptions["onPostRender"]; + readonly revealLine: number | null; + readonly revealRequestId: number; + readonly wordWrap: boolean; +}) { + const plain = props.delimiter !== null || props.sizeBytes > FULL_TEXT_MAX_BYTES; + return plain ? : ; +} + +// Pierre keeps every token of a highlighted file in memory: a 320k-line log took about 280 MB. +const HIGHLIGHT_MAX_LINES = DEFAULT_TOKENIZE_MAX_LENGTH; + +/** Estimates the whole file's lines from the preview, so highlighting is decided once. */ +function estimatedLines(preview: string, sizeBytes: number): number { + let lines = 1; + for (let index = preview.indexOf("\n"); index !== -1; index = preview.indexOf("\n", index + 1)) + lines += 1; + return (lines / Math.max(1, new TextEncoder().encode(preview).length)) * sizeBytes; +} + +function FullTextPreview(props: Parameters[0]) { + const file = useFullFileText(props.src, props.preview); + // Deciding from the full text would highlight the preview, then drop it once the file arrives. + const highlight = estimatedLines(props.preview, props.sizeBytes) <= HIGHLIGHT_MAX_LINES; + if (file === "too-large" || file === "failed") return ; + return ( + <> + + {props.markdownCwd !== null ? ( + + ) : ( + + )} + + ); +} + +function MarkdownText( + props: Parameters[0] & { + readonly markdownCwd: string; + readonly file: { readonly text: string; readonly done: boolean }; + }, +) { + return ( + + ); +} + +function CopyText(props: { + readonly copyContents: RefObject<(() => Promise) | null>; + readonly text: string | null; +}) { + const gt = useGT(); + const { text } = props; + useImperativeHandle( + props.copyContents, + () => () => + text === null + ? Promise.reject(new Error(gt("The file is still loading. Try again in a moment."))) + : Promise.resolve(text), + [text, gt], + ); + return null; +} + +function PlainViewer(props: Parameters[0]) { + return ( + }> + + + ); +} diff --git a/apps/web/src/components/files/LargeTextViewer.tsx b/apps/web/src/components/files/LargeTextViewer.tsx index 3cfe6b7fafcaa..fc9a890dd9b3e 100644 --- a/apps/web/src/components/files/LargeTextViewer.tsx +++ b/apps/web/src/components/files/LargeTextViewer.tsx @@ -1,6 +1,7 @@ import { msg, T, useGT, useMessages } from "gt-react"; import { useEffect, useImperativeHandle, useRef, useState, type RefObject } from "react"; import { m } from "~/i18n/messages"; +import { Spinner } from "~/components/ui/spinner"; import { parseDelimitedPreview } from "@t3tools/shared/delimitedPreview"; import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { useClientSettings } from "~/hooks/useSettings"; @@ -29,6 +30,36 @@ function firstScreen(text: string, delimiter: "," | "\t" | null, complete: boole return rows.slice(0, PREVIEW_PAGE_ROWS * 2); } +type Meta = Extract; + +function firstScreenState(text: string, delimiter: "," | "\t" | null, complete: boolean) { + const rows = firstScreen(text, delimiter, complete); + if (!rows.length) return null; + return { + pages: new Map( + [0, PREVIEW_PAGE_ROWS] + .filter((start) => start < rows.length) + .map((start) => [start / PREVIEW_PAGE_ROWS, rows.slice(start, start + PREVIEW_PAGE_ROWS)]), + ), + meta: { + type: "meta", + count: rows.length, + columns: rows.reduce((max, row) => Math.max(max, row.length), 1), + complete: false, + } satisfies Meta as Meta, + }; +} + +// Reopening a recent file paints its first screen at once while the worker indexes it again. +const recentFirstScreens = new Map(); + +function rememberFirstScreen(src: string, text: string, complete: boolean) { + recentFirstScreens.delete(src); + recentFirstScreens.set(src, { text, complete }); + if (recentFirstScreens.size > 32) + recentFirstScreens.delete(recentFirstScreens.keys().next().value!); +} + export default function LargeTextViewer(props: { readonly name: string; readonly src?: string; @@ -44,8 +75,12 @@ export default function LargeTextViewer(props: { }) { const gt = useGT(); const messages = useMessages(); - const [meta, setMeta] = useState | null>(null); - const [pages, setPages] = useState(new Map()); + const [initial] = useState(() => { + const cached = props.src === undefined ? undefined : recentFirstScreens.get(props.src); + return cached ? firstScreenState(cached.text, props.delimiter, cached.complete) : null; + }); + const [meta, setMeta] = useState(initial?.meta ?? null); + const [pages, setPages] = useState(initial?.pages ?? new Map()); const [error, setError] = useState(null); const worker = useRef(null); const copyPending = useRef<{ @@ -66,25 +101,11 @@ export default function LargeTextViewer(props: { let prefetched = false; const paintFirstScreen = (text: string, complete: boolean) => { if (indexed || controller.signal.aborted) return; - const rows = firstScreen(text, props.delimiter, complete); - if (!rows.length) return; + const screen = firstScreenState(text, props.delimiter, complete); + if (!screen) return; prefetched = true; - setPages( - new Map( - [0, PREVIEW_PAGE_ROWS] - .filter((start) => start < rows.length) - .map((start) => [ - start / PREVIEW_PAGE_ROWS, - rows.slice(start, start + PREVIEW_PAGE_ROWS), - ]), - ), - ); - setMeta({ - type: "meta", - count: rows.length, - columns: rows.reduce((max, row) => Math.max(max, row.length), 1), - complete: false, - }); + setPages(screen.pages); + setMeta(screen.meta); }; const startWorker = () => { if (controller.signal.aborted) return; @@ -104,9 +125,14 @@ export default function LargeTextViewer(props: { } else if (result.type === "meta") { indexed = true; if (prefetched) { - setPages(new Map()); - pending.current.clear(); + // Keeps the painted first screen until the worker's own pages replace it. prefetched = false; + pending.current.clear(); + for (const index of [0, 1]) { + if (index * PREVIEW_PAGE_ROWS >= result.count) break; + pending.current.add(index); + engine.postMessage({ type: "page", index }, []); + } } setMeta(result); } else if (result.type === "page") { @@ -152,8 +178,12 @@ export default function LargeTextViewer(props: { }; // Only this bounded prefix is parsed on the main thread. Indexing the full // file and fetching later pages remain in the worker. + const cached = props.src === undefined ? undefined : recentFirstScreens.get(props.src); if (props.sizeBytes === 0) { startWorker(); + } else if (cached) { + paintFirstScreen(cached.text, cached.complete); + scheduleWorker(); } else if (props.text !== undefined) { paintFirstScreen( props.text.slice(0, FIRST_SCREEN_BYTES), @@ -161,7 +191,8 @@ export default function LargeTextViewer(props: { ); scheduleWorker(); } else if (props.src) { - void fetch(props.src, { + const src = props.src; + void fetch(src, { headers: { Range: `bytes=0-${FIRST_SCREEN_BYTES - 1}` }, cache: "no-store", signal: controller.signal, @@ -176,7 +207,9 @@ export default function LargeTextViewer(props: { return; } const total = Number(response.headers.get("content-range")?.split("/")[1]); - paintFirstScreen(await response.text(), total <= FIRST_SCREEN_BYTES); + const text = await response.text(); + rememberFirstScreen(src, text, total <= FIRST_SCREEN_BYTES); + paintFirstScreen(text, total <= FIRST_SCREEN_BYTES); }) .catch(() => { // The worker reports authorization, network and format failures. @@ -223,27 +256,28 @@ export default function LargeTextViewer(props: { className="flex min-h-10 shrink-0 flex-wrap items-center gap-x-1 border-b border-border/60 px-3 py-2 text-xs text-muted-foreground tabular-nums" role="status" > - {props.delimiter - ? `${gt("{count, plural, one {{formatted} row} other {{formatted} rows}}", { - count: rowCount, - formatted: rowCount.toLocaleString(), - })} · ${gt("{count, plural, one {{formatted} column} other {{formatted} columns}}", { - count: columnCount, - formatted: columnCount.toLocaleString(), - })}` - : gt("{count, plural, one {{formatted} line} other {{formatted} lines}}", { - count: meta.count, - formatted: meta.count.toLocaleString(), - })} + {/* Counts appear once indexing ends; the prefix count alone would understate the file. */} + {!meta.complete + ? null + : props.delimiter + ? `${gt("{count, plural, one {{formatted} row} other {{formatted} rows}}", { + count: rowCount, + formatted: rowCount.toLocaleString(), + })} · ${gt("{count, plural, one {{formatted} column} other {{formatted} columns}}", { + count: columnCount, + formatted: columnCount.toLocaleString(), + })}` + : gt("{count, plural, one {{formatted} line} other {{formatted} lines}}", { + count: meta.count, + formatted: meta.count.toLocaleString(), + })} {meta.complete && meta.sizeBytes !== undefined ? ` · ${meta.sizeBytes === 0 ? gt("0 bytes") : formatAttachmentSize(meta.sizeBytes, messages)}` - : ` · ${gt("Indexing…")}`} + : null}
{!meta.complete ? ( -
- - Loading the rest of the file… - +
+
) : null} {meta.columns === 1024 ? ( diff --git a/apps/web/src/components/files/NotebookPreview.tsx b/apps/web/src/components/files/NotebookPreview.tsx index 35d0203818850..e4858515024db 100644 --- a/apps/web/src/components/files/NotebookPreview.tsx +++ b/apps/web/src/components/files/NotebookPreview.tsx @@ -2,8 +2,8 @@ import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments"; import { T, useGT, useMessages } from "gt-react"; import { useEffect, useRef, useState } from "react"; -import type { Root, RootContent } from "mdast"; import ChatMarkdown from "~/components/ChatMarkdown"; +import type { MarkdownExtensions } from "~/markdown/wordsHast"; import { Button } from "~/components/ui/button"; import ReadOnlySourcePreview from "./ReadOnlySourcePreview"; import DocumentPages from "./DocumentPages"; @@ -11,24 +11,7 @@ import { FileSurfaceNotice } from "./fileSurfaceChrome"; import type { OfficeWorkerResult } from "./officePreviewProtocol"; // Saved notebooks must not load URLs or turn authored links into app actions. -function inertNotebookMarkdown() { - function clean(nodes: RootContent[]): RootContent[] { - return nodes.flatMap((node): RootContent[] => { - if (node.type === "html" || node.type === "definition") return []; - if (node.type === "image" || node.type === "imageReference") - return [{ type: "text", value: node.alt ?? "" }]; - if (node.type === "link" || node.type === "linkReference") return clean(node.children); - if (node.type === "inlineCode") return [{ type: "text", value: node.value }]; - if (node.type === "code" && node.lang === "mermaid") return [{ ...node, lang: "text" }]; - if ("children" in node) node.children = clean(node.children) as typeof node.children; - return [node]; - }); - } - return (tree: Root) => { - tree.children = clean(tree.children) as Root["children"]; - }; -} -const NOTEBOOK_PLUGINS = [inertNotebookMarkdown]; +const NOTEBOOK_MARKDOWN: MarkdownExtensions = { inert: true }; function NotebookSource(props: { readonly name: string; readonly text: string }) { const [height, setHeight] = useState(Math.min(360, props.text.split("\n").length * 20 + 16)); @@ -64,36 +47,42 @@ export default function NotebookPreview(props: { useEffect(() => { const root = scroll.current; if (!root || !outputCount) return; - const candidates = new Map(); - let active: Element[] = []; - const observer = new IntersectionObserver( - (entries) => { - for (const entry of entries) { - if (entry.isIntersecting) - candidates.set(entry.target, (entry.target as HTMLElement).dataset.notebookOutput!); - else candidates.delete(entry.target); - } - // Bound browsing contexts even when a cell contains hundreds of tiny HTML outputs. - const next = [...candidates.keys()].slice(0, 16); - const measured = active - .filter((node) => !next.includes(node)) - .map( - (node) => - [ - (node as HTMLElement).dataset.notebookOutput!, - node.getBoundingClientRect().height, - ] as const, - ); - active = next; - setOutputView((old) => ({ - mounted: new Set(next.map((node) => candidates.get(node)!)), - heights: new Map([...old.heights, ...measured]), - })); - }, - { root, rootMargin: "160px" }, - ); - for (const node of root.querySelectorAll("[data-notebook-output]")) observer.observe(node); - return () => observer.disconnect(); + const inView = new Set(); + const nearby = new Set(); + let active = new Set(); + const outputKey = (node: Element) => node.getAttribute("data-notebook-output")!; + const track = (candidates: Set) => (entries: IntersectionObserverEntry[]) => { + for (const entry of entries) { + if (entry.isIntersecting) candidates.add(entry.target); + else candidates.delete(entry.target); + } + // Mount every visible output. Only preload while the total is below 16. + const next = new Set(inView); + for (const node of nearby) { + if (next.size >= 16) break; + next.add(node); + } + const departing = [...active].filter((node) => !next.has(node)); + if (active.size === next.size && departing.length === 0) return; + const measured = departing + .map((node) => [outputKey(node), node.clientHeight] as const) + .filter(([, height]) => height > 0); + active = next; + setOutputView((old) => ({ + mounted: new Set(Array.from(next, outputKey)), + heights: new Map([...old.heights, ...measured]), + })); + }; + const viewportObserver = new IntersectionObserver(track(inView), { root }); + const preloadObserver = new IntersectionObserver(track(nearby), { root, rootMargin: "160px" }); + for (const node of root.querySelectorAll("[data-notebook-output]")) { + viewportObserver.observe(node); + preloadObserver.observe(node); + } + return () => { + viewportObserver.disconnect(); + preloadObserver.disconnect(); + }; }, [outputCount]); return ( <> @@ -129,7 +118,7 @@ export default function NotebookPreview(props: { text={cell.source} cwd={undefined} parseRawHtml={false} - extraRemarkPlugins={NOTEBOOK_PLUGINS} + extensions={NOTEBOOK_MARKDOWN} className="px-4 py-3" /> ) : cell.source.trim() ? ( @@ -138,42 +127,43 @@ export default function NotebookPreview(props: { text={cell.source} /> ) : null} - {cell.outputs.map((output, outputIndex) => ( -
- {output.kind === "html" ? ( - !outputView.mounted.has(`${index}-${outputIndex}`) ? null : ( - { + const key = `${index}-${outputIndex}`; + const mounted = outputView.mounted.has(key); + const estimatedHeight = outputView.heights.get(key) ?? 80; + return ( +
+ {output.kind === "html" ? ( + mounted ? ( + + ) : null + ) : output.kind === "image" ? ( + {gt("Cell - ) - ) : output.kind === "image" ? ( - {gt("Cell - ) : ( -
-                      {output.text}
-                    
- )} -
- ))} + ) : ( +
+                        {output.text}
+                      
+ )} +
+ ); + })} ))} {props.notebook.cells.length === 0 ? ( diff --git a/apps/web/src/components/files/ReadOnlySourcePreview.tsx b/apps/web/src/components/files/ReadOnlySourcePreview.tsx index d9236753e98a3..cd1559f46052f 100644 --- a/apps/web/src/components/files/ReadOnlySourcePreview.tsx +++ b/apps/web/src/components/files/ReadOnlySourcePreview.tsx @@ -17,6 +17,8 @@ export default function ReadOnlySourcePreview(props: { readonly onPostRender?: FileOptions["onPostRender"]; /** A preview's own wrap toggle; omitted follows the word wrap setting. */ readonly wordWrap?: boolean; + /** Files with more lines than this render without highlighting; omitted keeps Pierre's limit. */ + readonly tokenizeMaxLength?: number; }) { const resolvedTheme = useRenderedAppearance(); const defaultWordWrap = useClientSettings((settings) => settings.wordWrap); @@ -70,7 +72,8 @@ export default function ReadOnlySourcePreview(props: { }} > @@ -85,6 +88,9 @@ export default function ReadOnlySourcePreview(props: { overflow: wordWrap ? "wrap" : "scroll", theme: resolveDiffThemeName(resolvedTheme), preferredHighlighter: PREFERRED_HIGHLIGHTER, + ...(props.tokenizeMaxLength === undefined + ? {} + : { tokenizeMaxLength: props.tokenizeMaxLength }), themeType: resolvedTheme, unsafeCSS: FILE_LINK_REVEAL_UNSAFE_CSS, onPostRender: drawSelection, diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index 7d6021de6f811..f107ea0266043 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -538,6 +538,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { let state = { skip: false, deleted: false, + hiddenText: false, bold: false, italic: false, underline: false, @@ -560,7 +561,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { }; let run = ""; let fallback = 0; - const hidden = () => state.skip || state.deleted; + const hidden = () => state.skip || state.deleted || state.hiddenText; const encoded = new Uint8Array(bytes.byteLength); let encodedLength = 0; const flush = () => { @@ -722,10 +723,12 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "ul") state.underline = arg !== 0; else if (word === "ulnone") state.underline = false; else if (word === "deleted") state.deleted = arg !== 0; + else if (word === "v") state.hiddenText = arg !== 0; else if (word === "plain") state = { ...state, deleted: false, + hiddenText: false, bold: false, italic: false, underline: false, diff --git a/apps/web/src/components/files/fileReadingPosition.browser.test.tsx b/apps/web/src/components/files/fileReadingPosition.browser.test.tsx index 54106880f5104..d6bca9d4a2d13 100644 --- a/apps/web/src/components/files/fileReadingPosition.browser.test.tsx +++ b/apps/web/src/components/files/fileReadingPosition.browser.test.tsx @@ -60,6 +60,7 @@ import { csv, environmentId, holdIndexing, + LARGE_TEXT_BYTES, largeText, lines, ReadingPanel, @@ -190,63 +191,6 @@ describe("file reading position", () => { expect(reading.saved("a.ts", "source")).toEqual(saved); }); - it("returns rendered Markdown to the reader's block after a tab switch, clamped when shorter", async () => { - using reading = await readingSetup("rendered"); - const { panel, ref } = reading; - panel.openFile(ref, "b.ts"); - panel.openFile(ref, "doc.md"); - await using screen = await render(); - const viewport = () => - screen.container - .querySelector(".chat-markdown") - ?.closest('[data-slot="scroll-area-viewport"]'); - await vi.waitFor(() => expect(viewport()?.textContent).toContain("Paragraph 80.")); - await userEvent.wheel(viewport()!, { delta: { y: 1500 } }); - await vi.waitFor(() => expect(reading.saved("doc.md", "rendered")?.block).toBeGreaterThan(10)); - const wheeled = reading.saved("doc.md", "rendered")!.block!; - - // The custom scrollbar sits beside the viewport and moves it directly. - const scrollbar = screen.container.querySelector( - '[data-slot="scroll-area-scrollbar"]', - )!; - const track = scrollbar.getBoundingClientRect(); - await userEvent.click(scrollbar, { - position: { x: track.width / 2, y: track.height - 4 }, - }); - await vi.waitFor(() => - expect(reading.saved("doc.md", "rendered")?.block).toBeGreaterThan(wheeled), - ); - const before = viewport()!.scrollTop; - - await act(() => panel.activateSurface(ref, "file:b.ts")); - await vi.waitFor(() => expect(viewport()).toBeFalsy()); - await act(() => panel.activateSurface(ref, "file:doc.md")); - await vi.waitFor(() => expect(Math.abs(viewport()!.scrollTop - before)).toBeLessThanOrEqual(1)); - - await act(() => panel.activateSurface(ref, "file:b.ts")); - await vi.waitFor(() => expect(viewport()).toBeFalsy()); - const saved = reading.saved("doc.md", "rendered"); - const shorter = Array.from({ length: 30 }, (_, index) => `Paragraph ${index + 1}.`).join( - "\n\n", - ); - state.files["doc.md"] = { - relativePath: "doc.md", - contents: shorter, - byteLength: shorter.length, - truncated: false, - }; - await act(() => panel.activateSurface(ref, "file:doc.md")); - await vi.waitFor(() => { - const element = viewport()!; - expect(element.textContent).not.toContain("Paragraph 31."); - expect(element.scrollHeight).toBeGreaterThan(element.clientHeight); - expect(element.scrollTop).toBeGreaterThanOrEqual( - element.scrollHeight - element.clientHeight - 1, - ); - }); - expect(reading.saved("doc.md", "rendered")).toEqual(saved); - }); - it("returns a citation reopened with Reopen Closed View to the reader's place", async () => { using reading = await readingSetup("reopen-closed"); const { panel, ref } = reading; @@ -414,7 +358,7 @@ describe("large text and table rows keep the reader's place", () => { expect(reading.saved("table.csv", "rendered")).toEqual(saved); }); - it("keeps a text file's line when it grows past the 1 MB preview and when it shrinks back", async () => { + it("keeps a text file's line when it grows past the full-text read and when it shrinks back", async () => { using reading = await readingSetup("crossing"); const { panel, ref } = reading; const contents = lines(400); @@ -438,7 +382,7 @@ describe("large text and table rows keep the reader's place", () => { await act(() => panel.activateSurface(ref, "file:b.ts")); await vi.waitFor(() => view.expectLineInView(1, "beta_1")); reading.serve("app.log", contents); - state.files["app.log"] = { ...small, byteLength: 2_000_000, truncated: true }; + state.files["app.log"] = { ...small, byteLength: LARGE_TEXT_BYTES, truncated: true }; await act(() => panel.activateSurface(ref, "file:app.log")); await vi.waitFor(() => { rows.indexed(); @@ -512,8 +456,14 @@ describe("large text and table rows keep the reader's place", () => { await using screen = await render(); const rows = rowsView(screen.container); const view = sourceView(screen.container); - const status = () => screen.container.querySelector('[role="status"]')?.textContent ?? ""; - await vi.waitFor(() => expect(status()).toMatch(/600 lines.*Indexing/), COLD_WORKER); + // The worker has read all 600 rows; the status shows counts only once indexing ends. + const stillIndexing = () => { + expect(screen.container.querySelector("[aria-rowcount]")?.getAttribute("aria-rowcount")).toBe( + "600", + ); + expect(screen.container.querySelector('[role="status"]')?.textContent).toBe(""); + }; + await vi.waitFor(stillIndexing, COLD_WORKER); await rows.wheel(3000); await vi.waitFor(() => expect(rows.topRow()).toBeGreaterThan(80)); const top = rows.scroller()!.scrollTop; @@ -533,7 +483,7 @@ describe("large text and table rows keep the reader's place", () => { indexing.hold(); await act(() => panel.activateSurface(ref, "file:big.log")); // A click that scrolls nothing while it indexes leaves the restore to land. - await vi.waitFor(() => expect(status()).toMatch(/600 lines.*Indexing/), COLD_WORKER); + await vi.waitFor(stillIndexing, COLD_WORKER); await userEvent.click(rows.scroller()!); indexing.release(); await vi.waitFor(() => { diff --git a/apps/web/src/components/files/fileReadingTestKit.tsx b/apps/web/src/components/files/fileReadingTestKit.tsx index 92f72db6377f3..123cc7224953b 100644 --- a/apps/web/src/components/files/fileReadingTestKit.tsx +++ b/apps/web/src/components/files/fileReadingTestKit.tsx @@ -16,6 +16,7 @@ import appCss from "~/index.css?inline"; import { selectActiveRightPanelSurface, useRightPanelStore } from "~/rightPanelStore"; import FilePreviewPanel from "./FilePreviewPanel"; +import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; import { resetState, state } from "./fileReadingTestMocks"; export { state }; @@ -279,6 +280,9 @@ export function lines(count: number) { return Array.from({ length: count }, (_, index) => `log line ${index + 1}`).join("\n"); } +/** Past the full-text read, so the worker-backed rows viewer shows the file. */ +export const LARGE_TEXT_BYTES = FULL_TEXT_MAX_BYTES + 1; + /** A large text file the panel streams from its asset URL. */ export function largeText( reading: { readonly serve: (path: string, contents: string) => void }, @@ -286,7 +290,12 @@ export function largeText( contents: string, ) { reading.serve(path, contents); - state.files[path] = { relativePath: path, contents, byteLength: 2_000_000, truncated: true }; + state.files[path] = { + relativePath: path, + contents, + byteLength: LARGE_TEXT_BYTES, + truncated: true, + }; } /** diff --git a/apps/web/src/components/files/fullFileText.test.ts b/apps/web/src/components/files/fullFileText.test.ts new file mode 100644 index 0000000000000..80f507c3526cb --- /dev/null +++ b/apps/web/src/components/files/fullFileText.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; +import { FetchHttpClient } from "effect/http"; + +import { downloadText } from "./fullFileText"; +import { RENDERED_MAX_LINES } from "./largeTextProtocol"; + +const encoder = new TextEncoder(); + +const download = (file: Uint8Array) => + downloadText("http://localhost/assets/file.ts").pipe( + Stream.runLast, + Effect.map(Option.getOrThrow), + Effect.provide(FetchHttpClient.layer), + Effect.provideService(FetchHttpClient.Fetch, () => Promise.resolve(new Response(file.slice()))), + ); + +describe("downloadText", () => { + it.effect( + "drops a leading byte order mark as the preview read does, and keeps a later U+FEFF", + () => + Effect.gen(function* () { + const whole = new Uint8Array([0xef, 0xbb, 0xbf, ...encoder.encode("one\ntwo\n")]); + expect((yield* download(whole)).text).toBe("one\ntwo\n"); + }), + ); + + it.effect("stops at the first text past the lines the main thread can lay out", () => + Effect.gen(function* () { + const file = yield* download(encoder.encode("\n".repeat(RENDERED_MAX_LINES + 10))); + expect(file.lines).toBeGreaterThan(RENDERED_MAX_LINES); + }), + ); +}); diff --git a/apps/web/src/components/files/fullFileText.ts b/apps/web/src/components/files/fullFileText.ts new file mode 100644 index 0000000000000..8ff9c557407a1 --- /dev/null +++ b/apps/web/src/components/files/fullFileText.ts @@ -0,0 +1,90 @@ +import { useAtomValue } from "@effect/atom-react"; +import { splitMarkdown, type SplitMarkdown } from "@t3tools/shared/markdownChunks"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; +import * as Stream from "effect/Stream"; +import { AsyncResult, Atom } from "effect/reactivity"; + +import { connectionAtomRuntime } from "~/connection/runtime"; + +import { FULL_TEXT_MAX_BYTES, RENDERED_MAX_LINES } from "./largeTextProtocol"; + +// A slow download swaps in what has arrived this often, so the reader is not left at 1 MB. +const SWAP_INTERVAL = "1 second"; +// Switching back to a recently closed file reuses its text instead of downloading it again. +const RECENT_FILE_TTL_MS = 60_000; + +interface Downloaded { + readonly text: string; + readonly lines: number; +} + +function countNewlines(text: string): number { + let lines = 0; + for (let index = text.indexOf("\n"); index !== -1; index = text.indexOf("\n", index + 1)) { + lines += 1; + } + return lines; +} + +// Past either cap the main thread cannot hold or lay the text out. +const tooLarge = (file: Downloaded) => + file.lines > RENDERED_MAX_LINES || file.text.length > FULL_TEXT_MAX_BYTES; + +/** A file's text so far, at most once per interval, ending at its whole text or past a cap. */ +export const downloadText = (src: string) => + HttpClient.get(src).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.map((response) => response.stream), + Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }), + Stream.unwrap, + // Drops a leading BOM, as the 1 MB preview read does. + Stream.decodeText, + Stream.scan( + (): Downloaded => ({ text: "", lines: 1 }), + (file, chunk) => ({ text: file.text + chunk, lines: file.lines + countNewlines(chunk) }), + ), + Stream.takeUntil(tooLarge), + Stream.groupedWithin(Number.MAX_SAFE_INTEGER, SWAP_INTERVAL), + Stream.map((swaps) => swaps[swaps.length - 1]!), + ); + +/** `src` is the asset URL with its revision, so a changed file downloads again. */ +const fullFileTextAtom = Atom.family((src: string) => + connectionAtomRuntime + .atom(downloadText(src)) + .pipe(Atom.setIdleTTL(RECENT_FILE_TTL_MS), Atom.withLabel(`full-file-text:${src}`)), +); + +export type FullFileText = + | { readonly text: string; readonly done: boolean } + | "too-large" + | "failed"; + +/** A file past the 1 MB read: the preview at once, then the full file as it downloads. */ +export function useFullFileText(src: string, preview: string): FullFileText { + const result = useAtomValue(fullFileTextAtom(src)); + if (AsyncResult.isFailure(result)) return "failed"; + if (!AsyncResult.isSuccess(result)) return { text: preview, done: false }; + if (tooLarge(result.value)) return "too-large"; + if (!result.waiting) return { text: result.value.text, done: true }; + // Whole lines only, so the last row does not flicker as it fills in; the first swap can still + // hold less than the preview already shows. + const text = result.value.text.slice(0, result.value.text.lastIndexOf("\n") + 1); + return { text: text.length >= preview.length ? text : preview, done: false }; +} + +/** The finished text's Markdown pieces, kept as long as its text; splitting 12 MB takes 0.5 s. */ +const fullFileMarkdownAtom = Atom.family((src: string) => + Atom.make((get) => { + const result = get(fullFileTextAtom(src)); + return AsyncResult.isSuccess(result) && !result.waiting && !tooLarge(result.value) + ? splitMarkdown(result.value.text) + : null; + }).pipe(Atom.setIdleTTL(RECENT_FILE_TTL_MS), Atom.withLabel(`full-file-markdown:${src}`)), +); + +/** Markdown pieces of the text so far; a finished file's are split once and kept. */ +export function useFullFileMarkdown(src: string, text: string): SplitMarkdown { + return useAtomValue(fullFileMarkdownAtom(src)) ?? splitMarkdown(text); +} diff --git a/apps/web/src/components/files/largeTextProtocol.ts b/apps/web/src/components/files/largeTextProtocol.ts index 8ff6e54946289..661b15c8c8e7d 100644 --- a/apps/web/src/components/files/largeTextProtocol.ts +++ b/apps/web/src/components/files/largeTextProtocol.ts @@ -3,6 +3,12 @@ export const LARGE_TEXT_MAX_BYTES = 256 * 1024 * 1024; export const LARGE_TEXT_MAX_ROWS = 5_000_000; export const LARGE_TEXT_MAX_COLUMNS = 1024; export const PREVIEW_PAGE_ROWS = 32; +// Browsers stop laying out an element near 33.5M px. Rendered Markdown measured about 22 px per +// source line, so files taller than this stay in the scaled plain viewer. +export const RENDERED_MAX_LINES = 1_200_000; +// Rendered Markdown and highlighted source hold the whole file on the main thread; larger files +// use the worker-backed plain viewer. +export const FULL_TEXT_MAX_BYTES = 64 * 1024 * 1024; export type TextPreviewRequest = | { type: "open"; src?: string; text?: string; sizeBytes?: number; delimiter: "," | "\t" | null } | { type: "page"; index: number } diff --git a/apps/web/src/components/files/office/Spreadsheet.tsx b/apps/web/src/components/files/office/Spreadsheet.tsx index c85a51a11526f..425116d0767e2 100644 --- a/apps/web/src/components/files/office/Spreadsheet.tsx +++ b/apps/web/src/components/files/office/Spreadsheet.tsx @@ -56,8 +56,7 @@ export default function Spreadsheet(props: { }) { const { onError, bytes: source, onDetails, view } = props; const gt = useGT(); - const [opened, setOpened] = useState(); - const [error, setError] = useState(""); + const [preview, setPreview] = useState<{ opened: Opened; error?: string }>(); const picking = useRef(null); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Open the workbook worker and cancel workbook and sheet requests when the source changes or unmounts. useEffect(() => { @@ -76,7 +75,7 @@ export default function Spreadsheet(props: { .call("open", { bytes, view }, { transfer: [bytes], signal: controller.signal }) .then((value) => { if (!value) throw new Error(m(msg("This workbook has no visible sheets."))); - setOpened({ ...value, engine }); + setPreview({ opened: { ...value, engine } }); onDetails( m( msg("{count, plural, one {{count} sheet} other {{count} sheets}}", { @@ -93,22 +92,26 @@ export default function Spreadsheet(props: { }; }, [source, view, onDetails, onError]); const show = (sheet: number, target?: CellAddr) => { - if (!opened) return; + if (!preview) return; + const { opened } = preview; picking.current?.abort(); + // The previous reply may have queued a state update that React has yet to commit. + setPreview(preview); if (sheet === opened.layout.info.activeSheet) return; const controller = new AbortController(); picking.current = controller; void opened.engine .call("show", { sheet }, { signal: controller.signal }) .then((layout) => { - setError(""); - setOpened({ ...opened, layout, target }); + if (!controller.signal.aborted) setPreview({ opened: { ...opened, layout, target } }); }) .catch(() => { - if (!controller.signal.aborted) setError(m(msg("This sheet could not be opened."))); + if (!controller.signal.aborted) + setPreview({ opened, error: m(msg("This sheet could not be opened.")) }); }); }; - if (!opened) return ; + if (!preview) return ; + const { opened, error } = preview; return (
{error ? {error} : null} @@ -128,9 +131,9 @@ export default function Spreadsheet(props: { aria-label={gt("Sheets")} className="flex h-9 shrink-0 items-center gap-1 overflow-x-auto border-t border-border px-2" onKeyDown={(event) => { - const current = opened.tabs.findIndex( - (tab) => tab.index === opened.layout.info.activeSheet, - ); + // Focus moves before the worker confirms the selected sheet. + const buttons = event.currentTarget.querySelectorAll('[role="tab"]'); + const current = Array.from(buttons).findIndex((button) => button === event.target); const next = event.key === "ArrowRight" ? (current + 1) % opened.tabs.length @@ -145,7 +148,7 @@ export default function Spreadsheet(props: { event.preventDefault(); const tab = opened.tabs[next]; if (tab) show(tab.index); - event.currentTarget.querySelectorAll('[role="tab"]')[next]?.focus(); + buttons[next]?.focus(); }} > {opened.tabs.map((tab) => ( diff --git a/apps/web/src/components/files/useEditableAfterHighlight.ts b/apps/web/src/components/files/useEditableAfterHighlight.ts new file mode 100644 index 0000000000000..f91ef979de5c3 --- /dev/null +++ b/apps/web/src/components/files/useEditableAfterHighlight.ts @@ -0,0 +1,46 @@ +import { + DEFAULT_TOKENIZE_MAX_LENGTH, + getFiletypeFromFileName, + type FileContents, + type PostRenderPhase, +} from "@pierre/diffs"; +import { useWorkerPool } from "@pierre/diffs/react"; +import type { WorkerPoolManager } from "@pierre/diffs/worker"; +import { useEffect, useState } from "react"; + +function needsWorkerHighlight(workerPool: WorkerPoolManager | undefined, file: FileContents) { + if (workerPool?.isWorkingPool() !== true) return false; + if ((file.lang ?? getFiletypeFromFileName(file.name)) === "text") return false; + let lines = 1; + for ( + let index = file.contents.indexOf("\n"); + index !== -1; + index = file.contents.indexOf("\n", index + 1) + ) { + lines += 1; + } + return lines <= DEFAULT_TOKENIZE_MAX_LENGTH; +} + +/** Enable editing only after worker highlighting renders; active edit sessions highlight on the main + * thread. */ +export function useEditableAfterHighlight(file: FileContents) { + const workerPool = useWorkerPool(); + const [highlightedFile, setHighlightedFile] = useState(null); + const needsHighlight = needsWorkerHighlight(workerPool, file); + const ready = !needsHighlight || highlightedFile === file; + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- primes the worker pool's highlight cache for this file and falls back to plain text if it fails + useEffect(() => { + if (ready || workerPool === undefined) return; + workerPool.primeFileHighlightCache(file).catch(() => setHighlightedFile(file)); + }, [file, ready, workerPool]); + + const onPostRender = (renderedFile: FileContents | undefined, phase: PostRenderPhase) => { + if (ready || phase === "unmount" || renderedFile?.cacheKey !== file.cacheKey) return; + // Cache results arrive just before instance rendering; seeing the cache during render means rows are + // highlighted. + if (workerPool?.getFileResultCache(file) !== undefined) setHighlightedFile(file); + }; + return { ready, onPostRender }; +} diff --git a/apps/web/src/components/issue/IssueDetailPanel.tsx b/apps/web/src/components/issue/IssueDetailPanel.tsx index bdee83563a330..30a55dd1d9e48 100644 --- a/apps/web/src/components/issue/IssueDetailPanel.tsx +++ b/apps/web/src/components/issue/IssueDetailPanel.tsx @@ -18,6 +18,7 @@ import type { IssueComment, IssueDetail, IssueEvent, + IssueEventReference, IssueLabelCandidate, IssueLinkedPullRequest, IssueListEntry, @@ -376,12 +377,44 @@ function LinkedPullRequestRow({ ); } +/** The sentence for an event, its source shown as a link where the tracker named one. */ +function IssueEventText({ + event, + sentence, + onOpen, +}: { + event: IssueEvent; + sentence: string; + /** Opens the source beside this issue, and says whether it did; if not, the link goes to the host. */ + onOpen: (source: IssueEventReference) => boolean; +}) { + const source = event.reference; + const at = event.detail === null ? -1 : sentence.indexOf(event.detail); + if (source === undefined || event.detail === null || at < 0) return {sentence}; + return ( + + {sentence.slice(0, at)} + } + onClick={(click) => { + if (!click.metaKey && !click.ctrlKey && onOpen(source)) click.preventDefault(); + }} + > + {event.detail} + + {sentence.slice(at + event.detail.length)} + + ); +} + export function IssueDetailPanel({ environmentId, reference, threadRef = null, listEntry = null, onSelectPullRequest, + onSelectIssue, }: { environmentId: EnvironmentId; reference: IssueRef; @@ -390,6 +423,8 @@ export function IssueDetailPanel({ threadRef?: ScopedThreadRef | null; /** Opens a linked change request beside this one; absent, the link goes to the host. */ onSelectPullRequest?: ((reference: PullRequestRef) => void) | undefined; + /** Opens a referenced issue beside this one; absent, the link goes to the host. */ + onSelectIssue?: ((reference: IssueRef & { readonly url: string }) => void) | undefined; }) { const gt = useGT(); const messages = useMessages(); @@ -442,6 +477,30 @@ export function IssueDetailPanel({ const tracker = issueTrackerPresentation(detail.tracker); const currentState = issueStatePresentation(detail.state); + const host = reference.host === undefined ? {} : { host: reference.host }; + const openEventSource = (source: IssueEventReference) => { + if (source.kind === "pull-request") { + if (!onSelectPullRequest) return false; + onSelectPullRequest({ + projectId: reference.projectId, + ...host, + repository: source.repository, + number: source.number, + }); + return true; + } + if (!onSelectIssue) return false; + onSelectIssue({ + projectId: reference.projectId, + tracker: reference.tracker, + ...host, + scope: source.repository, + key: String(source.number), + url: source.url, + }); + return true; + }; + const loadOlder = async () => { const failure = await pager.loadOlder(registry, (cursor) => loadComments({ environmentId, input: { ...reference, cursor } }), @@ -869,7 +928,11 @@ export function IssueDetailPanel({ className="px-1 text-xs text-muted-foreground" > - {issueEventSentence(item.event, messages)} + {formatRelativeTimeLabel(item.event.createdAt, undefined, messages)} ), diff --git a/apps/web/src/components/issue/IssuesPage.tsx b/apps/web/src/components/issue/IssuesPage.tsx index e29e3aa3c8123..d1c9f77aa2917 100644 --- a/apps/web/src/components/issue/IssuesPage.tsx +++ b/apps/web/src/components/issue/IssuesPage.tsx @@ -419,7 +419,7 @@ export function IssuesPage() { : clearedSelection, ); - const selectEntry = (entry: IssueRowTarget) => { + const selectEntry = (entry: Omit & { readonly host?: string }) => { if (rightPanelRef === null) return; useRightPanelStore.getState().openIssue(rightPanelRef, entry); updateSearch({ @@ -864,6 +864,13 @@ export function IssuesPage() { environmentId: panelEnvironmentId, }); }} + onSelectIssue={({ host, ...reference }) => + selectEntry({ + ...reference, + ...(host === undefined ? {} : { host }), + environmentId: panelEnvironmentId, + }) + } /> ) : ( ({ ...(await original()), @@ -86,3 +87,16 @@ describe("project action editor save lifecycle", () => { expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]); }); }); + +describe("project action editor dismissal", () => { + it("stays open when the user clicks outside the editor", async () => { + setup(); + await using screen = await render(null); + await open(screen, { scriptId: null, initial: EMPTY_PROJECT_SCRIPT_INPUT }); + await expect.element(page.getByRole("dialog")).toBeVisible(); + + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + + expect(onClose).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/components/projectScriptEditor.tsx b/apps/web/src/components/projectScriptEditor.tsx index 504e0afc69ca0..ea9b5ca1f2245 100644 --- a/apps/web/src/components/projectScriptEditor.tsx +++ b/apps/web/src/components/projectScriptEditor.tsx @@ -188,6 +188,8 @@ export function ProjectScriptEditorDialog({ <> { if (!open) onClose(); }} diff --git a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx index a797a7984cbce..250240d2849fa 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailLayout.tsx @@ -1,12 +1,39 @@ import { useGT } from "gt-react"; -import { ArrowLeftIcon, FileDiffIcon } from "lucide-react"; +import { ArrowLeftIcon, FileDiffIcon, LockIcon } from "lucide-react"; import { useEffect, useRef, type ComponentProps, type ReactNode } from "react"; import { cn } from "~/lib/utils"; +import { Badge } from "../ui/badge"; import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { PullRequestMetaLine } from "./pullRequestPresentation"; +export function PullRequestPrivateMark({ className }: { className?: string }) { + const gt = useGT(); + const label = gt("Private"); + return ( + + } + /> + {label} + + ); +} + +export function PullRequestPrivateBadge() { + const gt = useGT(); + return ( + + + + {gt("Private")} + + + ); +} + export function PullRequestDetailHeaderBody({ title, author, diff --git a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx index 9024f0adb27f5..83bd3892a1d0b 100644 --- a/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx +++ b/apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx @@ -90,6 +90,7 @@ import { MiddleTruncate } from "../ui/middle-truncate"; import { PullRequestChecksStatusLine, PullRequestDetailHeaderBody, + PullRequestPrivateBadge, PullRequestDetailTabBar, } from "./PullRequestDetailLayout"; import { PullRequestDetailGhost, PullRequestTimelineGhost } from "./PullRequestGhosts"; @@ -112,7 +113,7 @@ import { PullRequestsUnavailableState } from "./PullRequestsUnavailableState"; import type { PullRequestAgentSelectionInput } from "./PullRequestCodeTab"; import { openOnHostLabel } from "./pullRequestLinkContextMenu"; import { PullRequestMarkdownContext } from "./PullRequestMarkdown"; -import { pullRequestMarkdownPlugins } from "./pullRequestMarkdown.logic"; +import { pullRequestMarkdownExtensions } from "./pullRequestMarkdown.logic"; import { PullRequestComposer } from "./PullRequestComposer"; import { PullRequestSummaryTab } from "./PullRequestSummaryTab"; import { PullRequestTimelineTab } from "./PullRequestTimelineTab"; @@ -298,7 +299,7 @@ function pullRequestMarkdownContext( threadRef: ScopedThreadRef | null, ) { return { - remarkPlugins: pullRequestMarkdownPlugins(detail), + extensions: pullRequestMarkdownExtensions(detail), lineBreaks: sourceControlClients.find(detail?.provider ?? "")?.hardLineBreaks ?? false, threadRef, repository: detail?.repository ?? null, @@ -1578,6 +1579,7 @@ export function PullRequestDetailPanel({
{detail ? ( + {detail.visibility === "private" ? : null} {context === "page" ? ( + {entry.visibility === "private" ? ( + + ) : null} {entry.checksState === undefined ? null : ( { if (!filtersOpen) return NO_LIST_TARGETS; return environmentQueries.map(({ environmentId, projectIds }) => ({ diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts index 4f25b26f3276e..3d0ae22b15017 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.test.ts @@ -1280,6 +1280,15 @@ describe("adding a remark to the chat", () => { }); expect(context?.text).toBe("octocat: This leaks the token.\n\n```html\n\n```"); + // A stray backtick before the comment opens no code span across the paragraphs. + const stray = buildPullRequestCommentContext(pullRequest, { + kind: "comment", + comment: remark( + "c2", + "Avoid `foo.\n\n\nSee `bar` and `` a ` ``.", + ), + }); + expect(stray?.text).toBe("octocat: Avoid `foo.\n\nSee `bar` and `` a ` ``."); }); it("keeps comments inside a quoted fence as code", () => { diff --git a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts index 238038730b93f..d98ec3ff114ec 100644 --- a/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestDetail.logic.ts @@ -5,8 +5,9 @@ import { resolvePullRequestReviewAnchor, } from "@t3tools/shared/pullRequestAnchor"; import { stripInlineContextReferences } from "~/lib/composerContextReferences"; -import type { Nodes as MdastNodes } from "mdast"; -import { fromMarkdown } from "mdast-util-from-markdown"; +import type { Nodes } from "hast"; + +import { markdownHtmlComments, markdownTree } from "~/markdown/wordsHast"; import { sourceControlClients, type ChangeRequestTerminology, @@ -693,27 +694,18 @@ export function pagePullRequestConversationItems( function readableBody(raw: string): string | null { if (visibleBody(raw) === null) return null; const body = raw.replace(/\r\n?/gu, "\n"); - const cuts: Array<[number, number]> = []; - const visit = (node: MdastNodes) => { - if (node.type === "html" && node.position?.start.offset !== undefined) { - cuts.push([node.position.start.offset, node.position.end.offset ?? body.length]); - } - if ("children" in node) for (const child of node.children) visit(child); - }; - visit(fromMarkdown(body)); let readable = ""; let from = 0; - for (const [start, end] of cuts) { + for (const { start, end } of markdownHtmlComments(body)) { + // A comment opened inside another one ends with it. + if (start < from) continue; readable += body.slice(from, start); - // An HTML block can carry markup around its comment; only the comment itself is hidden. - const html = body.slice(start, end).replace(/|$)/gu, ""); // A line that was all comment is dropped rather than left as a blank one. const ownLine = /(?:^|\n)[ \t>]*$/u.test(readable) && /^[ \t]*(?:\n|$)/u.test(body.slice(end)); - if (ownLine && html.trim() === "") { + if (ownLine) { readable = readable.replace(/[ \t>]*$/u, ""); from = end + (/^[ \t]*\n/u.exec(body.slice(end))?.[0].length ?? 0); } else { - readable += html; from = end; } } @@ -740,11 +732,12 @@ const LINK_EXCERPT_LENGTH = 280; /** The words of a markdown body, without markup, HTML or images, for a short preview. */ function markdownExcerpt(body: string): string | null { const words: string[] = []; - const visit = (node: MdastNodes) => { - if (node.type === "text" || node.type === "inlineCode") words.push(node.value); - if (node.type !== "code" && "children" in node) for (const child of node.children) visit(child); + const visit = (node: Nodes) => { + if (node.type === "text") words.push(node.value); + if (node.type === "element" && node.tagName === "pre") return; + if ("children" in node) for (const child of node.children) visit(child); }; - visit(fromMarkdown(body)); + visit(markdownTree(body, { skipHtml: true })); // GitHub's alert marker (`> [!NOTE]`) parses as text but reads as markup. const text = words .join(" ") diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts index dfa31d4dbcd6b..e14d24e7c23b7 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.test.ts @@ -17,6 +17,7 @@ import { findScopedProject, mergePullRequestLists, pullRequestEntryKey, + pullRequestListAnsweredEmpty, groupPullRequestsByInvolvement, pullRequestStatsBatches, pullRequestStatsKeysToRequest, @@ -552,6 +553,18 @@ describe("merging the environments' own listings", () => { expect(merged?.errors).toEqual([{ ...error, environmentId: ENV_1 }]); }); + it("counts a listing with no rows as empty even when a project could not be read", () => { + const error = { + projectId: "project-1" as ProjectId, + projectTitle: "Web", + message: "acme/web could not be read.", + } as const; + const data = mergePullRequestLists([[ENV_1, answer({ errors: [error] })]]); + + expect(pullRequestListAnsweredEmpty({ data, isPending: false, error: null })).toBe(true); + expect(pullRequestListAnsweredEmpty({ data, isPending: true, error: null })).toBe(false); + }); + it("folds a host reached from two environments into one switcher row", () => { const merged = mergePullRequestLists([ [ENV_1, answer()], diff --git a/apps/web/src/components/pullRequest/pullRequestList.logic.ts b/apps/web/src/components/pullRequest/pullRequestList.logic.ts index 15478d82fddf0..55daa5d2680c7 100644 --- a/apps/web/src/components/pullRequest/pullRequestList.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestList.logic.ts @@ -589,6 +589,15 @@ export function mergePullRequestLists( }; } +/** Project errors do not count: the priority reads cover the same projects and are skipped here. */ +export function pullRequestListAnsweredEmpty(view: { + readonly data: MergedPullRequestList | null; + readonly isPending: boolean; + readonly error: unknown; +}): boolean { + return view.data?.entries.length === 0 && !view.isPending && view.error === null; +} + export const pullRequestEnvironmentSetKey = (environmentIds: ReadonlyArray): string => [...environmentIds].sort((left, right) => left.localeCompare(right)).join(","); diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts index 1655427b2d4e9..7c4ffac84b8a5 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.test.ts @@ -1,45 +1,44 @@ -import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-markdown"; -import remarkParse from "remark-parse"; -import { unified } from "unified"; +import type { Element, Root } from "hast"; import { describe, expect, it } from "vite-plus/test"; +import { wordsHast } from "~/markdown/wordsHast"; import { pullRequestCommentPreview, - pullRequestMarkdownPlugins, - remarkPullRequestAutolinks, + pullRequestMarkdownExtensions, } from "./pullRequestMarkdown.logic"; -type Node = { - type: string; - value?: string; - url?: string; - data?: { hProperties?: Record }; - children?: Node[]; -}; - function links(markdown: string) { - const autolinks = changeRequestReferenceAutolinker({ + const extensions = pullRequestMarkdownExtensions({ provider: "github", url: "https://github.com/team/repo/pull/8", - })!; - const tree = unified().use(remarkParse).parse(markdown) as Node; - remarkPullRequestAutolinks({ autolinks })(tree as never); - const found: Array<[string | undefined, string | undefined, unknown]> = []; - const visit = (node: Node) => { - if (node.type === "link") { - found.push([ - node.children?.[0]?.value, - node.url, - node.data?.hProperties?.["dataPullRequestAutolink"], - ]); + }); + const tree = wordsHast(markdown, { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const found: Array<[string, unknown, unknown]> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "a") { + const label = child.children[0]; + found.push([ + label?.type === "text" ? label.value : "", + child.properties.href, + child.properties.dataPullRequestAutolink, + ]); + } + visit(child); } - node.children?.forEach(visit); }; visit(tree); return found; } -describe("remarkPullRequestAutolinks", () => { +describe("pullRequestMarkdownExtensions", () => { it("links the host's references in prose and leaves links and code alone", () => { expect(links("Fixes #12 in **abcdef1**. [#13](https://example.com) `#14`")).toEqual([ ["#12", "https://github.com/team/repo/issues/12", "reference"], @@ -47,22 +46,25 @@ describe("remarkPullRequestAutolinks", () => { ["#13", "https://example.com", undefined], ]); }); -}); - -describe("pullRequestMarkdownPlugins", () => { it("renders GitHub emoji shortcodes in prose and leaves code literal", () => { - const processor = unified() - .use(remarkParse) - .use( - pullRequestMarkdownPlugins({ - provider: "github", - url: "https://github.com/team/repo/pull/8", - }), - ); - const tree = processor.runSync(processor.parse("Ship it :tada: :+1: `:tada:`")) as Node; - const text = (node: Node): string => - (node.type === "inlineCode" ? `\`${node.value}\`` : (node.value ?? "")) + - (node.children ?? []).map(text).join(""); + const extensions = pullRequestMarkdownExtensions({ + provider: "github", + url: "https://github.com/team/repo/pull/8", + }); + const tree = wordsHast("Ship it :tada: :+1: `:tada:`", { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions, + }); + const text = (node: Root | Element | Root["children"][number]): string => { + if (node.type === "text") return node.value; + if (node.type === "element" && node.tagName === "code") { + return `\`${node.children.map(text).join("")}\``; + } + return "children" in node ? node.children.map(text).join("") : ""; + }; expect(text(tree)).toBe("Ship it 🎉 👍 `:tada:`"); }); }); diff --git a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts index 21f3574838e06..560b6ee03fd37 100644 --- a/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts +++ b/apps/web/src/components/pullRequest/pullRequestMarkdown.logic.ts @@ -1,130 +1,63 @@ -import { - changeRequestReferenceAutolinker, - expandGithubEmojiAliases, - resolveChangeRequestMediaUrl, -} from "@t3tools/client-runtime/pull-request-markdown"; -import { - sourceControlClients, - type ReferenceAutolink, -} from "@t3tools/client-runtime/source-control-clients"; -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { changeRequestReferenceAutolinker } from "@t3tools/client-runtime/pull-request-references"; +import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import type { Nodes } from "hast"; -import remarkParse from "remark-parse"; -import remarkRehype from "remark-rehype"; -import { unified, type PluggableList } from "unified"; -export { - splitPullRequestBody, +import { + splitPullRequestBody as splitBody, type PullRequestBodySegment, } from "@t3tools/client-runtime/pull-request-markdown"; +import { + markdownReferenceDefinitions, + wordsHast, + type MarkdownExtensions, +} from "~/markdown/wordsHast"; -type MarkdownNode = { - type: string; - value?: string; - children?: MarkdownNode[]; - url?: string; - data?: unknown; -}; - -const AUTOLINK_IGNORED_TYPES = new Set(["link", "linkReference"]); - -export function remarkPullRequestAutolinks(options: { - readonly autolinks: (text: string) => ReadonlyArray; -}) { - const visit = (node: MarkdownNode): void => { - const children = node.children; - if (children === undefined) return; - for (let index = 0; index < children.length; index += 1) { - const child = children[index]!; - if (AUTOLINK_IGNORED_TYPES.has(child.type)) continue; - if (child.type !== "text" || child.value === undefined) { - visit(child); - continue; - } - const value = child.value; - const links = options.autolinks(value); - if (links.length === 0) continue; - const replacements: MarkdownNode[] = []; - let start = 0; - for (const link of links) { - if (start < link.index) { - replacements.push({ type: "text", value: value.slice(start, link.index) }); - } - replacements.push({ - type: "link", - url: link.url, - data: { hProperties: { dataPullRequestAutolink: link.kind } }, - children: [{ type: "text", value: link.label }], - }); - start = link.index + link.text.length; - } - if (start < value.length) replacements.push({ type: "text", value: value.slice(start) }); - children.splice(index, 1, ...replacements); - index += replacements.length - 1; - } - }; - return (tree: MarkdownNode) => visit(tree); -} +export type { PullRequestBodySegment }; -function remarkChangeRequestMediaUrls(options: { readonly changeRequestUrl: string }) { - const visit = (node: MarkdownNode): void => { - if ((node.type === "image" || node.type === "definition") && node.url !== undefined) { - node.url = resolveChangeRequestMediaUrl(node.url, options.changeRequestUrl); - } - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); +export function splitPullRequestBody(body: string): ReadonlyArray { + return splitBody(body, markdownReferenceDefinitions); } -/** GitHub renders `:alias:` emoji in prose; code keeps them, being `inlineCode`/`code`, not `text`. */ -function remarkGithubEmoji() { - const visit = (node: MarkdownNode): void => { - if (node.type === "text" && node.value !== undefined) - node.value = expandGithubEmojiAliases(node.value); - node.children?.forEach(visit); - }; - return (tree: MarkdownNode) => visit(tree); -} - -const NO_PLUGINS: PluggableList = []; -const markdownPlugins = new Map(); +const NO_EXTENSIONS: MarkdownExtensions = {}; +const markdownExtensions = new Map(); /** - * One plugin list per repository, so every comment of a pull request shares one markdown + * One extension object per repository, so every comment of a pull request shares one markdown * renderer and its parse cache instead of parsing again on each render. */ -export function pullRequestMarkdownPlugins( +export function pullRequestMarkdownExtensions( changeRequest: { readonly provider: string; readonly url: string } | null, -): PluggableList { - if (changeRequest === null) return NO_PLUGINS; +): MarkdownExtensions { + if (changeRequest === null) return NO_EXTENSIONS; const repositoryUrl = sourceControlClients.parseChangeRequestUrl(changeRequest.url)?.link .repositoryUrl; - if (repositoryUrl === undefined) return NO_PLUGINS; + if (repositoryUrl === undefined) return NO_EXTENSIONS; const key = `${changeRequest.provider}\u0000${repositoryUrl}`; - let plugins = markdownPlugins.get(key); - if (plugins === undefined) { - const autolinks = changeRequestReferenceAutolinker(changeRequest); - plugins = [[remarkChangeRequestMediaUrls, { changeRequestUrl: repositoryUrl }]]; - if (changeRequest.provider === "github") plugins.push(remarkGithubEmoji); - if (autolinks) plugins.push([remarkPullRequestAutolinks, { autolinks }]); - markdownPlugins.set(key, plugins); + let extensions = markdownExtensions.get(key); + if (extensions === undefined) { + extensions = { + changeRequest: { + repositoryUrl, + autolinks: changeRequestReferenceAutolinker(changeRequest), + }, + githubEmoji: changeRequest.provider === "github", + }; + markdownExtensions.set(key, extensions); } - return plugins; + return extensions; } -const commentPreviewProcessor = (plugins: PluggableList) => - unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(plugins) - .use(remarkRehype, { allowDangerousHtml: true }) - .use(CHAT_MARKDOWN_REHYPE_PLUGINS) - .freeze(); -const commentPreview = commentPreviewProcessor(NO_PLUGINS); -const githubCommentPreview = commentPreviewProcessor([remarkGithubEmoji]); +const PREVIEW_MARKDOWN = { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions: NO_EXTENSIONS, +}; +const GITHUB_PREVIEW_MARKDOWN = { + ...PREVIEW_MARKDOWN, + extensions: { githubEmoji: true }, +}; const PREVIEW_BLOCK_TAGS = new Set([ "blockquote", @@ -164,7 +97,6 @@ function commentPreviewText(node: Nodes): string { } export function pullRequestCommentPreview(body: string, provider: string): string { - const processor = provider === "github" ? githubCommentPreview : commentPreview; - const tree = processor.runSync(processor.parse(body), body); - return commentPreviewText(tree).replace(/\s+/gu, " ").trim(); + const options = provider === "github" ? GITHUB_PREVIEW_MARKDOWN : PREVIEW_MARKDOWN; + return commentPreviewText(wordsHast(body, options)).replace(/\s+/gu, " ").trim(); } diff --git a/apps/web/src/components/settings/EnvironmentsMap.tsx b/apps/web/src/components/settings/EnvironmentsMap.tsx index befa3c5e19b68..5d4b2f96754c8 100644 --- a/apps/web/src/components/settings/EnvironmentsMap.tsx +++ b/apps/web/src/components/settings/EnvironmentsMap.tsx @@ -1044,7 +1044,7 @@ function FleetCanvas({ )}
{/* Below the canvas, not over it: nothing on the map can end up under the controls. */} -
+
0} />
@@ -275,19 +297,22 @@ function ProjectBindings({ if (held && !saving && !refreshing && !refreshFailed) setPicks({}); const busy = saving || (held && refreshing); const bound = (projectId: ProjectId) => - picks[projectId] ?? boundIssueTrackerScopes(tracker.tracker, bindings[projectId]); + picks[projectId] ?? boundIssueTrackerScopes(tracker, bindings[projectId]); if (projects.length === 0 || !hasIssueTrackerTeams(tracker, bindings)) return null; const change = async (projectId: ProjectId, scopes: ReadonlyArray) => { if (busy) return; - const binding = issueTrackerBindingFor(tracker.tracker, bound(projectId), scopes); + const binding = issueTrackerBindingFor(tracker, bound(projectId), scopes); const before = picks[projectId]; setSaving(true); setPicks((current) => ({ ...current, - [projectId]: boundIssueTrackerScopes(tracker.tracker, binding ?? undefined), + [projectId]: boundIssueTrackerScopes(tracker, binding ?? undefined), })); - const result = await bind({ environmentId, input: { projectId, binding } }); + const result = await bind({ + environmentId, + input: issueTrackerBindInput(projectId, tracker, binding), + }); if (result._tag !== "Success") setPicks((current) => ({ ...current, [projectId]: before })); setSaving(false); }; @@ -302,7 +327,7 @@ function ProjectBindings({ )} /> {projects.map((project) => { - // A project bound to another tracker keeps that binding; this picker shows it unbound. + // A project bound to another tracker or account keeps that binding; this picker shows it unbound. const value = bound(project.id); const options = issueTrackerScopeOptions(tracker, value); return ( @@ -359,3 +384,49 @@ function ProjectBindings({ ); } + +/** A credential for another account of the tracker, kept beside this one. */ +function AddAccountRow({ + tracker, + onAdd, +}: { + readonly tracker: IssueTrackerConnection; + readonly onAdd: (token: string) => Promise; +}) { + const gt = useGT(); + const [adding, setAdding] = useState(false); + const inputId = `issue-tracker-${tracker.tracker}-add-account`; + if (!adding) { + return ( + setAdding(true)}> + + Add account + + } + /> + ); + } + return ( + {tracker.credential.label}} + description={gt("For the new {tracker} account.", { tracker: tracker.displayName })} + control={ + { + if (next.trim()) void onAdd(next.trim()).then((added) => added && setAdding(false)); + }} + /> + } + /> + ); +} diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts index 4468d0ee66a14..64984a238c251 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts @@ -14,6 +14,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, shortcutToKeybindingInput, + shortcutToKeybindingParts, unknownWhenVariables, whenAstToExpression, } from "./KeybindingsSettings.logic"; @@ -250,6 +251,15 @@ describe("KeybindingsSettings.logic", () => { ).toBe("mod+m"); }); + it("keeps a literal plus key as its own part", () => { + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod++")!)).toEqual(["mod", "+"]); + expect(shortcutToKeybindingParts(parseKeybindingShortcut("mod+shift++")!)).toEqual([ + "mod", + "shift", + "+", + ]); + }); + it("serializes shortcuts and when expressions for upserts", () => { expect( shortcutToKeybindingInput({ diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts index 29a3476f7a3c9..4e5f68fabbb58 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -91,7 +91,7 @@ export const DEFAULT_WHEN_VARIABLE = ) ?? "terminalFocus"; const KNOWN_WHEN_VARIABLES = new Set(DEFAULT_WHEN_VARIABLES); -export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { +export function shortcutToKeybindingParts(shortcut: KeybindingShortcut): ReadonlyArray { const parts: string[] = []; if (shortcut.modKey) parts.push("mod"); if (shortcut.metaKey) parts.push("meta"); @@ -99,7 +99,11 @@ export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string if (shortcut.altKey) parts.push("alt"); if (shortcut.shiftKey) parts.push("shift"); parts.push(shortcut.key === " " ? "space" : shortcut.key === "escape" ? "esc" : shortcut.key); - return parts.join("+"); + return parts; +} + +export function shortcutToKeybindingInput(shortcut: KeybindingShortcut): string { + return shortcutToKeybindingParts(shortcut).join("+"); } export function whenAstToExpression(node: KeybindingWhenNode | undefined): string { diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 0bbeda05b1990..ebf45fe0f62a4 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.tsx +++ b/apps/web/src/components/settings/KeybindingsSettings.tsx @@ -28,6 +28,7 @@ import { AuthOrchestrationOperateScope, AuthSettingsWriteScope, type KeybindingCommand, + type KeybindingShortcut, type KeybindingWhenNode, type ServerRemoveKeybindingInput, type ServerUpsertKeybindingInput, @@ -86,6 +87,7 @@ import { keybindingFromKeyboardEvent, parseWhenExpressionDraft, groupKeybindingRows, + shortcutToKeybindingParts, type KeybindingCommandOption, type KeybindingGroup, type KeybindingRow, @@ -101,35 +103,34 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { useAtomCommand } from "../../state/use-atom-command"; import { withoutUnusedCommands } from "../../fork/workArea/retiredCommands"; -function KeybindingPill({ value }: { value: string }) { - // Keys dedupe repeated parts; a literal "+" in a shortcut splits into empty strings. - const seenParts = new Map(); - const parts = value.split("+").map((part) => { - const seen = seenParts.get(part) ?? 0; - seenParts.set(part, seen + 1); - return { part, key: seen === 0 ? part : `${part}-${seen}` }; - }); +function KeybindingPill({ shortcut }: { shortcut: KeybindingShortcut }) { + const isMac = navigator.platform.toLowerCase().includes("mac"); + const parts = shortcutToKeybindingParts(shortcut); + const modifierParts = parts.slice(0, -1); + const keyPart = parts.at(-1); + return ( - {parts.map(({ part, key }) => ( - + {modifierParts.map((part) => ( + {part === "mod" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "⌘" : "Ctrl" : part === "shift" ? "⇧" : part === "alt" - ? navigator.platform.toLowerCase().includes("mac") + ? isMac ? "⌥" : "Alt" : part === "ctrl" ? "⌃" - : part.length === 1 - ? part.toUpperCase() - : part} + : part} ))} + {keyPart !== undefined ? ( + {keyPart.length === 1 ? keyPart.toUpperCase() : keyPart} + ) : null} ); } @@ -916,7 +917,7 @@ function KeybindingKeyControl({ Unassigned ) : ( - + )} ) : ( diff --git a/apps/web/src/components/settings/LabsSettingsPanel.tsx b/apps/web/src/components/settings/LabsSettingsPanel.tsx index 293435976974a..f6354fb880ea0 100644 --- a/apps/web/src/components/settings/LabsSettingsPanel.tsx +++ b/apps/web/src/components/settings/LabsSettingsPanel.tsx @@ -1,16 +1,23 @@ +import { msg } from "gt-react"; import { managedCapabilityDenial } from "@t3tools/client-runtime/contract-labels"; import { useAuth } from "@clerk/react"; import { Link } from "@tanstack/react-router"; +import { AgentFeedbackMode } from "@t3tools/contracts"; import { T, useGT, useMessages } from "gt-react"; import { hasCloudPublicConfig } from "~/cloud/publicConfig"; import { useT3ConnectAuthPrompt } from "../clerk/useT3ConnectAuthPrompt"; import { Button } from "../ui/button"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; import { Switch } from "../ui/switch"; import { ScopedSwitch } from "./ScopedSwitch"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout"; import { useSearchableSetting } from "./settingsSearch"; -import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings"; +import { + useScopedSettings, + useScopedSettingsMixed, + useUpdateScopedSettings, +} from "./useScopedSettings"; import { useOptionalSettingsScope, useSettingsScope } from "./SettingsScopeContext"; import { firstManagedDenial, usePrimaryManagedPolicy } from "~/state/managedPolicy"; @@ -24,9 +31,11 @@ export function LabsSettingsPanel() { {/* Clerk is only mounted when this build has T3 Connect. */} {hasCloudPublicConfig() ? : } + + ); @@ -186,6 +195,31 @@ function LinkedEnvironmentsRow() { ); } +function WorkflowsRow() { + const searchableSetting = useSearchableSetting(); + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const gt = useGT(); + return ( + updateSettings({ workflowsEnabled: Boolean(checked) })} + aria-label={gt("Workflows")} + /> + } + /> + ); +} + function PromptSuggestionsRow() { const searchableSetting = useSearchableSetting(); const settings = useScopedSettings(); @@ -291,3 +325,74 @@ function FastWorktreeCheckoutRow() { /> ); } + +/** Shows only when every machine in scope honors it; older servers drop the setting. */ +const AGENT_FEEDBACK_MODES = AgentFeedbackMode.literals; +const AGENT_FEEDBACK_MODE_LABELS: Record = { + off: msg("Off"), + "on-request": msg("When I ask"), + auto: msg("Automatic"), +}; +const AGENT_FEEDBACK_MODE_DESCRIPTIONS: Record = { + off: msg("Agents send no feedback to the T3 team."), + "on-request": msg( + "When you ask, agents show you a short report about T3 Code and send it to the T3 team if you approve.", + ), + auto: msg( + "Agents also report T3 Code problems they hit on their own, such as a T3 tool that failed.", + ), +}; + +function AgentFeedbackRow() { + const searchableSetting = useSearchableSetting(); + const { scope, connectedEnvironments } = useSettingsScope(); + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + const gt = useGT(); + const m = useMessages(); + const mixed = useScopedSettingsMixed(["agentFeedback"]); + if ( + scope.kind === "project" || + scope.kind === "checkout" || + connectedEnvironments.length === 0 || + connectedEnvironments.some( + (environment) => environment.serverConfig?.environment.capabilities.agentFeedback !== true, + ) + ) + return null; + return ( + { + if (mode !== null) updateSettings({ agentFeedback: { mode } }); + }} + > + + + {(mode: AgentFeedbackMode | null) => + mode === null ? gt("Mixed") : m(AGENT_FEEDBACK_MODE_LABELS[mode]) + } + + + + {AGENT_FEEDBACK_MODES.map((mode) => ( + + {m(AGENT_FEEDBACK_MODE_LABELS[mode])} + + ))} + + + } + /> + ); +} diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 954c0e1c4ee3c..5ab6debec7255 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -659,7 +659,7 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu const forget = async () => { const confirmed = await (requestConfirmDialog( gt( - "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", { label: link.label }, ), { variant: "destructive" }, @@ -668,7 +668,18 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu setBusy(true); const result = await unlink({ environmentId, input: { environmentId: link.environmentId } }); setBusy(false); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + if (result._tag === "Success") { + if (result.value.removed && result.value.endedThere !== true) { + toastManager.add({ + type: "warning", + title: gt("{label} did not answer", { label: link.label }), + description: gt( + "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + { label: link.label }, + ), + }); + } + } else if (!isAtomCommandInterrupted(result)) { failureToast(gt("Could not forget the link"), String(squashAtomCommandFailure(result))); } }; diff --git a/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx index ea6868ed3dc93..6ea4694620c23 100644 --- a/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx +++ b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx @@ -338,7 +338,9 @@ function AddTrackedFolderDialog(props: { key={entry.fullPath} type="button" className={rowClassName} - onClick={() => setQuery(appendBrowsePathSegment(query, entry.name))} + onClick={() => + setQuery(appendBrowsePathSegment(browsePath.directoryPath, entry.name)) + } > {entry.name} diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx index 7ba2d17d7291d..417868799a18d 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx @@ -279,4 +279,18 @@ describe("ScheduledTasksSettings", () => { await expect.element(dialog.getByRole("heading", { name: "New task" })).toBeInTheDocument(); await expect.element(name).toHaveValue("My draft"); }); + + it("keeps a new task's draft when the user clicks outside the editor", async () => { + setup(); + await using _screen = await render(); + await userEvent.click(page.getByRole("button", { name: "New task" })); + const dialog = page.getByRole("dialog"); + const name = dialog.getByRole("textbox", { name: "Name" }); + await userEvent.fill(name, "My draft"); + + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + + await expect.element(dialog).toHaveAttribute("data-open"); + await expect.element(name).toHaveValue("My draft"); + }); }); diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index 4f70815684faa..a2ffce32e68cd 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -1270,6 +1270,8 @@ function ScheduledTaskEditorDialog({ return ( { if (!open && !saving) onClose(); }} diff --git a/apps/web/src/components/settings/SnoozePresetsSettings.tsx b/apps/web/src/components/settings/SnoozePresetsSettings.tsx index 6df4eb32e982a..3db8c08dd6924 100644 --- a/apps/web/src/components/settings/SnoozePresetsSettings.tsx +++ b/apps/web/src/components/settings/SnoozePresetsSettings.tsx @@ -17,6 +17,7 @@ import { msg, T, useGT, useLocale, useMessages, Var } from "gt-react"; import { PlusIcon, XIcon } from "lucide-react"; import { useNowMinute } from "../../hooks/useNowMinute"; +import { useFormattingLocale } from "../../i18n/I18nProvider"; import { reconcileSnoozeDraft, sortSnoozeRows } from "./SnoozePresetsSettings.logic"; import { formatShortTimestamp } from "../../timestampFormat"; import { Button } from "../ui/button"; @@ -249,14 +250,15 @@ function SnoozePresetList(props: { }) { const gt = useGT(); const m = useMessages(); + const locale = useFormattingLocale(); const nowMinute = useNowMinute(); const now = new Date(`${nowMinute}Z`); const formatTime = (date: Date) => - formatShortTimestamp(date.toISOString(), props.timestampFormat); + formatShortTimestamp(date.toISOString(), props.timestampFormat, locale); const seenIds = new Set(); const seenWakes = new Set(); const previews = props.presets.map((preset) => { - const resolved = resolveSnoozePreset(preset, now, formatTime, m); + const resolved = resolveSnoozePreset(preset, now, formatTime, m, locale); if (resolved === null) return { tone: "muted", text: gt("Passed for today") } as const; if (seenIds.has(resolved.id)) { return { tone: "muted", text: gt("Duplicate of an option above") } as const; @@ -269,7 +271,7 @@ function SnoozePresetList(props: { return { tone: "menu", label: resolved.label, when: resolved.whenLabel } as const; }); - const menuPresets = resolveSnoozePresets(now, { presets: props.presets, formatTime }, m); + const menuPresets = resolveSnoozePresets(now, { presets: props.presets, formatTime, locale }, m); const repeatedLabels = new Set( menuPresets .map((preset) => preset.label) diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx index 8eecf79f5d33a..fd5b90f9c6c19 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx @@ -157,6 +157,58 @@ it("sizes an oversized theme file just under 1 MB as 1.00 MB", async () => { ); }); +it.each(["failed read", "batch install"])( + "keeps the oversized replacement warning after a superseded %s", + async (earlierImport) => { + using _themes = isolateThemes(); + await using _screen = await render( + {}} + onImported={() => true} + onImportedMany={() => {}} + />, + ); + const earlierRead = Promise.withResolvers(); + const readStarted = Promise.withResolvers(); + const earlierFile = Object.assign(themeFile("Dusk"), { + text() { + readStarted.resolve(); + return earlierRead.promise; + }, + }); + const input = document.querySelector('input[type="file"]')!; + const files = new DataTransfer(); + if (earlierImport === "batch install") files.items.add(themeFile("Dawn")); + files.items.add(earlierFile); + await act(async () => { + input.files = files.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + await readStarted.promise; + }); + await expect.element(page.getByRole("button", { name: "Reading…" })).toBeDisabled(); + await userEvent.upload( + input, + new File([" ".repeat(256 * 1024 + 1)], earlierFile.name, { type: "application/json" }), + ); + const warning = page.getByText(/^That file is/); + await expect.element(warning).toBeVisible(); + + await act(async () => { + if (earlierImport === "batch install") { + earlierRead.resolve(JSON.stringify(theme("Dusk"))); + } else { + earlierRead.reject(new Error("Could not read Dusk")); + } + await earlierRead.promise.catch(() => {}); + }); + + expect(getCustomThemes().map((theme) => theme.label)).toEqual([]); + expect(page.getByRole("alert").element().textContent).toMatch(/^That file is/); + await expect.element(page.getByRole("button", { name: "Choose files" })).toBeEnabled(); + }, +); + function themeJsonc(name: string, background: string) { return `{ // VS Code themes use JSONC even with a .json extension. diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx index 189560efdee9e..aeac23821884f 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.tsx @@ -233,19 +233,20 @@ function ThemeImportBody({ const [isReading, setIsReading] = useState(false); const [isDropTarget, setIsDropTarget] = useState(false); const [conflicts, setConflicts] = useState | null>(null); - // A newer read supersedes an older one still in flight. + // A new file selection supersedes a pending import even if the selection is rejected. const importRequestRef = useRef(0); const isCurrentRequest = (requestId: number) => requestId === importRequestRef.current && !signal.aborted; const readThemeFile = async (file: ImportableThemeFile) => { + const requestId = ++importRequestRef.current; const oversized = describeOversizedThemeFile(file.size); if (oversized) { + setIsReading(false); setError(oversized); return; } - const requestId = ++importRequestRef.current; setIsReading(true); const fileText = await settlePromise(() => file.text()); if (!isCurrentRequest(requestId)) return; diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index b220fff63e1bd..0d615600bd03c 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -170,6 +170,7 @@ describe("searchSettings", () => { "linked-environments", "worktree-reflink", "right-panel-menu", + "agent-feedback", ]); expect(available.map((item) => item.id).filter((id) => gatedIds.has(id))).toEqual([]); }); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 68db2f1524148..13cf7a4885cb4 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -76,6 +76,7 @@ export interface SettingsSearchItem { readonly peerLinksOnly?: boolean; readonly fastWorktreeCheckoutOnly?: boolean; readonly reflinkWorktreesOnly?: boolean; + readonly agentFeedbackOnly?: boolean; readonly textGeneratorsOnly?: boolean; readonly rightPanelMenuOnly?: boolean; readonly secondary?: boolean; @@ -94,6 +95,7 @@ export interface SettingsSearchAvailability { readonly hasPeerLinkHost?: boolean; readonly hasFastWorktreeCheckoutEnvironment?: boolean; readonly hasReflinkWorktreesEnvironment?: boolean; + readonly hasAgentFeedbackEnvironment?: boolean; /** An environment without a provider allow-list, which hides text generators. */ readonly hasTextGeneratorsEnvironment?: boolean; readonly hasPrimaryEnvironment?: boolean; @@ -544,6 +546,7 @@ export const SETTINGS_SEARCH_ITEMS = [ targetId: "boring-sidebar", searchTerms: [msg("beta boring sidebar folder rows multiline branch pull request details")], }, + { id: "tool-call-visibility", title: msg("Tool calls in chat"), @@ -588,6 +591,13 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "environment", searchTerms: [msg("beta link another machine vps peer agents work there delegate")], }, + { + id: "workflows-beta", + title: msg("Workflows"), + to: "/settings/labs", + scope: "environment", + searchTerms: [msg("beta workflow durable runs automation steps schedule webhook folder")], + }, { id: "prompt-suggestions-beta", title: msg("Suggest next prompt"), @@ -1029,6 +1039,16 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/maintenance", searchTerms: [msg("logs traces processes resource history failures spans cpu memory")], }, + { + id: "agent-feedback", + title: msg("Agent feedback"), + to: "/settings/labs", + scope: "environment-defaults", + agentFeedbackOnly: true, + searchTerms: [ + msg("report bug problem t3 team send feedback agents tools automatic when i ask"), + ], + }, { id: "open-source-licenses", title: msg("Open source licenses"), @@ -1610,6 +1630,7 @@ export function getSettingsSearchTargetScope(targetId: string) { title: item.title, scope: item.scope ?? SETTINGS_CATEGORY_SCOPES[item.to], ...(item.requiresThreadAutoSettlement ? { requiresThreadAutoSettlement: true } : {}), + ...(item.agentFeedbackOnly ? { agentFeedbackOnly: true } : {}), } : null; } @@ -1703,6 +1724,7 @@ export function filterAvailableSettingsSearchItems( (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && (!item.reflinkWorktreesOnly || availability.hasReflinkWorktreesEnvironment === true) && + (!item.agentFeedbackOnly || availability.hasAgentFeedbackEnvironment === true) && (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true) && (!item.rightPanelMenuOnly || availability.hasRightPanelMenu === true), diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index d9aaa32be74cf..c5fb1aaa7cdc4 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -52,6 +52,12 @@ export function useAvailableSettingsSearchItems() { environment.connection.phase === "connected" && environment.serverConfig?.environment.capabilities.reflinkWorktrees === true, ) === true; + const hasAgentFeedbackEnvironment = + environments.some( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ) === true; const hasTextGeneratorsEnvironment = environments.some( (environment) => @@ -92,6 +98,7 @@ export function useAvailableSettingsSearchItems() { hasPeerLinkHost, hasFastWorktreeCheckoutEnvironment, hasReflinkWorktreesEnvironment, + hasAgentFeedbackEnvironment, hasTextGeneratorsEnvironment, hasPrimaryEnvironment: primaryEnvironmentId !== null, hasSecretProvidersEnvironment, diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx index 7b7adf7a31ea5..9e2e6a058f220 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx @@ -8,16 +8,24 @@ import { formatAssistantCitationForComposer } from "../../composer-logic"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { SidebarDraftBlock, useSidebarDrafts } from "./SidebarDraftBlock"; -function DraftBlock() { - const { draftIds, routeDraftComposer } = useSidebarDrafts(null, null); +const NO_TERMINAL_LABELS: ReadonlyMap = new Map(); + +function DraftBlock(props: { + routeDraftId?: string | null; + terminalLabels?: ReadonlyMap; +}) { + const routeDraftId = props.routeDraftId ?? null; + const terminalLabels = props.terminalLabels ?? NO_TERMINAL_LABELS; + const { draftIds, routeDraftComposer } = useSidebarDrafts(null, routeDraftId, terminalLabels); return ( @@ -91,3 +99,42 @@ it("keeps draft previews current through edits, promotion and removal", async () await act(() => initial.clearDraftThread(nextDraftId)); await expect.element(row).not.toBeInTheDocument(); }); + +it("lists empty drafts by terminal label while their terminal exists, active or not", async () => { + const initial = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => useComposerDraftStore.setState(initial, true), + }; + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); + const environmentId = EnvironmentId.make("draft-terminal-environment"); + const terminalDraftId = DraftId.make("draft-with-terminal"); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("terminal-project")), + terminalDraftId, + { threadId: ThreadId.make("terminal-thread") }, + ); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("idle-project")), + DraftId.make("draft-without-terminal"), + { threadId: ThreadId.make("idle-thread") }, + ); + + const terminalLabels = new Map([[`${environmentId}:terminal-thread`, "dev"]]); + const block = (routeDraftId: string | null) => ( +
    + +
+ ); + await using screen = await render(block(terminalDraftId)); + const rows = screen.getByTestId("sidebar-draft-row"); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); + + await screen.rerender(block(null)); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); +}); diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 3a4a74bb64f18..e0b0d92a764ac 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -3,6 +3,7 @@ import type { ContextMenuSource } from "@t3tools/contracts"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { T, useGT } from "gt-react"; import { SquarePenIcon, XIcon } from "lucide-react"; import { @@ -12,8 +13,10 @@ import { type MouseEvent as ReactMouseEvent, } from "react"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId } from "@t3tools/contracts"; import { useShallow } from "zustand/react/shallow"; import { cn } from "~/lib/utils"; +import { useTerminalLabelsByThreadKey } from "~/state/terminalSessions"; import { resolveSidebarRowAccessibility } from "../Sidebar.logic"; import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -31,9 +34,41 @@ import { JumpHintBadge, } from "./SidebarThreadRow"; +const EMPTY_COMPOSER_PARTS = { + prompt: "", + images: [], + persistedAttachments: [], + files: [], + terminalContexts: [], + previewAnnotations: [], + reviewComments: [], +} as const; + +/** Terminal labels for draft threads; an unsent draft stays listed while it has a terminal. */ +export function useDraftTerminalLabels(): ReadonlyMap { + const environmentIds = useComposerDraftStore((store) => { + const ids = new Set(); + for (const session of Object.values(store.draftThreadsByThreadKey)) { + if (session.promotedTo == null) ids.add(session.environmentId); + } + return [...ids].toSorted().join("\n"); + }); + return useTerminalLabelsByThreadKey( + environmentIds === "" ? [] : (environmentIds.split("\n") as EnvironmentId[]), + ); +} + +export function draftTerminalLabel( + session: DraftSessionState, + terminalLabels: ReadonlyMap, +): string | null { + return terminalLabels.get(`${session.environmentId}:${session.threadId}`) ?? null; +} + const SidebarDraftRow = memo(function SidebarDraftRow(props: { draftId: DraftId; - composer: ComposerThreadDraftState; + composer: ComposerThreadDraftState | null; + terminalLabel: string | null; project: ProjectFaviconProject | null; projectDisplayName: string | null; isActive: boolean; @@ -46,11 +81,14 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { source: ContextMenuSource, ) => void; }) { - const { composer, draftId, onContextMenu, onDiscard, onNavigate } = props; + const { draftId, onContextMenu, onDiscard, onNavigate } = props; + const composer = props.composer ?? EMPTY_COMPOSER_PARTS; const gt = useGT(); const promptPreview = assistantCitationsToPlainText( - replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + ), ) .trim() .split("\n", 1)[0] ?? ""; @@ -65,9 +103,11 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const preview = promptPreview.length > 0 ? promptPreview - : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { - count: attachmentCount, - }); + : attachmentCount === 0 && props.terminalLabel !== null + ? props.terminalLabel + : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { + count: attachmentCount, + }); const accessibility = resolveSidebarRowAccessibility({ title: preview, statusLabel: gt("Unsent draft"), @@ -174,6 +214,7 @@ function listedDraftComposer(draftId: string | null): ComposerThreadDraftState | export function useSidebarDrafts( scopedProjectKeys: ReadonlySet | null, routeDraftId: string | null, + terminalLabels: ReadonlyMap, ): { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null } { const [frozenRoute, setFrozenRoute] = useState<{ routeDraftId: string | null; @@ -195,10 +236,12 @@ export function useSidebarDrafts( ) { continue; } + // Composer edits stay frozen while open; terminals come and go live. const isListed = - draftKey === routeDraftId + draftTerminalLabel(session, terminalLabels) !== null || + (draftKey === routeDraftId ? routeDraftComposer !== null - : composerDraftHasUserContent(store.draftsByThreadKey[draftKey]); + : composerDraftHasUserContent(store.draftsByThreadKey[draftKey])); if (isListed) listed.push([draftKey, session]); } listed.sort(([, left], [, right]) => right.createdAt.localeCompare(left.createdAt)); @@ -211,6 +254,7 @@ export function useSidebarDrafts( export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null; + terminalLabels: ReadonlyMap; jumpLabelByDraftId: ReadonlyMap | null; projectByKey: ReadonlyMap; projectDisplayNameByKey: ReadonlyMap; @@ -233,8 +277,10 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { const drafts = props.draftIds.flatMap((draftId) => { const session = draftThreadsByThreadKey[draftId]; const composer = - draftId === props.routeDraftId ? props.routeDraftComposer : draftsByThreadKey[draftId]; - return session && composer ? [{ draftId, session, composer }] : []; + (draftId === props.routeDraftId ? props.routeDraftComposer : null) ?? + draftsByThreadKey[draftId] ?? + null; + return session ? [{ draftId, session, composer }] : []; }); if (drafts.length === 0) { return null; @@ -248,6 +294,7 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { key={draftId} draftId={draftId} composer={composer} + terminalLabel={draftTerminalLabel(session, props.terminalLabels)} project={props.projectByKey.get(projectKey) ?? null} projectDisplayName={props.projectDisplayNameByKey.get(projectKey) ?? null} isActive={draftId === props.routeDraftId} diff --git a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx index 85836a5ecf7cf..185f8fc8487a5 100644 --- a/apps/web/src/components/sidebar/SidebarThreadHeader.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadHeader.tsx @@ -1,5 +1,5 @@ import { useGT } from "gt-react"; -import { FolderPlusIcon, SearchIcon, SquarePenIcon, XIcon } from "lucide-react"; +import { SearchIcon, SquarePenIcon, XIcon } from "lucide-react"; import { type ComponentProps, type KeyboardEvent as ReactKeyboardEvent, @@ -16,7 +16,6 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; export interface SidebarThreadHeaderProps { hasProjects: boolean; projectScope: ReactNode; - onNewProject: () => void; onNewThread: (event: ReactMouseEvent) => void; newThreadDisabled: boolean; newThreadShortcutLabel: string | null | undefined; @@ -35,7 +34,6 @@ export interface SidebarThreadHeaderProps { export function SidebarThreadHeader({ hasProjects, projectScope, - onNewProject, onNewThread, newThreadDisabled, newThreadShortcutLabel, @@ -99,14 +97,7 @@ export function SidebarThreadHeader({ ) : null}
- {hasProjects ? ( - <> - {projectScope} - - - - - ) : null} + {hasProjects ? projectScope : null} instanceId !== modelInstanceId) .map((instanceId) => providerEntryByInstanceId.get(instanceId)?.displayName ?? instanceId); @@ -324,6 +326,12 @@ function SidebarThreadTooltip({
) : null} + {worktreePath ? ( +
+ + +
+ ) : null} {branchMismatch ? (
@@ -575,7 +583,7 @@ function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: type SidebarThreadRowProps = { thread: SidebarThreadSummary; // "folder" is a one-line row inside a boring sidebar project folder; - // "folder-multiline" adds the card's branch and PR line under it. + // "folder-multiline" adds the card's environment and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; @@ -598,10 +606,8 @@ type SidebarThreadRowProps = { // Read at click time; a prop would re-render every row on entering or leaving a thread route. readOpensPullRequestsInRightPanel: () => boolean; jumpLabel: string | null; - currentEnvironmentId: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; - scratchMachineLabel: string | null; project: EnvironmentProject | null; projectDisplayName: string | null; providerEntryByInstanceId: ReadonlyMap; @@ -863,9 +869,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ? getTriggerDisplayModelName(selectedModel, providerEntry?.driverKind) : thread.modelSelection.model; - const isRemote = thread.environmentId !== props.currentEnvironmentId; - const showsScratchMachine = !checkoutThread.branch && props.scratchMachineLabel !== null; - const detailsTooltip = ( - - - ) : null; const diff = latestRunDiff(thread); // Only the trailing icons would remain, so the row moves them to the title line instead. const metaLineEmpty = - !checkoutThread.branch && - !showsScratchMachine && + props.environmentLabel === null && prBadge === null && issueBadge === null && diff === null && runningTerminalIds.length === 0; const metaLine = metaLineEmpty ? null : (
- {checkoutThread.branch ? ( - <> - - - - - - ) : showsScratchMachine ? ( + {props.environmentLabel !== null ? ( <> - {props.scratchMachineLabel} + {props.environmentLabel} ) : ( @@ -1305,7 +1294,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP aria-hidden className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" > - {remoteMachineIcon} - {remoteMachineIcon} - {children} + {observeContent ? ( + // Base UI only observes content resizes through Content; minWidth overrides its fit-content default. + + {children} + + ) : ( + children + )} {!hideScrollbars && ( <> diff --git a/apps/web/src/components/ui/shared-tooltip.tsx b/apps/web/src/components/ui/shared-tooltip.tsx new file mode 100644 index 0000000000000..cca4d8a43fd61 --- /dev/null +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -0,0 +1,265 @@ +import { + cloneElement, + createContext, + use, + useEffect, + useId, + useRef, + useState, + type FocusEvent, + type PointerEvent, + type ReactElement, + type ReactNode, +} from "react"; +import { flushSync } from "react-dom"; + +import { Tooltip, TooltipPopup, TooltipTrigger, useTooltipScrollTracker } from "./tooltip"; + +// Base UI's tooltip timing: open after a rest, reopen at once right after another closed. +const OPEN_DELAY_MS = 600; +const REOPEN_WINDOW_MS = 400; +// Time to travel from the trigger into a hoverable popup. +const CLOSE_GRACE_MS = 100; + +interface SharedTooltipContent { + readonly render: () => ReactNode; + /** Comparable key that changes whenever `render()` output changes while open. */ + readonly contentKey?: unknown; + readonly side?: "top" | "bottom" | "left" | "right"; + readonly variant?: "default" | "glass" | "code"; +} + +interface SharedTooltipState extends SharedTooltipContent { + readonly anchor: HTMLElement; + readonly open: boolean; +} + +interface SharedTooltipApi { + show(anchor: HTMLElement, content: SharedTooltipContent, immediate: boolean): void; + refresh(anchor: HTMLElement, content: SharedTooltipContent): void; + hide(anchor: HTMLElement): void; + /** A press closes it at once, as Base UI's closeOnClick does. */ + dismiss(anchor: HTMLElement): void; + holdOpen(): void; +} + +function setAriaDescribedBy(element: HTMLElement, id: string, present: boolean) { + const tokens = (element.getAttribute("aria-describedby") ?? "").split(/\s+/).filter(Boolean); + const next = present + ? tokens.includes(id) + ? tokens + : [...tokens, id] + : tokens.filter((token) => token !== id); + if (next.length > 0) element.setAttribute("aria-describedby", next.join(" ")); + else element.removeAttribute("aria-describedby"); +} + +const SharedTooltipContext = createContext(null); + +/** + * One tooltip for many triggers: a long message would otherwise mount a Base UI tooltip per + * link and file chip, and almost none of them are ever hovered. + */ +export function SharedTooltipProvider({ children }: { children: ReactNode }) { + const popupId = useId(); + const [state, setState] = useState(null); + const timer = useRef | null>(null); + const pending = useRef(null); + const lastClosedAt = useRef(0); + const current = useRef(null); + + const commit = (next: SharedTooltipState | null) => { + current.current = next; + setState(next); + }; + const clearTimer = () => { + if (timer.current !== null) clearTimeout(timer.current); + timer.current = null; + pending.current = null; + }; + const [api] = useState(() => ({ + show(anchor, content, immediate) { + clearTimer(); + // A Root that mounts open skips Base UI's mount transition, so the popup would slide in from (0,0). + if (!current.current) flushSync(() => commit({ ...content, anchor, open: false })); + const open = current.current?.open === true; + const reopen = performance.now() - lastClosedAt.current < REOPEN_WINDOW_MS; + if (immediate || open || reopen) { + commit({ ...content, anchor, open: true }); + return; + } + pending.current = { ...content, anchor, open: true }; + timer.current = setTimeout(() => { + const next = pending.current; + pending.current = null; + if (next) commit(next); + }, OPEN_DELAY_MS); + }, + refresh(anchor, content) { + if (pending.current?.anchor === anchor) { + pending.current = { ...pending.current, ...content }; + } + const active = current.current; + if (!active || active.anchor !== anchor) return; + if ( + active.contentKey === content.contentKey && + active.side === content.side && + active.variant === content.variant + ) { + return; + } + commit({ ...active, ...content }); + }, + hide(anchor) { + if (current.current && current.current.anchor !== anchor) { + clearTimer(); + return; + } + clearTimer(); + timer.current = setTimeout(() => { + if (current.current?.open) lastClosedAt.current = performance.now(); + if (current.current) commit({ ...current.current, open: false }); + }, CLOSE_GRACE_MS); + }, + dismiss(anchor) { + clearTimer(); + if (current.current?.anchor !== anchor) return; + if (current.current.open) lastClosedAt.current = 0; + commit({ ...current.current, open: false }); + }, + holdOpen() { + clearTimer(); + }, + })); + + const activeAnchor = state?.open ? state.anchor : null; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- links the active trigger DOM element to the shared tooltip popup via aria-describedby + useEffect(() => { + if (!activeAnchor) return; + setAriaDescribedBy(activeAnchor, popupId, true); + return () => setAriaDescribedBy(activeAnchor, popupId, false); + }, [activeAnchor, popupId]); + + return ( + + {children} + {state ? ( + { + if (!open) api.hide(state.anchor); + }} + > + api.holdOpen()} + onMouseLeave={() => api.hide(state.anchor)} + > + {state.render()} + + + ) : null} + + ); +} + +export interface SharedTooltipTriggerProps { + onPointerEnter: (event: PointerEvent) => void; + onPointerLeave: (event: PointerEvent) => void; + onFocus: (event: FocusEvent) => void; + onBlur: (event: FocusEvent) => void; + onPointerDown: (event: PointerEvent) => void; +} + +/** Props that show `content` on the shared tooltip, or null outside a SharedTooltipProvider. */ +export function useSharedTooltip(content: SharedTooltipContent): SharedTooltipTriggerProps | null { + const api = use(SharedTooltipContext); + const scrollTracker = useTooltipScrollTracker(); + const anchorRef = useRef(null); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- refreshes an open shared tooltip when its trigger's label changes + useEffect(() => { + if (api && anchorRef.current) api.refresh(anchorRef.current, content); + }, [api, content]); + if (!api) return null; + return { + // Touch never opens it, as Base UI's mouseOnly trigger; taps also send compatibility mouse events. + onPointerEnter: (event) => { + if (event.pointerType === "touch") return; + const trigger = event.currentTarget; + anchorRef.current = trigger; + api.show(trigger, content, false); + // Scrolling the timeline closes it, as it does a TooltipTrigger's. + scrollTracker?.hover(trigger, api, () => api.dismiss(trigger)); + }, + onPointerLeave: (event) => api.hide(event.currentTarget), + // Keyboard focus shows it at once, as Base UI does. + onFocus: (event) => { + if (event.currentTarget.matches(":focus-visible")) { + anchorRef.current = event.currentTarget; + api.show(event.currentTarget, content, true); + } + }, + onBlur: (event) => api.hide(event.currentTarget), + onPointerDown: (event) => api.dismiss(event.currentTarget), + }; +} + +type Handlers = Partial void>>; + +/** The trigger's own handlers run first, then the shared tooltip's. */ +export function withSharedTooltip( + element: ReactElement, + tooltip: SharedTooltipTriggerProps, + children?: ReactNode, +): ReactElement { + const own = element.props as Handlers; + const merged: Record void> = {}; + for (const key of Object.keys(tooltip) as Array) { + const shared = tooltip[key] as (event: never) => void; + const mine = own[key]; + merged[key] = mine + ? (event) => { + mine(event); + shared(event); + } + : shared; + } + return children === undefined + ? cloneElement(element, merged as Partial) + : cloneElement(element, merged as Partial, children); +} + +/** A tooltip on `render`: the shared one inside a SharedTooltipProvider, Base UI's otherwise. */ +export function SharedTooltipTrigger({ + render, + children, + label, + side = "top", + variant, +}: { + render: ReactElement; + children?: ReactNode; + label: ReactNode; + side?: SharedTooltipContent["side"]; + variant?: SharedTooltipContent["variant"]; +}) { + const tooltip = useSharedTooltip({ + render: () => label, + contentKey: label, + side, + ...(variant ? { variant } : {}), + }); + if (tooltip) return withSharedTooltip(render, tooltip, children); + return ( + + {children} + + {label} + + + ); +} diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx index 24d76784e8a5a..344ddcea7f0f1 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -3,41 +3,136 @@ import { page, userEvent } from "vite-plus/test/browser"; import "~/index.css"; import { render } from "../../../test/render"; +import { SharedTooltipProvider, SharedTooltipTrigger } from "./shared-tooltip"; import { Tooltip, TooltipPopup, TooltipScrollDismissArea, TooltipTrigger } from "./tooltip"; +function TimelineAction({ shared }: { shared: boolean }) { + if (shared) { + return ( + + }> + Timeline action + + + ); + } + return ( + + Timeline action + Description + + ); +} + it.each([ - { focus: "mouse", keptOpen: false }, - { focus: "keyboard", keptOpen: true }, -])("scrolling with a $focus-focused hovered trigger keeps it open: $keptOpen", async (c) => { - const onScroll = vi.fn(); + { shared: false, focus: "mouse", keptOpen: false }, + { shared: false, focus: "keyboard", keptOpen: true }, + { shared: true, focus: "mouse", keptOpen: false }, + { shared: true, focus: "keyboard", keptOpen: true }, +])( + "scrolling with a $focus-focused hovered trigger (shared: $shared) keeps it open: $keptOpen", + async (c) => { + const onScroll = vi.fn(); + await using screen = await render( + + +
+ , + ); + const trigger = screen.getByRole("button", { name: "Timeline action" }); + if (c.focus === "mouse") { + // A press closes the tooltip; hovering again reopens it with mouse focus kept. + await userEvent.click(trigger); + await userEvent.unhover(trigger); + } else { + await userEvent.keyboard("{Tab}"); + } + await userEvent.hover(trigger); + await expect.element(trigger).toHaveFocus(); + await expect.element(page.getByText("Description")).toBeVisible(); + + // One pixel keeps the pointer over the trigger, so only the scroll can close it. + screen.getByTestId("timeline").element().scrollTop = 1; + await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); + + if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); + else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); + }, +); + +it("refreshes an open shared tooltip's label and links aria-describedby on focus", async () => { await using screen = await render( - - - Timeline action - Description - -
- , + + }> + Copy + + , ); - const trigger = screen.getByRole("button", { name: "Timeline action" }); - if (c.focus === "mouse") { - // A press closes the tooltip; hovering again reopens it with mouse focus kept. - await userEvent.click(trigger); - await userEvent.unhover(trigger); - } else { - await userEvent.keyboard("{Tab}"); - } - await userEvent.hover(trigger); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.keyboard("{Tab}"); await expect.element(trigger).toHaveFocus(); - await expect.element(page.getByText("Description")).toBeVisible(); + const popup = page.getByText("Copy code"); + await expect.element(popup).toBeVisible(); + const popupId = trigger.element().getAttribute("aria-describedby"); + expect(popupId).toBeTruthy(); + expect(document.getElementById(popupId!)?.textContent).toBe("Copy code"); + + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copied")).toBeVisible(); + + await userEvent.keyboard("{Tab}"); + await vi.waitFor(() => expect(trigger.element().getAttribute("aria-describedby")).toBeNull()); +}); - screen.getByTestId("timeline").element().scrollTop = 20; - await vi.waitFor(() => expect(onScroll).toHaveBeenCalledOnce()); +it("refreshes a pending shared tooltip if its label changes during the open delay", async () => { + await using screen = await render( + + }> + Copy + + , + ); + const trigger = screen.getByRole("button", { name: "Copy" }); + await userEvent.hover(trigger); + await screen.rerender( + + }> + Copy + + , + ); + await expect.element(page.getByText("Copy code")).toBeVisible(); + expect(page.getByText("Copied").query()).toBeNull(); +}); - if (c.keptOpen) await expect.element(page.getByText("Description")).toBeVisible(); - else await expect.element(page.getByText("Description")).not.toBeInTheDocument(); +it("opens a shared tooltip in place the first time", async () => { + await using _screen = await render( + // Away from the corner the unpositioned popup sits in, so a slide from there is a real move. +
+ + }> + Target + + +
, + ); + // Focus opens it at once, while a position transition would still be running. + await userEvent.keyboard("{Tab}"); + await expect.element(page.getByText("Description")).toBeVisible(); + const moving = document + .getAnimations() + .filter((animation) => animation instanceof CSSTransition) + .map((transition) => transition.transitionProperty) + .filter((property) => ["top", "left", "right", "bottom", "transform"].includes(property)); + expect(moving).toEqual([]); }); diff --git a/apps/web/src/components/ui/tooltip.tsx b/apps/web/src/components/ui/tooltip.tsx index 577aa48da87fa..e47a6b8d13afe 100644 --- a/apps/web/src/components/ui/tooltip.tsx +++ b/apps/web/src/components/ui/tooltip.tsx @@ -21,13 +21,13 @@ type TooltipActionsRef = RefObject; // The compiler freezes context values; update hovered tooltips through calls instead of shared ref writes. function createTooltipHoverTracker() { - let hovered: { trigger: HTMLElement; actionsRef: TooltipActionsRef } | null = null; + let hovered: { trigger: HTMLElement; owner: object; close: () => void } | null = null; return { - hover(trigger: HTMLElement, actionsRef: TooltipActionsRef) { - hovered = { trigger, actionsRef }; + hover(trigger: HTMLElement, owner: object, close: () => void) { + hovered = { trigger, owner, close }; }, - release(actionsRef: TooltipActionsRef) { - if (hovered?.actionsRef === actionsRef) hovered = null; + release(owner: object) { + if (hovered?.owner === owner) hovered = null; }, dismissUnfocused() { const tooltip = hovered; @@ -37,8 +37,7 @@ function createTooltipHoverTracker() { return; } hovered = null; - // Base UI also cancels delayed hover opens through this action. - tooltip.actionsRef.current?.close(); + tooltip.close(); }, }; } @@ -96,7 +95,8 @@ function TooltipTrigger(props: TooltipPrimitive.Trigger.Props) { {...props} onMouseEnter={(event) => { props.onMouseEnter?.(event); - tracker.hover(event.currentTarget, actionsRef); + // Base UI also cancels delayed hover opens through this action. + tracker.hover(event.currentTarget, actionsRef, () => actionsRef.current?.close()); }} /> ); @@ -161,4 +161,14 @@ function TooltipPopup({ ); } -export { TooltipProvider, Tooltip, TooltipTrigger, TooltipPopup, TooltipScrollDismissArea }; +/** The enclosing TooltipScrollDismissArea's tracker, for triggers that bypass TooltipTrigger. */ +const useTooltipScrollTracker = () => use(TooltipScrollContext); + +export { + TooltipProvider, + Tooltip, + TooltipTrigger, + TooltipPopup, + TooltipScrollDismissArea, + useTooltipScrollTracker, +}; diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index adb05afb92ebb..326b592e823db 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -519,7 +519,7 @@ export function UsagePage() {
- + {selectedEnvironments.length === 0 ? (

diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts new file mode 100644 index 0000000000000..736aa4648aaf9 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { diskChange, staleAfterSave } from "./WorkflowDefinitionEditor.logic"; + +describe("diskChange", () => { + it.each([ + [ + "a clean editor follows the file", + { source: "B", baseline: "A", dirty: false, saving: null }, + "follow", + ], + [ + "edits over a change are stale", + { source: "B", baseline: "A", dirty: true, saving: null }, + "stale", + ], + [ + "the file it already holds is nothing", + { source: "A", baseline: "A", dirty: true, saving: null }, + "ignore", + ], + [ + "the save's own text is nothing", + { source: "C", baseline: "A", dirty: true, saving: "C" }, + "ignore", + ], + // The disk went A → B → A while C was being saved: back at the baseline, but not what was saved. + [ + "a change back to the baseline during a save is stale", + { source: "A", baseline: "A", dirty: true, saving: "C" }, + "stale", + ], + ] as const)("%s", (_, input, expected) => { + expect(diskChange(input)).toBe(expected); + }); +}); + +describe("staleAfterSave", () => { + it("settles the change the person saved over and keeps a newer one", () => { + const b = { source: "B" }; + expect(staleAfterSave(b, b)).toBeNull(); + const a = { source: "A" }; + expect(staleAfterSave(a, b)).toBe(a); + expect(staleAfterSave(a, null)).toBe(a); + // The disk went B → A → B while the save was out: back at the same text, but a change of its own. + const bAgain = { source: "B" }; + expect(staleAfterSave(bAgain, b)).toBe(bAgain); + }); +}); diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts new file mode 100644 index 0000000000000..c056c6576f061 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.logic.ts @@ -0,0 +1,23 @@ +/** + * What a new version of the file on disk means for an editor holding `baseline`. A change that + * lands while a save is out is never the save's own unless it is the saved text itself. + */ +export function diskChange(input: { + readonly source: string; + readonly baseline: string; + readonly dirty: boolean; + readonly saving: string | null; +}): "follow" | "stale" | "ignore" { + if (input.saving !== null) return input.source === input.saving ? "ignore" : "stale"; + if (input.source === input.baseline) return "ignore"; + return input.dirty ? "stale" : "follow"; +} + +/** One change on disk the person has not settled. Each change is its own, even with the same text. */ +export interface DiskChange { + readonly source: string; +} + +/** The warning after a save: the change the person saved over is settled, any later one stays. */ +export const staleAfterSave = (now: DiskChange | null, overwrote: DiskChange | null) => + now === overwrote ? null : now; diff --git a/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx b/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx new file mode 100644 index 0000000000000..da810dd5c93ac --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowDefinitionEditor.tsx @@ -0,0 +1,575 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { FileContents } from "@pierre/diffs"; +import { Editor, type EditorFactory, type EditorOptions, type Marker } from "@pierre/diffs/edit"; +import { EditProvider, File, Virtualizer } from "@pierre/diffs/react"; +import { type EnvironmentId, type WorkflowDefinitionProblem } from "@t3tools/contracts"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import { useBlocker } from "@tanstack/react-router"; +import { T, useGT, Var } from "gt-react"; +import { FileCode2Icon, PlusIcon } from "lucide-react"; +import { useEffect, useRef, useState, type KeyboardEvent } from "react"; +import { createPortal } from "react-dom"; + +import { requestConfirmDialog } from "../../confirmDialog"; +import { useTheme } from "../../hooks/useTheme"; +import { resolveDiffThemeName } from "../../lib/diffRendering"; +import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting"; +import { isMacPlatform } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; +import { useEditableAfterHighlight } from "../files/useEditableAfterHighlight"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { type DiskChange, diskChange, staleAfterSave } from "./WorkflowDefinitionEditor.logic"; +import { WorkflowsEmpty } from "./WorkflowRunsView"; + +type DefinitionEditor = Editor<"file", undefined, undefined>; +const createEditor: EditorFactory = (editorType, options, editStateKey) => + new Editor(editorType, options, editStateKey); + +const fileOf = (path: string, contents: string, revision: number): FileContents => ({ + name: path, + contents, + cacheKey: `workflow-definition:${path}:${revision}:${contents.length}`, +}); + +/** A problem that names a line, as a squiggle under that line. */ +const markersOf = (problems: ReadonlyArray): Array => + problems.flatMap((problem) => + problem.line === undefined + ? [] + : [ + { + start: { line: problem.line - 1, character: 0 }, + end: { line: problem.line - 1, character: Number.MAX_SAFE_INTEGER }, + severity: "error" as const, + message: problem.message, + source: "workflows", + }, + ], + ); + +function ProblemList({ + title, + problems, +}: { + readonly title: string; + readonly problems: ReadonlyArray; +}) { + return ( +

+

{title}

+
    + {problems.map((problem) => ( +
  • + {problem.line === undefined ? null : ( + + + Line {problem.line}: + {" "} + + )} + {problem.message} +
  • + ))} +
+
+ ); +} + +function Surface({ + environmentId, + name, + path, + source, + revision, + onDisk, + draft, + offline, + onDelete, + onClose, + actions, +}: { + readonly environmentId: EnvironmentId; + readonly name: string; + readonly path: string; + readonly source: string; + readonly revision: number; + /** Why the file on disk is not what runs, when it is not. */ + readonly onDisk: ReadonlyArray; + /** What a file that is not on disk yet starts as. */ + readonly draft?: string; + /** The environment is away: the draft stays, and nothing is sent until it is back. */ + readonly offline: boolean; + /** Take the file away, saying whether it went. Absent where that cannot be done. */ + readonly onDelete?: (() => Promise) | undefined; + /** Leave the file for the list. */ + readonly onClose: () => void; + /** Where in the page's header the file's status and its actions go. */ + readonly actions: HTMLElement | null; +}) { + const { resolvedTheme } = useTheme(); + const gt = useGT(); + const canSave = useAtomValue( + serverEnvironment.saveWorkflowDefinition.permissionAtom(environmentId), + ); + const save = useAtomCommand(serverEnvironment.saveWorkflowDefinition, { + label: "workflow definition save", + }); + // What the draft started from. The file on disk moving past it is someone else's edit. + const [baseline, setBaseline] = useState(source); + // The file as this editor last took note of it, so only a real change on disk is acted on: after + // a save, `source` is still the old text until the server's answer is read again. + const [seen, setSeen] = useState(source); + // The disk text that changed under the person's edits, until they settle it. + const [staleAt, setStaleAt] = useState(null); + const stale = staleAt !== null; + const [shown, setShown] = useState(() => fileOf(path, draft ?? source, revision)); + const [edited, setEdited] = useState(draft ?? null); + const [problems, setProblems] = useState>([]); + // The last save wrote the file, so its problems are why it does not run, not why it was refused. + const [written, setWritten] = useState(false); + const [failure, setFailure] = useState(null); + // The text a save in flight is writing, so its own echo from disk is told from a real change. + const [savingText, setSavingText] = useState(null); + const saving = savingText !== null; + const [savedOnce, setSavedOnce] = useState(false); + const [deleting, setDeleting] = useState(false); + // Set once the file is deleted, so leaving it does not ask about a draft of a file that is gone. + const released = useRef(false); + const [seenRevision, setSeenRevision] = useState(revision); + const editorRef = useRef(null); + const dirty = edited !== null && edited !== baseline; + const adopt = () => { + setBaseline(source); + setShown(fileOf(path, source, revision)); + setEdited(null); + setProblems([]); + setStaleAt(null); + }; + if (source !== seen) { + setSeen(source); + // With nothing of the person's own in the editor, it follows the file. + const change = diskChange({ source, baseline, dirty, saving: savingText }); + if (change === "stale") setStaleAt({ source }); + else if (change === "follow") adopt(); + } + // Why a saved file did not run is old news once the server loads it cleanly. + if (revision !== seenRevision) { + setSeenRevision(revision); + if (written && onDisk.length === 0) setProblems([]); + } + const { ready: editable, onPostRender } = useEditableAfterHighlight(shown); + + const saveNow = async () => { + if (!dirty || saving || deleting || offline || !canSave || edited === null) return; + // Saving over a change on disk that was already shown is a choice. One that lands while this + // save is out is not, and stays shown. + const overwrote = staleAt; + setSavingText(edited); + setFailure(null); + const result = await save({ environmentId, input: { name, source: edited } }); + setSavingText(null); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) setFailure(String(squashAtomCommandFailure(result))); + return; + } + setProblems(result.value.problems); + setWritten(result.value.changed); + if (!result.value.changed) return; + setBaseline(edited); + setStaleAt((now) => staleAfterSave(now, overwrote)); + setSavedOnce(true); + }; + const onKeyDown = (event: KeyboardEvent) => { + const mac = isMacPlatform(navigator.platform); + if (event.key.toLowerCase() !== "s" || !(mac ? event.metaKey : event.ctrlKey)) return; + event.preventDefault(); + void saveNow(); + }; + const deleteNow = async () => { + if (onDelete === undefined || deleting || saving) return; + // Busy from the dialog on, so a save cannot slip in while it asks. + setDeleting(true); + const gone = await onDelete(); + setDeleting(false); + if (!gone) return; + released.current = true; + onClose(); + }; + // Leaving with an unsaved draft, by a link in the app or by closing the tab, asks first. + useBlocker({ + shouldBlockFn: async () => + dirty && + !released.current && + !(await (requestConfirmDialog( + gt("Leave without saving? Your changes to this file are lost."), + { + variant: "destructive", + }, + ) ?? Promise.resolve(false))), + enableBeforeUnload: () => dirty && !released.current, + }); + + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the editor draws markers itself and takes them only through its own method + useEffect(() => { + editorRef.current?.setMarkers(markersOf(problems)); + }, [problems]); + + const editorOptions: EditorOptions<"file", undefined, undefined> = { + onAttach: (editor) => { + editorRef.current = editor; + editor.setMarkers(markersOf(problems)); + }, + onComplete: () => { + editorRef.current = null; + }, + }; + const status = offline + ? gt("Not connected") + : saving + ? gt("Checking…") + : dirty + ? gt("Unsaved changes") + : savedOnce && problems.length === 0 + ? gt("Saved and running") + : null; + + return ( +
+ {actions === null + ? null + : createPortal( + <> + + {canSave || offline ? status : gt("Read-only")} + + {canSave && onDelete !== undefined ? ( + + ) : null} + {canSave ? ( + + ) : null} + , + actions, + )} + {stale ? ( +
+ + The file changed on disk while you were editing. Saving replaces that change. + + +
+ ) : null} + {onDisk.length > 0 && problems.length === 0 ? ( + + ) : null} + {problems.length > 0 ? ( + + ) : null} + {failure === null ? null : ( + + )} + + + setEdited(file.contents)} + options={{ + disableFileHeader: true, + overflow: "scroll", + theme: resolveDiffThemeName(resolvedTheme), + preferredHighlighter: PREFERRED_HIGHLIGHTER, + themeType: resolvedTheme, + onPostRender: (_container, instance, phase) => onPostRender(instance.file, phase), + }} + className="min-h-full" + /> + + +
+ ); +} + +const NEW_FILE = `const { workflow, step, agent, ask, stop } = T3; + +workflow( + "my-workflow", + { version: 1, payload: Schema.Struct({}) }, + Effect.fn(function* () { + // yield* agent("first", { project: "/path/to/project", brief: "What to do." }); + }), +); +`; + +/** + * The files that define this server's workflows: the list of them, or `file` in an editor. A + * `file` the folder does not have yet is a new one, which exists once it is saved. + */ +export default function WorkflowDefinitionEditor({ + environmentId, + file, + away, + onOpen, + actions, +}: { + readonly environmentId: EnvironmentId; + readonly file: string | null; + /** The environment's name while it is not connected. */ + readonly away: string | null; + readonly onOpen: (file: string | null) => void; + readonly actions: HTMLElement | null; +}) { + const query = useEnvironmentQuery( + serverEnvironment.workflowDefinition({ environmentId, input: {} }), + ); + const canChange = useAtomValue( + serverEnvironment.saveWorkflowDefinition.permissionAtom(environmentId), + ); + const remove = useAtomCommand(serverEnvironment.deleteWorkflowDefinition, { + label: "workflow definition delete", + }); + const gt = useGT(); + const [naming, setNaming] = useState(null); + // What the last delete said, on the page it belongs to: the file, or the list once it is gone. + const [refusal, setRefusal] = useState<{ + readonly at: string | null; + readonly problems: ReadonlyArray; + readonly deleted: boolean; + } | null>(null); + // Data already read stays on screen through a failed refresh or a dropped connection. + if (!query.data) { + if (away !== null) { + return ( + + ); + } + if (query.error) { + return ( + + ); + } + return ( +

+ Loading the workflow files… +

+ ); + } + const { directory, single, files, problems, revision } = query.data; + const open = (next: string | null) => { + setRefusal(null); + onOpen(next); + }; + const begin = () => { + const wanted = (naming ?? "").trim(); + if (wanted === "") return; + setNaming(null); + open(/\.(ts|mts|js|mjs)$/.test(wanted) ? wanted : `${wanted}.ts`); + }; + const removeFile = async (target: string) => { + const confirmed = await (requestConfirmDialog( + gt("Delete {file}? The workflows it defines can no longer be started.", { file: target }), + { variant: "destructive" }, + ) ?? Promise.resolve(false)); + if (!confirmed) return false; + const result = await remove({ environmentId, input: { name: target } }); + if (result._tag === "Failure") { + if (!isAtomCommandInterrupted(result)) { + setRefusal({ + at: target, + problems: [{ message: String(squashAtomCommandFailure(result)) }], + deleted: false, + }); + } + return false; + } + const { changed } = result.value; + setRefusal( + result.value.problems.length === 0 + ? null + : { at: changed ? null : target, problems: result.value.problems, deleted: changed }, + ); + return changed; + }; + const refused = refusal !== null && refusal.at === file ? refusal : null; + const between = ( + <> + {away === null ? null : ( +
+ {gt("{name} is not connected. What you write here stays, and saves once it is back.", { + name: away, + })} +
+ )} + {query.error === null || away !== null ? null : ( + + )} + {problems.length === 0 && refused === null ? null : ( + + )} + + ); + + if (file !== null) { + const shown = files.find((candidate) => candidate.name === file) ?? null; + return ( +
+ {between} + + removeFile(file)} + onClose={() => onOpen(null)} + actions={actions} + /> + +
+ ); + } + + return ( +
+ {between} +
+
+
+

+ + Every file in{" "} + + {directory} + {" "} + defines workflows. A change to one is picked up without a restart. + +

+ {single || !canChange ? null : naming === null ? ( + + ) : ( + { + event.preventDefault(); + begin(); + }} + > + setNaming(event.target.value)} + onKeyDown={(event) => { + if (event.key === "Escape") setNaming(null); + }} + /> + + + )} +
+ {files.length === 0 ? ( +

+ + No workflows yet. Make the first file here, or ask an agent to write one in that + folder. + +

+ ) : ( +
    + {files.map((candidate) => ( +
  • + +
  • + ))} +
+ )} +
+
+
+ ); +} diff --git a/apps/web/src/components/workflows/WorkflowPane.tsx b/apps/web/src/components/workflows/WorkflowPane.tsx new file mode 100644 index 0000000000000..e23d5de8a50c7 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowPane.tsx @@ -0,0 +1,179 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { workflowReferenceLabel } from "@t3tools/client-runtime/workflows"; +import { EnvironmentId, ThreadId, type WorkflowRunReference } from "@t3tools/contracts"; +import { useGT } from "gt-react"; +import { BotIcon, Maximize2Icon, XIcon } from "lucide-react"; + +import { cn } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { Button } from "../ui/button"; +import { + activeWorkflowPaneIndex, + closeWorkflowPaneTab, + openWorkflowPaneTab, + type WorkflowPaneState, + type WorkflowPaneTab, +} from "./workflowPane.logic"; +import { + useOpenReferencePage, + WorkflowReferenceMark, + WorkflowReferencePanel, +} from "./WorkflowReferences"; +import WorkflowThreadPane, { + useOpenThreadPage, + WorkflowThreadTabLabel, +} from "./WorkflowThreadPane"; + +/** + * The pane beside a run: a tab per transcript or reference opened from it. Only the tab that + * shows is mounted, so a pane with a chat and two pull requests renders one of them. + */ +export default function WorkflowPane({ + environmentId, + runId, + state, + onChange, +}: { + readonly environmentId: EnvironmentId; + readonly runId: string | null; + readonly state: WorkflowPaneState; + readonly onChange: (next: WorkflowPaneState) => void; +}) { + const gt = useGT(); + const detail = useEnvironmentQuery( + runId === null ? null : serverEnvironment.workflowRun({ environmentId, input: { runId } }), + ); + const openThreadPage = useOpenThreadPage(); + const openReferencePage = useOpenReferencePage(environmentId); + const tabs = state.pane ?? []; + const activeIndex = activeWorkflowPaneIndex(state); + const active = tabs[activeIndex]; + const threadOf = (tab: Extract) => + scopeThreadRef( + tab.env === undefined ? environmentId : EnvironmentId.make(tab.env), + ThreadId.make(tab.thread), + ); + const referenceOf = (tab: Extract) => + detail.data?.references.find( + (reference) => reference.kind === tab.kind && reference.key === tab.key, + ) ?? null; + const activeReference = active === undefined || "thread" in active ? null : referenceOf(active); + const openFull = + active === undefined + ? null + : "thread" in active + ? () => openThreadPage(threadOf(active)) + : activeReference === null + ? null + : openReferencePage(activeReference); + + return ( +
+
+
+ {tabs.map((tab, index) => ( +
+ + +
+ ))} +
+ {openFull === null ? null : ( + + )} + +
+
+ {active === undefined ? null : "thread" in active ? ( + + ) : activeReference !== null ? ( + + ) : ( +

+ {detail.data === null ? gt("Loading…") : gt("This run no longer lists it.")} +

+ )} +
+
+ ); +} + +function ReferenceTabLabel({ + reference, + fallback, +}: { + readonly reference: WorkflowRunReference | null; + readonly fallback: string; +}) { + if (reference === null) return {fallback}; + return ( + <> + + {workflowReferenceLabel(reference)} + + ); +} diff --git a/apps/web/src/components/workflows/WorkflowReferences.tsx b/apps/web/src/components/workflows/WorkflowReferences.tsx new file mode 100644 index 0000000000000..df89ecc7086cf --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowReferences.tsx @@ -0,0 +1,193 @@ +import { + workflowReferenceIssue, + workflowReferenceLabel, + workflowReferencePullRequest, +} from "@t3tools/client-runtime/workflows"; +import type { EnvironmentId, WorkflowRunReference } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { T } from "gt-react"; +import { CircleCheckIcon, CircleDotIcon, ExternalLinkIcon, LinkIcon } from "lucide-react"; + +import { isElectron } from "~/env"; +import { isTerminalFocused } from "../../lib/terminalFocus"; +import { cn } from "../../lib/utils"; +import { ISSUES_PANEL_REF, useRightPanelStore } from "../../rightPanelStore"; +import { IssueDetailPanel } from "../issue/IssueDetailPanel"; +import { readIssueListPreferences } from "../issue/issueListPreferences"; +import { PullRequestDetailPanel } from "../pullRequest/PullRequestDetailPanel"; +import { PULL_REQUEST_STATE_PRESENTATION } from "../pullRequest/pullRequestIcons"; +import { Button } from "../ui/button"; + +/** The mark a reference wears: its kind's icon, in the ink its state has on its own page. */ +function referenceGlyph(reference: WorkflowRunReference) { + if (workflowReferencePullRequest(reference) !== null) { + const state = + reference.state === "closed" || reference.state === "merged" ? reference.state : "open"; + return PULL_REQUEST_STATE_PRESENTATION[state]; + } + if (workflowReferenceIssue(reference) !== null) { + return reference.state === "closed" + ? { + Icon: CircleCheckIcon, + toneClassName: PULL_REQUEST_STATE_PRESENTATION.merged.toneClassName, + } + : { Icon: CircleDotIcon, toneClassName: PULL_REQUEST_STATE_PRESENTATION.open.toneClassName }; + } + return { Icon: LinkIcon, toneClassName: "text-muted-foreground" }; +} + +export function WorkflowReferenceMark({ reference }: { readonly reference: WorkflowRunReference }) { + const glyph = referenceGlyph(reference); + return ; +} + +/** A thing the run touched, as a chip that opens it beside the run. */ +export function WorkflowReferenceChip({ + reference, + open, + small = false, + onOpen, +}: { + readonly reference: WorkflowRunReference; + /** It shows in the pane now, so another click closes it. */ + readonly open: boolean; + /** On a step, where the label is enough. */ + readonly small?: boolean; + readonly onOpen: () => void; +}) { + const label = workflowReferenceLabel(reference); + const title = reference.title === label ? "" : reference.title; + const name = title === "" ? label : `${label} ${title}`; + return ( + + ); +} + +const shortcutContext = () => ({ + terminalFocus: isTerminalFocused(), + terminalOpen: false, + previewFocus: false, + previewOpen: false, + isWeb: !isElectron, + isDesktop: isElectron, +}); + +/** Opens the reference on its own page, where it has the whole window. Null for a kind with none. */ +export function useOpenReferencePage( + environmentId: EnvironmentId, +): (reference: WorkflowRunReference) => (() => void) | null { + const navigate = useNavigate(); + return (reference) => { + const issue = workflowReferenceIssue(reference); + if (issue !== null) { + return () => { + // The Issues page shows the issue its panel has open; the address keeps the list's place. + useRightPanelStore.getState().openIssue(ISSUES_PANEL_REF, { + environmentId, + projectId: issue.projectId, + tracker: issue.tracker, + ...(issue.host === undefined ? {} : { host: issue.host }), + scope: issue.scope, + key: issue.key, + ...(reference.url === null ? {} : { url: reference.url }), + }); + void navigate({ + to: "/issues", + search: { + ...readIssueListPreferences(), + selectedEnvironmentId: environmentId, + selectedProjectId: issue.projectId, + ...(issue.host === undefined ? {} : { selectedHost: issue.host }), + tracker: issue.tracker, + scope: issue.scope, + key: issue.key, + }, + }); + }; + } + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) { + return () => + void navigate({ + to: "/pull-requests", + search: { + involvement: "all", + state: "all", + repository: pullRequest.repository, + number: pullRequest.number, + ...(pullRequest.host === undefined ? {} : { selectedHost: pullRequest.host }), + selectedProjectId: pullRequest.projectId, + selectedEnvironmentId: environmentId, + }, + }); + } + return null; + }; +} + +/** A reference opened beside its run: the Issues or Pull requests page's own view of it. */ +export function WorkflowReferencePanel({ + environmentId, + reference, +}: { + readonly environmentId: EnvironmentId; + readonly reference: WorkflowRunReference; +}) { + const issue = workflowReferenceIssue(reference); + if (issue !== null) { + return ; + } + const pullRequest = workflowReferencePullRequest(reference); + if (pullRequest !== null) { + return ( + + ); + } + // A kind this client does not know yet: what the run knows of it, and where it lives. + return ( +
+

+ {reference.title === "" ? workflowReferenceLabel(reference) : reference.title} +

+

+ + {reference.kind} + {reference.state === null ? null : ( + <> + · + {reference.state} + + )} +

+ {reference.url === null ? null : ( + + )} +
+ ); +} diff --git a/apps/web/src/components/workflows/WorkflowRunFeed.tsx b/apps/web/src/components/workflows/WorkflowRunFeed.tsx new file mode 100644 index 0000000000000..003603a4cfde9 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunFeed.tsx @@ -0,0 +1,1926 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, + type AtomCommandResult, +} from "@t3tools/client-runtime/state/runtime"; +import { + EnvironmentId, + ThreadId, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, +} from "@t3tools/contracts"; +import { formatModelSlugName } from "@t3tools/shared/model"; +import { formatDuration } from "@t3tools/shared/orchestrationTiming"; +import { msg, T, useGT, useMessages, Var } from "gt-react"; +import { + ArrowLeftIcon, + ArrowUpRightIcon, + ChevronRightIcon, + BotIcon, + CheckIcon, + CircleAlertIcon, + HourglassIcon, + MoonIcon, + SquareIcon, +} from "lucide-react"; +import { secondTick } from "@t3tools/client-runtime/clock"; +import { + createContext, + useContext, + useRef, + useState, + useSyncExternalStore, + type ReactNode, +} from "react"; + +import { requestConfirmDialog } from "../../confirmDialog"; +import { useNowMinute } from "../../hooks/useNowMinute"; +import { cn } from "../../lib/utils"; +import { useQuietThreadShell } from "../../state/entities"; +import { useEnvironment, useEnvironmentProviders } from "../../state/environments"; +import { type MessageResolver } from "../../i18n/messages"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { formatRelativeTimeLabel } from "../../timestampFormat"; +import ChatMarkdown from "../ChatMarkdown"; +import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; +import { stackedThreadToast, toastManager } from "../ui/toast"; +import { + buildWorkflowFeed, + buildWorkflowTimeline, + readWorkflowQuestion, + workflowAgentSummary, + workflowAnswer, + workflowChip, + workflowFlowFocus, + workflowPausedBeat, + workflowResultLines, + workflowRunNow, + workflowRunState, + workflowSaidStart, + workflowStepReferences, + workflowStepTime, + workflowOneLine, + type WorkflowBeat, + type WorkflowFeedRow, + type WorkflowQuickSteps, + type WorkflowRunNode, + type WorkflowRunTone, +} from "@t3tools/client-runtime/workflows"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { WorkflowReferenceChip } from "./WorkflowReferences"; + +/** An agent's thread, as a step names it: the linked environment it is in, or null for this one. */ +export interface WorkflowThreadTarget { + readonly threadId: string; + readonly environmentId: string | null; +} + +// An agent that wrote a page gets a few lines of it; the rest is a click away. +const SAID_SHOWN = 320; + +// What waits on a person is what they came for, so it is in view when the run opens. +const revealOnMount = (element: HTMLElement | null) => { + element?.scrollIntoView({ block: "nearest" }); +}; + +function reportFailure(title: string, result: AtomCommandResult) { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + toastManager.add( + stackedThreadToast({ + type: "error", + title, + description: String(squashAtomCommandFailure(result)), + }), + ); +} + +// Reads the minute tick because the compiler caches a render-time Date.now() on the timestamp. +function useNowMs(): number { + return Date.parse(`${useNowMinute()}:00.000Z`); +} + +// A time still counting is told to the second: its tenths would only flicker. +const wholeSeconds = (ms: number) => Math.max(1000, Math.round(ms / 1000) * 1000); +const elapsedOf = (beat: WorkflowBeat) => + beat.status === "running" ? wholeSeconds(beat.endMs - beat.startMs) : beat.endMs - beat.startMs; + +const never = () => () => {}; +const noTick = () => 0; + +/** The clock a run is told by: to the second while it is under way, to the minute after. */ +function useRunNowMs(live: boolean): number { + const minute = useNowMs(); + const second = useSyncExternalStore( + live ? secondTick.subscribe : never, + live ? secondTick.getSnapshot : noTick, + live ? secondTick.getSnapshot : noTick, + ); + return live ? second : minute; +} + +export function RelativeLabel({ value }: { readonly value: string }) { + return formatRelativeTimeLabel(value, useNowMs()); +} + +const CHIP_TONES = [ + "bg-sky-500/15 text-sky-700 dark:text-sky-300", + "bg-violet-500/15 text-violet-700 dark:text-violet-300", + "bg-amber-500/15 text-amber-700 dark:text-amber-300", + "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300", + "bg-rose-500/15 text-rose-700 dark:text-rose-300", +] as const; + +/** Which workflow a run is of, at a glance: the same letters and colour wherever it shows. */ +export function WorkflowChip({ name }: { readonly name: string }) { + const chip = workflowChip(name); + return ( + + {chip.letters} + + ); +} + +// The thread list's own colours for the same states, so a run reads like a thread does. +const WORKFLOW_TONE_CLASS: Record = { + input: "text-warning-foreground", + failed: "text-destructive", + working: "text-info-foreground", + quiet: "text-muted-foreground", + done: "text-success-foreground", +}; + +export function WorkflowStateWord({ node }: { readonly node: WorkflowRunNode }) { + const m = useMessages(); + const state = workflowRunState(node, m); + return ( + + {state.tone === "working" ? ( + + ) : state.tone === "done" ? ( + + ) : null} + {state.word} + + ); +} + +const nthTry = (count: number, resolve: MessageResolver) => + resolve( + msg("{count, plural, =1 {1st try} =2 {2nd try} =3 {3rd try} other {{count}th try}}", { + count, + }), + ); + +// The loading view and the timeline each draw a question's card, so a reason typed while the +// steps load is kept here rather than in the card that is about to be replaced. +const AnswerDrafts = createContext<{ + readonly get: (key: string) => string | null; + readonly set: (key: string, reason: string | null) => void; +} | null>(null); + +export function WorkflowRunFeed({ + environmentId, + node, + parent, + shownTab, + onSelect, + onOpenThread, + onOpenReference, +}: { + readonly environmentId: EnvironmentId; + readonly node: WorkflowRunNode; + readonly parent: WorkflowRun | null; + /** What shows beside the run, so the card or chip that opened it can say so. */ + readonly shownTab: WorkflowPaneTab | null; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + readonly onOpenReference: (reference: WorkflowRunReference) => void; +}) { + const { run } = node; + const gt = useGT(); + const clockMs = useRunNowMs(node.run.endedAt === null); + // An ended run's last step can still read as running for a moment; it ran until the run ended. + const nowMs = node.run.endedAt === null ? clockMs : Date.parse(node.run.endedAt); + const panel = useRef(null); + const [picked, setPicked] = useState(null); + // Steps already there when the run opens are simply shown; only later ones arrive with motion. + const [openedAtMs] = useState(() => Date.now()); + const detail = useEnvironmentQuery( + serverEnvironment.workflowRun({ environmentId, input: { runId: run.runId } }), + ); + const canResume = useAtomValue(serverEnvironment.resumeWorkflowRun.permissionAtom(environmentId)); + const canCancel = useAtomValue(serverEnvironment.cancelWorkflowRun.permissionAtom(environmentId)); + const resume = useAtomCommand(serverEnvironment.resumeWorkflowRun, { label: "workflow resume" }); + const cancel = useAtomCommand(serverEnvironment.cancelWorkflowRun, { label: "workflow cancel" }); + const [busy, setBusy] = useState(false); + const target = { environmentId, input: { runId: run.runId } }; + const [drafts, setDrafts] = useState>(() => new Map()); + const answerDrafts = { + get: (key: string) => drafts.get(key) ?? null, + set: (key: string, reason: string | null) => + setDrafts((current) => { + const next = new Map(current); + if (reason === null) next.delete(key); + else next.set(key, reason); + return next; + }), + }; + const resumeRun = async () => { + if (busy) return; + setBusy(true); + const result = await resume(target); + setBusy(false); + reportFailure(gt("Could not resume the run"), result); + }; + const cancelRun = async () => { + if (busy) return; + // Busy while the dialog is up, so a second click does not open a second one. + setBusy(true); + const confirmed = await (requestConfirmDialog( + gt("Cancel {title}? Its agents stop and the run cannot be resumed.", { title: run.title }), + { variant: "destructive" }, + ) ?? Promise.resolve(false)); + if (!confirmed) return setBusy(false); + const result = await cancel(target); + setBusy(false); + reportFailure(gt("Could not cancel the run"), result); + }; + const ended = run.endedAt !== null; + const ranMs = ended + ? Date.parse(run.endedAt) - Date.parse(run.startedAt) + : wholeSeconds(nowMs - Date.parse(run.startedAt)); + const steps = detail.data?.steps; + const references = detail.data?.references ?? []; + // An open transcript is one thread in one environment; `env` is absent for the run's own. + const openThread = shownTab !== null && "thread" in shownTab ? shownTab : null; + const chip = (reference: WorkflowRunReference, small = false) => ( + onOpenReference(reference)} + /> + ); + const feed = + steps === undefined + ? null + : buildWorkflowFeed( + buildWorkflowTimeline({ + run, + steps, + children: node.children.map((child) => child.run), + nowMs, + }), + ); + const beats = (feed ?? []).flatMap((row) => + row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row], + ); + // A question is told where it was asked. One whose step is not in the list yet still shows. + const questionOf = (beat: WorkflowBeat) => + beat.kind === "ask" && beat.status === "running" + ? (node.questions.find((question) => question.name === beat.name) ?? null) + : null; + const loose = node.questions.filter( + (question) => !beats.some((beat) => questionOf(beat) === question), + ); + const pausedAt = feed === null ? null : workflowPausedBeat(feed, run.status); + const pause = (name: string | null, attempts: number, reason: string | null) => ( + void resumeRun()} + kept={(steps ?? []).some((step) => step.status === "completed")} + /> + ); + const beatCard = (beat: WorkflowBeat) => { + if (beat === pausedAt) { + // The step's own card stays, so its transcript can be read before resuming. + return ( +
+ {pause(beat.name, beat.attempts, beat.detail ?? run.detail)} + {stepCard(beat)} +
+ ); + } + return stepCard(beat); + }; + const stepCard = (beat: WorkflowBeat) => ( + child.run.runId === beat.childRun?.runId) ?? null} + nowMs={nowMs} + open={ + beat.thread !== null && + openThread !== null && + beat.thread.threadId === openThread.thread && + (beat.thread.environmentId ?? undefined) === openThread.env + } + onSelect={onSelect} + onOpenThread={onOpenThread} + /> + ); + const resultLines = workflowResultLines(run.result); + const pausedApart = run.status === "paused" && pausedAt === null; + const keys = new Set([ + ...(feed ?? []).flatMap((row) => (row.kind === "quick" ? [`quick:${row.steps[0]?.name}`] : [])), + ...beats.map((beat) => `step:${beat.name}`), + ...loose.map((question) => `question:${question.name}`), + ...(pausedApart ? ["pause"] : []), + ...(ended ? ["end"] : []), + ]); + // A run that finished opens on what it came to: its result when that says more than the last + // answer, else the last agent's reply. The header already says it is done. + const lastAnswer = beats.findLast((beat) => beat.kind === "ask" && beat.status === "completed"); + const answered = lastAnswer === undefined ? null : workflowAnswer(lastAnswer.result); + const resultSaysMore = + resultLines.length > 0 && + !(resultLines.length === 1 && answered !== null && resultLines[0]?.value === answered.choice); + const latest = (found: ReadonlyArray) => + found.reduce( + (best, beat) => (best === undefined || beat.endMs >= best.endMs ? beat : best), + undefined, + ); + const lastAgent = latest( + beats.filter((beat) => beat.kind === "agent" && beat.status === "completed"), + ); + const finishedFocus = + run.status !== "completed" || resultSaysMore || lastAgent === undefined + ? "end" + : `step:${lastAgent.name}`; + const focus = + picked !== null && keys.has(picked) + ? picked + : feed === null + ? null + : ended + ? finishedFocus + : workflowFlowFocus({ + rows: feed, + status: run.status, + ended, + questions: node.questions.map((question) => question.name), + }); + const pick = (key: string) => { + const asks = + key.startsWith("question:") || + beats.some((beat) => `step:${beat.name}` === key && questionOf(beat) !== null); + setPicked(asks ? null : key); + // Below the flow on a narrow page, so picking a step brings what it shows into view; a + // question is answered where it is, so the page stays put. + if (!asks) panel.current?.scrollIntoView({ block: "nearest" }); + }; + const endWord = + run.status === "completed" + ? gt("Finished", { $context: "how a workflow run ended" }) + : run.status === "stopped" + ? gt("Stopped", { $context: "how a workflow run ended" }) + : run.status === "skipped" + ? gt("Skipped", { $context: "how a workflow run ended" }) + : gt("Cancelled", { $context: "how a workflow run ended" }); + // A question is answered where it was asked, so beside it is what led up to it. + const asking = + focus !== null && + (focus.startsWith("question:") || + beats.some( + (beat) => + `step:${beat.name}` === focus && + // Answered, its question is gone a moment before the step itself says it is done. + (questionOf(beat) !== null || (beat.kind === "ask" && beat.status === "running")), + )); + // The latest agent's reply is what a person weighs before answering; failing that, the last + // step that left something behind. A sleep or a wait has nothing to say. + const before = asking + ? (latest(beats.filter((beat) => beat.kind === "agent" && beat.status !== "running")) ?? + beats.findLast( + (beat) => + beat.status !== "running" && + beat.kind !== "ask" && + beat.kind !== "sleep" && + beat.kind !== "wait", + ) ?? + null) + : null; + const shown = asking ? (before === null ? null : `step:${before.name}`) : focus; + const shownBeat = beats.find((beat) => `step:${beat.name}` === shown); + const shownQuick = (feed ?? []).find( + (row) => row.kind === "quick" && `quick:${row.steps[0]?.name}` === shown, + ); + + return ( + +
+
+ + {parent === null ? null : ( + + )} +
+

{run.title}

+ + {ended ? null : ( + + )} +
+

+ + {run.workflow} + · + + + started{" "} + + + + + + {run.status === "paused" ? null : ( + <> + · + + {ended + ? gt("took {duration}", { duration: formatDuration(ranMs) }) + : gt("{duration} so far", { duration: formatDuration(ranMs) })} + + + )} + {run.retired ? ( + <> + · + + its version is no longer registered + + + ) : null} +

+ {references.length === 0 ? null : ( +
    + {references.map((reference) => ( +
  • + {chip(reference, reference.title !== "" && run.title.includes(reference.title))} +
  • + ))} +
+ )} +
+ + {detail.error || + feed === null || + (feed.length === 0 && run.status === "paused" && loose.length === 0) ? ( + <> + {detail.error ? ( +

{detail.error}

+ ) : feed === null ? ( +

+ Loading steps… +

+ ) : null} + {/* A question the run already asks is answerable without its step history. */} + {run.status === "paused" ? ( +
+
{pause(null, run.pauses, run.detail)}
+
+ ) : null} + {node.questions.map((question) => ( +
+ +
+ ))} + + ) : ( +
+ +
+ {shownBeat !== undefined ? ( + // Keyed by the step: a reason typed for one question must not follow to the next. +
+ {beatCard(shownBeat)} + {(() => { + // With one reference, the header already says it. + const touched = + references.length > 1 + ? workflowStepReferences(references, shownBeat.name) + : []; + return touched.length === 0 ? null : ( +
+ {touched.map((reference) => chip(reference, true))} +
+ ); + })()} +
+ ) : shownQuick !== undefined && shownQuick.kind === "quick" ? ( + + ) : asking ? null : focus === "pause" ? ( + pause(null, run.pauses, run.detail) + ) : focus === "end" ? ( + + + ) : null + } + name={endWord} + sub={} + /> + {run.status !== "completed" && run.detail ? ( +

{run.detail}

+ ) : null} + +
+ ) : ( +

+ Nothing yet. +

+ )} +
+
+ )} +
+
+ ); +} + +type StepTone = "working" | "input" | "quiet" | "done" | "failed" | "ended"; + +// Colour says what is live: blue for work under way, amber for a person's turn. Done is quiet. +const RING: Record = { + working: "stroke-info", + input: "stroke-warning", + quiet: "stroke-muted-foreground/60", + done: "stroke-muted-foreground/45", + failed: "stroke-destructive", + ended: "stroke-muted-foreground/60", +}; + +const VERB_TONE = { + working: "text-info-foreground", + input: "text-warning-foreground", + quiet: "text-muted-foreground", + failed: "text-destructive", +} as const; + +/** + * A step's place on the rail: a ring, filled while it works, ticked when it is done. `pulse` and + * `draw` never change for a step, so each plays once, when its part of the mark first appears. + */ +function StepMark({ + tone, + pulse, + draw, +}: { + readonly tone: StepTone; + /** It started while the run was open here. */ + readonly pulse: boolean; + /** It ended while the run was open here. */ + readonly draw: boolean; +}) { + const live = tone === "working" || tone === "input"; + return ( + + {live && pulse ? ( + + ) : null} + + + {live || tone === "quiet" ? ( + + ) : tone === "done" ? ( + + ) : tone === "failed" ? ( + + ) : ( + + )} + + + ); +} + +/** One line of the run: its mark on the rail, name, what it is doing, a word on how it went, its time. */ +function TimelineRow({ + tone, + enters, + draw, + lead, + name, + note, + verb, + verbTone = "working", + aside, + asideTone, + duration, + selected, + current = false, + onPick, + sub = false, +}: { + readonly tone: StepTone; + /** It started while the run was open here, so it arrives instead of just being there. */ + readonly enters: boolean; + /** It ended while the run was open here. */ + readonly draw: boolean; + /** A small mark before the name, such as the agent's provider. */ + readonly lead?: ReactNode; + readonly name: string; + /** A quieter word after the name, such as the agent's model. */ + readonly note?: string | null; + readonly verb?: string | null; + readonly verbTone?: keyof typeof VERB_TONE; + readonly aside?: string | null; + readonly asideTone?: "failed"; + readonly duration?: string | null; + readonly selected: boolean; + /** The pane beside the timeline shows it. */ + readonly current?: boolean; + readonly onPick: () => void; + /** A step of a fork, hanging off the branch rather than the rail. */ + readonly sub?: boolean; +}) { + const live = tone === "working" || tone === "input"; + return ( + + ); +} + +/** The rail beside a row: from the row above to this mark, and on to the next unless it is last. */ +function Rail({ first, last }: { readonly first: boolean; readonly last: boolean }) { + return ( + + ); +} + +// A fork leaves the rail under its mark, runs through each step's dot, and rejoins the rail. +// The rail's centre is 10px in and a step's dot 39px in; the mark ends 26px down, the first dot +// sits 46px down, and each dot is 14px below its own row's top. +function BranchOut() { + return ( + + + + ); +} + +function BranchBack() { + return ( + <> + + + + + + ); +} + +/** + * The run as it went, one line per step that took time or involved someone. Steps that ran at once + * hang off a branch. It never draws what comes next: a run can branch, so the rail just goes on. + */ +function WorkflowTimeline({ + environmentId, + rows, + node, + nowMs, + focus, + onPick, + loose, + paused, + end, + question, + onOpenThread, + openedAtMs, + current, +}: { + readonly environmentId: EnvironmentId; + readonly rows: ReadonlyArray; + readonly node: WorkflowRunNode; + readonly nowMs: number; + readonly focus: string | null; + readonly onPick: (key: string) => void; + /** Questions whose step is not in the list yet. */ + readonly loose: ReadonlyArray; + /** The run is paused, and not at a step that failed. */ + readonly paused: boolean; + /** How the run ended, once it has. */ + readonly end: string | null; + /** What it ended with, in a few words. */ + /** The question a step waits on a person for, answered right under it. */ + readonly question: (beat: WorkflowBeat) => WorkflowQuestion | null; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + /** When this run was opened here: only what changes after that arrives with motion. */ + readonly openedAtMs: number; + /** What the pane beside the timeline shows. */ + readonly current: string | null; +}) { + const gt = useGT(); + const completed = node.run.status === "completed"; + const ask = (asked: WorkflowQuestion) => ( +
+ +
+ ); + const beatRow = (beat: WorkflowBeat, sub = false) => ( + child.run.runId === beat.childRun?.runId) ?? null} + asks={node.questions.some((asked) => asked.name === beat.name)} + nowMs={nowMs} + selected={focus === `step:${beat.name}`} + current={current === `step:${beat.name}`} + onPick={() => onPick(`step:${beat.name}`)} + sub={sub} + openedAtMs={openedAtMs} + /> + ); + const items: Array<{ + readonly key: string; + readonly body: ReactNode; + /** Its steps hang off a branch, which carries the rail past them. */ + readonly branch?: boolean; + }> = []; + for (const row of rows) { + if (row.kind === "quick") { + const key = `quick:${row.steps[0]?.name}`; + // Keyed by its first step, as that step's own row was, so regrouping does not remount it. + const itemKey = row.steps[0]?.name ?? key; + const names = row.steps.map((step) => step.name); + items.push({ + key: itemKey, + body: ( + openedAtMs} + name={ + names.length <= 2 + ? names.join(" · ") + : gt("{names} and {count} more", { + names: names.slice(0, 2).join(" · "), + count: names.length - 2, + }) + } + duration={workflowStepTime(Math.max(0, row.endMs - row.startMs))} + selected={focus === key} + current={current === key} + onPick={() => onPick(key)} + /> + ), + }); + continue; + } + if (row.kind === "together") { + const running = row.beats.filter((beat) => beat.status === "running").length; + // Steps that only sleep or wait are under way without working. + const working = row.beats.some( + (beat) => beat.status === "running" && beat.kind !== "sleep" && beat.kind !== "wait", + ); + const failed = row.beats.some((beat) => beat.status === "failed"); + const asks = row.beats.some( + (beat) => beat.status === "running" && node.questions.some((q) => q.name === beat.name), + ); + const startMs = Math.min(...row.beats.map((beat) => beat.startMs)); + const endMs = Math.max(...row.beats.map((beat) => beat.endMs)); + const first = row.beats[0]; + items.push({ + key: first?.name ?? "together", + branch: true, + body: ( + <> +
+ 0 + ? "quiet" + : failed + ? "failed" + : "done" + } + pulse={startMs > openedAtMs} + draw={running === 0 && endMs > openedAtMs} + /> + 0 ? "font-medium" : "text-muted-foreground", + )} + > + {gt("{count} in parallel", { count: row.beats.length })} + + {working ? ( + + {gt("{count} running", { count: running })} + + ) : null} + + {workflowStepTime(running > 0 ? wholeSeconds(endMs - startMs) : endMs - startMs)} + + +
+ +
    + {row.beats.map((beat, index) => { + const firstBeat = index === 0; + const lastBeat = index === row.beats.length - 1; + const asked = question(beat); + return ( +
  1. + + {lastBeat ? : null} + {beatRow(beat, true)} + {asked === null ? null : ask(asked)} +
  2. + ); + })} +
+ + ), + }); + continue; + } + const asked = question(row); + items.push({ + key: row.name, + body: ( + <> + {beatRow(row)} + {asked === null ? null : ask(asked)} + + ), + }); + } + for (const asked of loose) { + // Keyed like its step's row, which replaces it once the step arrives, so it does not arrive twice. + items.push({ + key: asked.name, + body: ( + <> + openedAtMs} + draw={false} + name={asked.name} + verb={gt("Asks you", { $context: "a workflow step waits on a person's answer" })} + verbTone="input" + selected={focus === `question:${asked.name}`} + current={current === `question:${asked.name}`} + onPick={() => onPick(`question:${asked.name}`)} + /> + {ask(asked)} + + ), + }); + } + if (paused) { + items.push({ + key: "pause", + body: ( + onPick("pause")} + /> + ), + }); + } + // A finished run needs no closing row: the header says so, and the last step is the end. + if (end !== null && !completed) { + const endedMs = Date.parse(node.run.endedAt ?? node.run.updatedAt); + items.push({ + key: "end", + body: ( + openedAtMs} + draw={false} + name={end} + aside={node.run.detail} + selected={focus === "end"} + current={current === "end"} + onPick={() => onPick("end")} + /> + ), + }); + } + const live = end === null; + return ( + + ); +} + +function WorkflowBeatRow({ + environmentId, + beat, + child, + asks, + nowMs, + selected, + onPick, + sub, + openedAtMs, + current, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly child: WorkflowRunNode | null; + /** A person's answer is what it waits for. */ + readonly asks: boolean; + readonly nowMs: number; + readonly selected: boolean; + readonly onPick: () => void; + readonly sub: boolean; + readonly openedAtMs: number; + readonly current: boolean; +}) { + const gt = useGT(); + const m = useMessages(); + const threadEnvironmentId = + beat.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(beat.thread.environmentId); + const shell = useQuietThreadShell( + beat.thread === null + ? null + : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), + ); + const provider = useEnvironmentProviders() + .get(threadEnvironmentId) + ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); + const under = beat.status === "running"; + const failed = beat.status === "failed"; + const said = workflowAgentSummary(beat).said; + const answer = beat.kind === "ask" ? workflowAnswer(beat.result) : null; + const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); + // An agent's own approval or question needs a person as much as the workflow's does. + const agentAsks = + beat.kind === "agent" && under && shell !== null + ? shell.hasPendingUserInput + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : shell.hasPendingApprovals + ? gt("waits for your approval") + : null + : null; + // A question waits on a person until its step ends, answered or not; the list of open + // questions drops it a moment before the step reports done. + const needsYou = (under && (asks || beat.kind === "ask")) || agentAsks !== null; + const model = shell === null ? null : formatModelSlugName(shell.modelSelection.model); + const verb = (() => { + if (!under) return null; + if (agentAsks !== null) return agentAsks; + switch (beat.kind) { + case "agent": + return shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" + ? gt("starting") + : gt("working"); + case "ask": + // Without its question it was just answered, and the step is about to say so. + return asks + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : null; + case "sleep": + return Number.isFinite(wakes) && wakes > nowMs + ? gt("wakes in {duration}", { duration: formatDuration(wholeSeconds(wakes - nowMs)) }) + : gt("about to wake"); + case "wait": + return gt("waiting"); + case "run": + return child === null ? gt("running") : workflowRunNow(child, m); + case "step": + return gt("running"); + } + })(); + const aside = (() => { + if (failed) return workflowOneLine(beat.detail ?? gt("failed")); + if (under) return null; + switch (beat.kind) { + case "agent": + return said === null ? null : workflowOneLine(said); + case "ask": + return answer === null + ? gt("nobody answered") + : gt("You said {choice}", { choice: answer.choice }); + case "sleep": + case "wait": + return null; + case "run": + return child === null ? null : workflowRunNow(child, m); + case "step": { + const first = workflowResultLines(beat.result)[0]; + return first === undefined + ? null + : first.label === null + ? first.value + : `${first.label}: ${first.value}`; + } + } + })(); + + return ( + openedAtMs} + draw={!under && beat.endMs > openedAtMs} + lead={ + beat.kind === "agent" && provider !== undefined ? ( + + ) : beat.kind === "run" ? ( + + ) : undefined + } + name={beat.childRun?.title ?? beat.name} + note={beat.kind === "agent" && (under || said === null) ? model : null} + verb={verb} + verbTone={ + needsYou ? "input" : beat.kind === "sleep" || beat.kind === "wait" ? "quiet" : "working" + } + aside={aside} + {...(failed ? { asideTone: "failed" as const } : {})} + duration={workflowStepTime(elapsedOf(beat))} + selected={selected} + current={current} + onPick={onPick} + sub={sub} + /> + ); +} + +// What happened reads as part of the page. A question, answered in the timeline, is the one box; +// a pause says so in its heading and its button. +const CARD_TONE = { + plain: "", + quiet: "", + ask: "rounded-xl border border-warning/30 bg-warning-surface px-3 py-2.5", + failed: "", + done: "", +} as const; + +function FeedCard({ + tone = "plain", + label, + reveal = false, + children, +}: { + readonly tone?: keyof typeof CARD_TONE; + readonly label?: string; + /** Scroll it into view when it first shows. */ + readonly reveal?: boolean; + readonly children: ReactNode; +}) { + return ( +
+ {children} +
+ ); +} + +function CardHead({ + mark, + name, + sub, + action, +}: { + readonly mark: ReactNode; + readonly name: ReactNode; + readonly sub?: ReactNode; + readonly action?: ReactNode; +}) { + return ( +
+
+ {mark === null || mark === undefined ? null : ( + {mark} + )} +
{name}
+ {action === undefined || action === null ? null :
{action}
} +
+ {sub === undefined || sub === null || sub === "" ? null : ( +
{sub}
+ )} +
+ ); +} + +function ResultLines({ + lines, +}: { + readonly lines: ReadonlyArray<{ readonly label: string | null; readonly value: string }>; +}) { + if (lines.length === 0) return null; + if (lines.every((line) => line.label === null)) { + return ( +
+ {lines.map((line) => ( +

+ {line.value} +

+ ))} +
+ ); + } + return ({ label: line.label ?? "", value: line.value }))} />; +} + +/** What a step left behind, as a list of names and values. */ +function Facts({ + facts, +}: { + readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>; +}) { + return ( +
+ {facts.map((fact) => ( +
+
{fact.label}
+
{fact.value}
+
+ ))} +
+ ); +} + +/** A step with nothing to show but that it happened, and what it left behind. */ +function Note({ + label, + children, + detail, +}: { + readonly label: string; + readonly children: ReactNode; + readonly detail?: ReactNode; +}) { + return ( + + + {detail} + + ); +} + +function WorkflowQuickStepsCard({ row }: { readonly row: WorkflowQuickSteps }) { + const gt = useGT(); + return ( + +
    + {row.steps.map((step) => ( +
  • + {step.name} + +
  • + ))} +
+
+ ); +} + +function WorkflowBeatCard({ + environmentId, + beat, + child, + nowMs, + open, + onSelect, + onOpenThread, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly child: WorkflowRunNode | null; + readonly nowMs: number; + readonly open: boolean; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; +}) { + const gt = useGT(); + const m = useMessages(); + const under = beat.status === "running"; + const length = formatDuration(elapsedOf(beat)); + const tries = beat.attempts > 1 ? ` · ${nthTry(beat.attempts, m)}` : ""; + switch (beat.kind) { + case "agent": + return ( + + ); + case "ask": { + const answer = workflowAnswer(beat.result); + if (answer === null) + return {`${gt("nobody answered")} · ${length}`}; + return ( + + +

+ {answer.reason === null ? ( + + You said{" "} + + {answer.choice} + + . + + ) : ( + + You said{" "} + + {answer.choice} + + : {answer.reason} + + )} +

+
+ ); + } + case "sleep": { + if (!under) return {`${gt("slept")} · ${length}`}; + const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); + return ( + + } + name={beat.name} + sub={ + Number.isFinite(wakes) && wakes > nowMs + ? gt("wakes in {duration}", { + duration: formatDuration(wholeSeconds(wakes - nowMs)), + }) + : gt("about to wake") + } + /> + + ); + } + case "wait": + if (!under) return {`${gt("waited")} · ${length}`}; + return ( + + } + name={beat.name} + sub={gt("{duration} so far", { duration: length })} + /> + + ); + case "run": { + const title = beat.childRun?.title ?? beat.name; + return ( + + } + name={title} + sub={ + child === null + ? `${beat.childRun?.workflow ?? ""} · ${length}` + : `${child.run.workflow} · ${workflowRunNow(child, m)}` + } + action={ + <> + {child === null ? null : } + + + } + /> + + ); + } + case "step": { + if (under) { + return ( + + } + name={beat.name} + sub={`${gt("running for {duration}", { duration: length })}${tries}`} + /> + + ); + } + const lines = workflowResultLines(beat.result); + return ( + }> + {beat.status === "failed" ? `${gt("failed")} · ${length}` : length} + {tries} + + ); + } + } +} + +function WorkflowAgentCard({ + environmentId, + beat, + open, + onOpenThread, +}: { + readonly environmentId: EnvironmentId; + readonly beat: WorkflowBeat; + readonly open: boolean; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; +}) { + const gt = useGT(); + const m = useMessages(); + const [all, setAll] = useState(false); + const elsewhere = beat.thread !== null && beat.thread.environmentId !== null; + const threadEnvironmentId = + beat.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(beat.thread.environmentId); + // This client can only show a thread on an environment it is itself connected to. + const threadEnvironment = useEnvironment(threadEnvironmentId); + const shell = useQuietThreadShell( + beat.thread === null + ? null + : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), + ); + const provider = useEnvironmentProviders() + .get(threadEnvironmentId) + ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); + const under = beat.status === "running"; + const length = formatDuration(elapsedOf(beat)); + const summary = workflowAgentSummary(beat); + const start = summary.said === null ? null : workflowSaidStart(summary.said, SAID_SHOWN); + const liveWord = !under + ? null + : shell?.hasPendingUserInput === true + ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) + : shell?.hasPendingApprovals === true + ? gt("waits for your approval") + : shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" + ? gt("starting") + : gt("working"); + const sub = [ + shell === null ? null : formatModelSlugName(shell.modelSelection.model), + liveWord, + length, + beat.attempts > 1 ? nthTry(beat.attempts, m) : null, + elsewhere + ? gt("on {environment}", { environment: threadEnvironment?.label ?? threadEnvironmentId }) + : null, + ] + .filter((part) => part !== null) + .join(" · "); + return ( + + + ) : ( + + ) + } + name={beat.name} + sub={sub} + action={ + beat.thread === null ? null : threadEnvironment === null ? ( + + + Thread on {threadEnvironmentId} + + + ) : ( + + ) + } + /> + {beat.status === "failed" && beat.detail ? ( +

+ + {beat.detail} +

+ ) : null} + {summary.said === null ? null : ( + // Set off from the head, so headings in the reply read as the agent's, not the page's. +
+ + {start !== null ? ( + + ) : null} +
+ )} + {summary.facts.length === 0 ? null : } +
+ ); +} + +function WorkflowPauseCard({ + run, + name, + attempts, + reason, + nowMs, + disabled, + onResume, + kept, +}: { + readonly run: WorkflowRun; + /** The step it stopped at, when the steps say which. */ + readonly name: string | null; + readonly attempts: number; + readonly reason: string | null; + readonly nowMs: number; + readonly disabled: boolean; + readonly onResume: () => void; + /** Steps before it finished, and resuming keeps them. */ + readonly kept: boolean; +}) { + const gt = useGT(); + const m = useMessages(); + const resumes = run.resumesAt === null ? Number.NaN : Date.parse(run.resumesAt); + const next = run.retired + ? gt("cannot go on until its workflow version is registered again") + : !Number.isFinite(resumes) + ? gt("waits for you to resume it") + : resumes > nowMs + ? gt("tries again by itself in {duration}", { duration: formatDuration(resumes - nowMs) }) + : gt("about to try again by itself"); + return ( + + } + name={ + name === null + ? gt("Paused", { $context: "a workflow run is paused" }) + : gt("Paused at {step}", { step: name }) + } + sub={ + <> + {attempts > 0 ? `${nthTry(attempts, m)} · ` : null} + · {next} + + } + action={ + + } + /> + {reason ?

{reason}

: null} + {kept ? ( +

+ Only the failed step runs again; what finished before it is kept. +

+ ) : null} +
+ ); +} + +function WorkflowQuestionCard({ + environmentId, + question, + onOpenThread, + inline = false, +}: { + readonly environmentId: EnvironmentId; + readonly question: WorkflowQuestion; + readonly onOpenThread: (thread: WorkflowThreadTarget) => void; + /** Under its step in the run, which already says that it asks. */ + readonly inline?: boolean; +}) { + const gt = useGT(); + const view = readWorkflowQuestion(question); + const drafts = useContext(AnswerDrafts); + const [ownReason, setOwnReason] = useState(null); + const draftKey = `${question.runId}:${question.name}:${question.askedAt}`; + const reason = drafts === null ? ownReason : drafts.get(draftKey); + const setReason = (next: string | null) => + drafts === null ? setOwnReason(next) : drafts.set(draftKey, next); + const [busy, setBusy] = useState(false); + const canAnswer = useAtomValue( + serverEnvironment.answerWorkflowQuestion.permissionAtom(environmentId), + ); + const answer = useAtomCommand(serverEnvironment.answerWorkflowQuestion, { + label: "workflow answer", + }); + const threadEnvironmentId = + question.thread?.environmentId == null + ? environmentId + : EnvironmentId.make(question.thread.environmentId); + const reachable = useEnvironment(threadEnvironmentId) !== null; + const choose = async (choice: string) => { + if (busy) return; + setBusy(true); + const given = reason?.trim() ?? ""; + const result = await answer({ + environmentId, + input: { + runId: question.runId, + name: question.name, + choice, + ...(given === "" ? {} : { reason: given }), + }, + }); + setBusy(false); + reportFailure(gt("Could not answer the question"), result); + }; + return ( + + {inline ? null : ( +

+ + Needs you + + + + asked{" "} + + + {" "} + · the run waits for you + + +

+ )} +

+ {view.title} +

+ {view.body ? ( + + ) : null} +
+ {view.choices.map((choice, index) => ( + + ))} +
+ {reason === null || (question.thread !== null && reachable) ? ( +
+ {reason === null ? ( + + ) : null} + {question.thread === null || !reachable ? null : ( + + )} +
+ ) : null} + {reason === null ? null : ( +
+ setReason(event.currentTarget.value)} + /> +
+ )} +
+ ); +} diff --git a/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx b/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx new file mode 100644 index 0000000000000..386ba513e0e5b --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunsView.browser.test.tsx @@ -0,0 +1,477 @@ +import { Atom } from "effect/reactivity"; +import { + EnvironmentId, + type WorkflowQuestion, + type WorkflowRun, + type WorkflowRunReference, + type WorkflowRunsSnapshot, + type WorkflowStep, +} from "@t3tools/contracts"; +import { describe, expect, it, vi } from "vite-plus/test"; +import { page as browserPage, userEvent } from "vite-plus/test/browser"; + +import "~/index.css"; +import { render } from "../../../test/render"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { WorkflowRunsView } from "./WorkflowRunsView"; + +const environmentId = EnvironmentId.make("laptop"); +const at = (minute: number) => new Date(Date.UTC(2026, 10, 1, 0, minute)).toISOString(); +const run = (fields: Partial & Pick): WorkflowRun => ({ + workflow: "release", + version: 1, + status: "running", + detail: null, + result: null, + pauses: 0, + retired: false, + resumesAt: null, + parentRunId: null, + parentStep: null, + startedAt: at(0), + updatedAt: at(5), + endedAt: null, + ...fields, +}); +const step = ( + fields: Partial & Pick, +): WorkflowStep => ({ + status: "completed", + attempts: 1, + detail: null, + threadId: null, + environmentId: null, + result: null, + said: null, + startedAt: at(0), + endedAt: at(0), + ...fields, +}); + +const state = vi.hoisted(() => ({ + live: { query: "live" }, + snapshot: { workflows: [], runs: [], questions: [] } as { + workflows: ReadonlyArray; + runs: ReadonlyArray; + questions: ReadonlyArray; + }, + steps: {} as Record>, + references: {} as Record>, + commands: [] as Array, + permitted: true, + detailError: null as string | null, +})); +const canOperate = Atom.make(true); +const cannotOperate = Atom.make(false); + +function setup( + given: Omit & Partial>, + steps: Record> = {}, + references: Record> = {}, +) { + state.snapshot = { workflows: [], ...given }; + state.steps = steps; + state.references = references; + state.commands = []; + state.permitted = true; + state.detailError = null; +} + +const environment = { environmentId, label: "Laptop" }; + +vi.mock(import("../../state/server"), async (original) => { + const actual = await original(); + const permissionAtom = () => (state.permitted ? canOperate : cannotOperate); + return { + ...actual, + serverEnvironment: { + ...actual.serverEnvironment, + workflowsLive: (() => state.live) as never, + workflowRun: ((target: { readonly input: { readonly runId: string } }) => + target.input) as never, + answerWorkflowQuestion: { + ...actual.serverEnvironment.answerWorkflowQuestion, + permissionAtom, + }, + resumeWorkflowRun: { ...actual.serverEnvironment.resumeWorkflowRun, permissionAtom }, + cancelWorkflowRun: { ...actual.serverEnvironment.cancelWorkflowRun, permissionAtom }, + }, + }; +}); +// Stands in for the live list and for one run's detail, which the mocked atoms above name. +vi.mock(import("../../state/query"), async (original) => ({ + ...(await original()), + useEnvironmentQuery: ((request: { readonly runId?: string }) => ({ + data: + request === state.live + ? state.snapshot + : state.detailError !== null + ? null + : { + run: null, + steps: state.steps[request.runId ?? ""] ?? [], + references: state.references[request.runId ?? ""] ?? [], + }, + error: request === state.live ? null : state.detailError, + isPending: false, + refresh: vi.fn(), + })) as never, +})); +vi.mock(import("../../state/use-atom-command"), async (original) => ({ + ...(await original()), + useAtomCommand: ((_command: unknown, options: { readonly label: string }) => + (value: { readonly input: unknown }) => { + state.commands.push([options.label, value.input]); + return Promise.resolve({ _tag: "Success", value: undefined }); + }) as never, +})); +vi.mock(import("../../state/environments"), async (original) => ({ + ...(await original()), + useEnvironment: ((id: EnvironmentId | null) => + id === environmentId ? environment : null) as never, +})); +// The chat's renderer loads its highlighter; a question's body only has to reach the page. +vi.mock("../ChatMarkdown", () => ({ + default: ({ text }: { readonly text: string }) =>
{text}
, +})); + +const question: WorkflowQuestion = { + runId: "ship", + name: "approve", + request: { + title: "Ship release 1.2?", + choices: ["Ship", "Hold"], + data: { body: "The diff touches the installer." }, + }, + askedAt: at(4), + thread: { threadId: "thread-9", environmentId: null }, +}; + +const issue101: WorkflowRunReference = { + kind: "issue", + key: "i101", + address: { projectId: "p1", tracker: "github", scope: "me/app", key: "101" }, + title: "Wrong minutes", + url: "https://github.com/me/app/issues/101", + state: "open", + steps: ["triage"], + origin: "trigger", +}; + +/** Wide enough for the list and the run side by side; put back when the test ends. */ +async function desktop() { + const width = window.innerWidth; + const height = window.innerHeight; + await browserPage.viewport(1280, 800); + return { [Symbol.asyncDispose]: () => browserPage.viewport(width, height) }; +} + +const page = ( + selectedRunId: string | null = null, + on: { + readonly select?: (runId: string | null) => void; + readonly thread?: () => void; + readonly reference?: () => void; + } = {}, + shownTab: WorkflowPaneTab | null = null, +) => ( + +); + +describe("WorkflowRunsView", () => { + it("opens on the question that waits, and answers it with the reason given", async () => { + setup( + { + runs: [ + run({ runId: "busy", title: "Nightly sync" }), + run({ runId: "ship", title: "Release 1.2", status: "waiting", detail: "approve" }), + ], + questions: [question], + }, + { ship: [step({ name: "approve", kind: "ask", status: "running", endedAt: null })] }, + ); + const thread = vi.fn(); + await using _desktop = await desktop(); + await using screen = await render(page(null, { thread })); + + // The list opens on what waits on a person, and the run that asks is the one shown. + const runs = screen.getByRole("navigation", { name: "Workflow runs" }); + await expect.element(runs.getByRole("button", { name: /Release 1\.2/ })).toBeVisible(); + await expect + .element(runs.getByRole("button", { name: /Nightly sync/ })) + .not.toBeInTheDocument(); + await expect.element(runs).toMatchTextContent("Asks: Ship release 1.2?"); + await expect.element(screen.getByText("The diff touches the installer.")).toBeVisible(); + + await screen.getByRole("button", { name: "Ask the agent first" }).click(); + expect(thread).toHaveBeenCalledWith("ship", { threadId: "thread-9", environmentId: null }); + + await screen.getByRole("button", { name: "Add a reason" }).click(); + await userEvent.fill( + screen.getByRole("textbox", { name: "Reason for Ship release 1.2?" }), + " Too risky today ", + ); + await screen.getByRole("button", { name: "Hold", exact: true }).click(); + + await vi.waitFor(() => + expect(state.commands).toEqual([ + [ + "workflow answer", + { runId: "ship", name: "approve", choice: "Hold", reason: "Too risky today" }, + ], + ]), + ); + }); + + it("answers a question whose steps did not load, and says a linked run is not here", async () => { + setup({ + runs: [run({ runId: "ship", title: "Release 1.2", status: "waiting", detail: "approve" })], + questions: [question], + }); + state.detailError = "The server did not answer."; + await using _desktop = await desktop(); + { + await using screen = await render(page("ship")); + await expect.element(screen.getByText("The server did not answer.")).toBeVisible(); + await screen.getByRole("button", { name: "Ship", exact: true }).click(); + await vi.waitFor(() => + expect(state.commands).toEqual([ + ["workflow answer", { runId: "ship", name: "approve", choice: "Ship" }], + ]), + ); + } + + // A link to a run this environment does not have never shows another run in its place. + const select = vi.fn(); + await using screen = await render(page("gone", { select })); + await expect.element(screen.getByText("This run is not here")).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Ship", exact: true })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: "Back to the runs" }).click(); + expect(select).toHaveBeenCalledWith(null); + }); + + it("says a linked run is not here where nothing has run yet", async () => { + setup({ runs: [], questions: [] }); + const select = vi.fn(); + await using screen = await render(page("gone", { select })); + await expect.element(screen.getByText("This run is not here")).toBeVisible(); + await screen.getByRole("button", { name: "Back to the runs" }).click(); + expect(select).toHaveBeenCalledWith(null); + }); + + it("turns the answers off for a session that may not operate", async () => { + setup({ + runs: [run({ runId: "ship", title: "Release 1.2", status: "waiting" })], + questions: [question], + }); + state.permitted = false; + await using _desktop = await desktop(); + await using screen = await render(page()); + + await expect.element(screen.getByRole("button", { name: "Ship", exact: true })).toBeDisabled(); + await expect.element(screen.getByRole("button", { name: "Hold", exact: true })).toBeDisabled(); + }); + + it("says why a run paused at the step that failed, and resumes it", async () => { + setup( + { + runs: [ + run({ + runId: "sync", + title: "Sync labels", + status: "paused", + detail: "apply: 503", + pauses: 1, + }), + ], + questions: [], + }, + { + sync: [ + // A failure the workflow caught and went on from is not where it paused. + step({ name: "lint", kind: "step", status: "failed", endedAt: at(1), detail: "lint" }), + step({ name: "fetch", kind: "step", startedAt: at(1), endedAt: at(1) }), + step({ + name: "apply", + kind: "agent", + status: "failed", + attempts: 3, + detail: "503", + threadId: "thread-apply", + startedAt: at(2), + endedAt: at(3), + }), + ], + }, + ); + await using _desktop = await desktop(); + await using screen = await render(page()); + + const why = screen.getByRole("region", { name: "Why it paused" }); + await expect.element(why).toMatchTextContent(/Paused at apply.*3rd try.*waits for you/); + await expect.element(why).toMatchTextContent("503"); + // The failed agent's transcript is there to read before choosing. + await expect.element(screen.getByRole("button", { name: "Transcript" })).toBeVisible(); + await expect.element(screen.getByText("Paused at lint")).not.toBeInTheDocument(); + await why.getByRole("button", { name: "Resume" }).click(); + + await vi.waitFor(() => + expect(state.commands).toEqual([["workflow resume", { runId: "sync" }]]), + ); + }); + + it("draws a finished run as a flow, and shows the step that is picked", async () => { + setup( + { + runs: [ + run({ + runId: "fix", + title: "#101 Wrong minutes", + status: "completed", + result: "merged as ba6ac7", + endedAt: at(12), + }), + ], + questions: [], + }, + { + fix: [ + step({ name: "load", kind: "step" }), + step({ name: "existing-prs", kind: "step" }), + step({ + name: "triage", + kind: "agent", + endedAt: at(3), + threadId: "thread-1", + said: "Reproduced on main.", + result: { kind: "bug", reproduced: true }, + }), + step({ + name: "implement", + kind: "agent", + startedAt: at(3), + endedAt: at(10), + threadId: "thread-2", + environmentId: "build-box", + }), + step({ + name: "approve", + kind: "ask", + startedAt: at(10), + endedAt: at(11), + result: { choice: "Fix it", reason: "It hits everyone on Windows" }, + }), + ], + }, + { fix: [issue101] }, + ); + const thread = vi.fn(); + const reference = vi.fn(); + await using screen = await render(page("fix", { thread, reference }, { thread: "thread-1" })); + + // A finished run opens on how it ended; the flow has a node for each step that mattered. + const happened = screen.getByRole("region", { name: "What happened" }); + await expect.element(happened).toMatchTextContent(/Finished.*merged as ba6ac7/); + const flow = screen.getByRole("navigation", { name: "Steps so far" }); + await expect + .element(flow) + .toMatchTextContent(/load · existing-prs.*triage.*Reproduced on main\..*implement.*approve/); + + await flow.getByRole("button", { name: /triage/ }).click(); + const triage = screen.getByRole("region", { name: "triage" }); + await expect.element(triage).toMatchTextContent(/3m 0s.*Reproduced on main\..*kind.*bug/); + // Its thread is the one open beside the run, and the button says so. + const transcript = triage.getByRole("button", { name: "Transcript" }); + await expect.element(transcript).toHaveAttribute("aria-pressed", "true"); + await transcript.click(); + expect(thread).toHaveBeenCalledWith("fix", { threadId: "thread-1", environmentId: null }); + // What the run touched is under its title, by number alone when the title already says it. + // It opens beside the run. + const touched = screen.getByRole("list", { name: "What the run touched" }); + const onRun = touched.getByRole("button", { name: "#101 Wrong minutes" }); + await expect.element(onRun).toMatchTextContent(/^#101$/); + await onRun.click(); + expect(reference).toHaveBeenCalledWith("fix", issue101); + // This client is not connected to the linked environment, so there is nothing to open. + await flow.getByRole("button", { name: /implement/ }).click(); + await expect + .element(screen.getByRole("region", { name: "implement" })) + .toMatchTextContent("Thread on build-box"); + await flow.getByRole("button", { name: /approve/ }).click(); + await expect + .element(screen.getByRole("region", { name: "approve" })) + .toMatchTextContent("You said Fix it: It hits everyone on Windows"); + await flow.getByRole("button", { name: /load · existing-prs/ }).click(); + await expect + .element(screen.getByRole("region", { name: "Quick steps" })) + .toMatchTextContent("loadexisting-prs"); + await expect + .element(screen.getByRole("button", { name: "Cancel run" })) + .not.toBeInTheDocument(); + }); + + it("opens an invoked run from its parent's story", async () => { + setup( + { + runs: [ + run({ runId: "rel", title: "Release 1.3", status: "waiting", detail: "check" }), + run({ runId: "chk", title: "Check web", parentRunId: "rel", parentStep: "check" }), + ], + questions: [], + }, + { + rel: [ + step({ name: "check/start", kind: "step" }), + step({ name: "check", kind: "wait", status: "running", endedAt: null }), + ], + }, + ); + const select = vi.fn(); + await using screen = await render(page("rel", { select })); + + const invoked = screen.getByRole("region", { name: "Check web" }); + await invoked.getByRole("button", { name: "Open run" }).click(); + expect(select).toHaveBeenCalledWith("chk"); + }); + + it("switches between what is under way and everything, one workflow at a time", async () => { + setup({ + workflows: [ + { name: "release", version: 1, triggers: ["webhook tags"] }, + { name: "report", version: 1, triggers: ["daily at 09:00"] }, + ], + runs: [ + run({ runId: "rel", title: "Release 1.3" }), + run({ runId: "old", title: "Release 1.2", status: "completed", endedAt: at(3) }), + ], + questions: [], + }); + await using _desktop = await desktop(); + await using screen = await render(page()); + + const runs = screen.getByRole("navigation", { name: "Workflow runs" }); + await expect.element(runs.getByRole("button", { name: /Release 1\.3/ })).toBeVisible(); + await expect + .element(runs.getByRole("button", { name: /Release 1\.2/ })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: "All", exact: true }).click(); + await expect.element(runs.getByRole("button", { name: /Release 1\.2/ })).toBeVisible(); + + // A workflow that has not run is still there to be picked, with what starts it. + await screen.getByRole("combobox", { name: "Workflow" }).click(); + await screen.getByRole("option", { name: "report" }).click(); + await expect.element(screen.getByText("Starts on daily at 09:00")).toBeVisible(); + await expect.element(runs).toMatchTextContent("Has not run yet."); + }); +}); diff --git a/apps/web/src/components/workflows/WorkflowRunsView.tsx b/apps/web/src/components/workflows/WorkflowRunsView.tsx new file mode 100644 index 0000000000000..4c43539b1e1e3 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunsView.tsx @@ -0,0 +1,384 @@ +import { type EnvironmentId, type WorkflowRunReference } from "@t3tools/contracts"; +import { msg, T, useGT, useMessages } from "gt-react"; +import { WorkflowIcon } from "lucide-react"; +import { useState, type ReactNode } from "react"; + +import { cn } from "../../lib/utils"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { Button } from "../ui/button"; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; +import { ScrollArea } from "../ui/scroll-area"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { Toggle, ToggleGroup } from "../ui/toggle-group"; +import { + RelativeLabel, + WorkflowChip, + WorkflowRunFeed, + WorkflowStateWord, + type WorkflowThreadTarget, +} from "./WorkflowRunFeed"; +import type { WorkflowPaneTab } from "./workflowPane.logic"; +import { + allWorkflowRunNodes, + defaultWorkflowListTab, + defaultWorkflowRunId, + groupWorkflowRuns, + listedWorkflowRuns, + workflowRunLists, + workflowRunNow, + workflowTriggerLine, + type WorkflowListTab, + type WorkflowRunNode, + workflowRunInvolves, +} from "@t3tools/client-runtime/workflows"; + +const WORKFLOWS_GUIDE_URL = "https://github.com/pingdotgg/t3code/blob/main/docs/user/workflows.md"; +const EVERY_WORKFLOW = ""; +const TABS: ReadonlyArray<{ readonly value: WorkflowListTab; readonly label: string }> = [ + { + value: "needs-you", + label: msg("Needs you", { $context: "tab: workflow runs that wait on the user" }), + }, + { value: "running", label: msg("Running", { $context: "tab: workflow runs under way" }) }, + { value: "all", label: msg("All", { $context: "tab: every workflow run" }) }, +]; +const NOTHING: Record = { + "needs-you": msg("Nothing waits on you."), + running: msg("Nothing is running."), + all: msg("No runs yet."), +}; + +export function WorkflowsEmpty({ + title, + description, +}: { + readonly title: string; + readonly description: ReactNode; +}) { + return ( +
+ + + + + + {title} + {description} + + +
+ ); +} + +/** One environment's runs: the list to pick from, and the picked run told as a feed. */ +export function WorkflowRunsView({ + environmentId, + selectedRunId, + paneOpen, + shownTab, + onSelect, + onOpenThread, + onOpenReference, + onOpenDefinitions, +}: { + readonly environmentId: EnvironmentId; + readonly selectedRunId: string | null; + /** Something is open beside the run, so the list makes room below `xl`. */ + readonly paneOpen: boolean; + /** What shows beside the run, so what opened it can say so. */ + readonly shownTab: WorkflowPaneTab | null; + readonly onSelect: (runId: string | null) => void; + readonly onOpenThread: (runId: string, thread: WorkflowThreadTarget) => void; + readonly onOpenReference: (runId: string, reference: WorkflowRunReference) => void; + readonly onOpenDefinitions: () => void; +}) { + const live = useEnvironmentQuery(serverEnvironment.workflowsLive({ environmentId, input: {} })); + const [pickedTab, setPickedTab] = useState(null); + const [workflow, setWorkflow] = useState(EVERY_WORKFLOW); + const gt = useGT(); + const m = useMessages(); + const [showSkipped, setShowSkipped] = useState(false); + const snapshot = live.data; + if (live.error) { + return ; + } + if (!snapshot) { + return ( +

+ Loading workflow runs… +

+ ); + } + // A broken file is said even where nothing has run, or its workflows would just seem missing. + const problemAlert = + snapshot.definition?.problem == null ? null : ( +
+ + + + A workflow file has a problem. + {" "} + The last version that did keeps running. + + + +
+ ); + const withProblem = (empty: ReactNode) => + problemAlert === null ? ( + empty + ) : ( +
+ {problemAlert} + {empty} +
+ ); + const notHere = ( + + This environment has no run with that link.{" "} + + + } + /> + ); + // A link to a run says it is not here, even where nothing has run at all. + if (snapshot.runs.length === 0 && snapshot.workflows.length === 0 && selectedRunId !== null) { + return withProblem(notHere); + } + if (snapshot.runs.length === 0 && snapshot.workflows.length === 0) { + return withProblem( + + A workflow ties agents, code, schedules and questions to you into one run that survives + restarts. Write one under{" "} + + , or ask an agent to.{" "} + + Read the guide + + + } + />, + ); + } + // A skipped run opened by its link is shown all the same. + const openedSkipped = snapshot.runs.some( + (run) => run.runId === selectedRunId && run.status === "skipped", + ); + const visible = listedWorkflowRuns(snapshot.runs, showSkipped || openedSkipped); + const groups = groupWorkflowRuns(snapshot.workflows, visible.runs, snapshot.questions); + const lists = workflowRunLists(groups); + const all = allWorkflowRunNodes(groups); + const section = groups.workflows.find((candidate) => candidate.name === workflow) ?? null; + // A run the address names is that run or none: another one's buttons would act on the wrong run. + const shownRunId = + selectedRunId === null + ? defaultWorkflowRunId(groups) + : (all.find((node) => node.run.runId === selectedRunId)?.run.runId ?? null); + const shown = all.find((node) => node.run.runId === shownRunId) ?? null; + // A run that another invoked is not in the list itself; the one it is part of stands for it. + const listedFor = (node: WorkflowRunNode | null): string | null => { + if (node === null) return null; + const parent = all.find((candidate) => candidate.run.runId === node.run.parentRunId); + return parent === undefined ? node.run.runId : listedFor(parent); + }; + const currentRunId = listedFor(shown); + // A run opened by its link is shown in a list that has it, so the list never points at nothing. + const opening = defaultWorkflowListTab(groups); + const holds = (candidate: WorkflowListTab) => + lists[candidate].some((node) => node.run.runId === currentRunId); + const tab = + pickedTab ?? + (selectedRunId === null || holds(opening) ? opening : holds("running") ? "running" : "all"); + const listed = lists[tab].filter( + (node) => section === null || workflowRunInvolves(node, section.name), + ); + return ( +
+ {problemAlert} +
+ {/* Below md there is room for one of the two: the list, or the run picked from it. */} +
+
+ { + const value = TABS.find((candidate) => candidate.value === next[0]); + if (value !== undefined) setPickedTab(value.value); + }} + > + {TABS.map(({ value, label }) => ( + + {m(label)} + + ))} + + {groups.workflows.length > 1 ? ( + + ) : null} + {section === null ? null : ( +

+ {workflowTriggerLine(section, m)} +

+ )} +
+ + + +
+ + {shown === null ? ( + selectedRunId === null ? null : ( + notHere + ) + ) : ( + node.run.runId === shown.run.parentRunId)?.run ?? null} + shownTab={shownTab} + onSelect={onSelect} + onOpenThread={(thread) => onOpenThread(shown.run.runId, thread)} + onOpenReference={(reference) => onOpenReference(shown.run.runId, reference)} + /> + )} + +
+
+ ); +} + +/** A run in the thread list's own shape: which workflow, its state in a word, and what it is at. */ +function WorkflowRunListItem({ + node, + current, + onSelect, +}: { + readonly node: WorkflowRunNode; + readonly current: boolean; + readonly onSelect: (runId: string | null) => void; +}) { + const { run } = node; + const m = useMessages(); + return ( +
  • + +
  • + ); +} diff --git a/apps/web/src/components/workflows/WorkflowThreadPane.tsx b/apps/web/src/components/workflows/WorkflowThreadPane.tsx new file mode 100644 index 0000000000000..7e6432eaec393 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowThreadPane.tsx @@ -0,0 +1,65 @@ +import { type ScopedThreadRef } from "@t3tools/contracts"; +import { useNavigate } from "@tanstack/react-router"; +import { useGT } from "gt-react"; + +import { ComposerHandleContext } from "../../composerHandleContext"; +import type { SideChatParentPanel } from "../../lib/sideChatPane"; +import { useQuietThreadShell } from "../../state/entities"; +import { useEnvironmentShellHasSnapshot } from "../../state/shell"; +import { buildThreadRouteParams } from "../../threadRoutes"; +import ChatView from "../ChatView"; +import { BackgroundThreadContext } from "../chat/backgroundThread"; + +/** Opens the thread as a full thread view. */ +export function useOpenThreadPage(): (threadRef: ScopedThreadRef) => void { + const navigate = useNavigate(); + return (threadRef) => + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(threadRef) }); +} + +/** What a transcript's tab is called: the step its agent did, or the thread's own title. */ +export function WorkflowThreadTabLabel({ threadRef }: { readonly threadRef: ScopedThreadRef }) { + const gt = useGT(); + const shell = useQuietThreadShell(threadRef); + const step = shell?.workflowRun?.step; + return step === undefined + ? (shell?.title ?? gt("Agent", { $context: "fallback title of a coding agent's thread" })) + : gt("{step} · transcript", { step, $context: "tab: the agent thread of a workflow step" }); +} + +/** + * An agent step's thread beside its run: the same chat as anywhere, composer included, so a + * person can read what the agent did and talk to it without leaving the run. + */ +export default function WorkflowThreadPane({ threadRef }: { readonly threadRef: ScopedThreadRef }) { + const gt = useGT(); + const openThreadPage = useOpenThreadPage(); + const shell = useQuietThreadShell(threadRef); + const snapshotLoaded = useEnvironmentShellHasSnapshot(threadRef.environmentId); + const openFull = () => openThreadPage(threadRef); + // The diff panel and the terminal drawer belong to the full thread view, so both lead there. + const panel: SideChatParentPanel = { + hostRef: threadRef, + openToolDiff: openFull, + runShellCommand: openFull, + }; + return shell === null ? ( +

    + {snapshotLoaded ? gt("This thread is no longer there.") : gt("Loading the thread…")} +

    + ) : ( + // The attribute is how the embedded chat knows the keyboard is meant for it. +
    + + + + + +
    + ); +} diff --git a/apps/web/src/components/workflows/WorkflowsPage.tsx b/apps/web/src/components/workflows/WorkflowsPage.tsx new file mode 100644 index 0000000000000..7c42a4d00080a --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowsPage.tsx @@ -0,0 +1,328 @@ +import { EnvironmentId, type WorkflowRunReference } from "@t3tools/contracts"; +import { Link, useNavigate, useSearch } from "@tanstack/react-router"; +import { T, useGT } from "gt-react"; +import { FileCode2Icon } from "lucide-react"; +import { lazy, Suspense, useState, type MouseEvent } from "react"; + +import { isElectron } from "~/env"; +import { type FileContextMenuAction, useFileContextMenu } from "../../fileContextMenu"; +import { cn } from "../../lib/utils"; +import { readLocalApi } from "../../localApi"; +import { useEnvironmentQuery } from "../../state/query"; +import { serverEnvironment } from "../../state/server"; +import { + useConnectedEnvironmentIds, + useEnvironments, + usePrimaryEnvironmentId, +} from "../../state/environments"; +import { useWorkflowEnvironmentIds } from "./useWorkflowEnvironmentIds"; +import { Button } from "../ui/button"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { SidebarInset } from "../ui/sidebar"; +import { + WorkspaceBreadcrumb, + WorkspaceBreadcrumbItem, + WorkspaceBreadcrumbSeparator, + WorkspaceBreadcrumbText, +} from "../WorkspaceBreadcrumb"; +import { WorkspacePageHeader } from "../WorkspacePageHeader"; +import { WorkflowRunsView, WorkflowsEmpty } from "./WorkflowRunsView"; +import WorkflowPane from "./WorkflowPane"; +import { + activeWorkflowPaneTab, + toggleWorkflowPaneTab, + type WorkflowPaneState, +} from "./workflowPane.logic"; + +const COPY_PATH = "copy-path"; + +// The editor brings the code view's highlighter with it, which the run list has no use for. +const WorkflowDefinitionEditor = lazy(() => import("./WorkflowDefinitionEditor")); + +export interface WorkflowsSearch extends WorkflowPaneState { + readonly env?: string; + readonly run?: string; + /** Show the definition files instead of the runs: all of them, or `file` in the editor. */ + readonly definitions?: boolean; + readonly file?: string; +} + +export function WorkflowsPage() { + const search = useSearch({ from: "/_chat/workflows" }); + const navigate = useNavigate(); + const gt = useGT(); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const connectedIds = useConnectedEnvironmentIds(); + const { environments } = useEnvironments(); + const workflowIds = useWorkflowEnvironmentIds(); + // Only servers with workflows on in Labs can be picked; a connected one with them off says so. + const connected = environments.filter((environment) => + workflowIds.includes(environment.environmentId), + ); + const asked = search.env === undefined ? null : EnvironmentId.make(search.env); + const turnedOff = + asked === null + ? workflowIds.length === 0 && connectedIds.length > 0 + : connectedIds.includes(asked) && !workflowIds.includes(asked); + // An environment the address names is kept while it is away: its run and file mean nothing on + // another server. + const environmentId = + asked !== null + ? (connected.find((environment) => environment.environmentId === asked)?.environmentId ?? + null) + : (connected.find((environment) => environment.environmentId === primaryEnvironmentId) + ?.environmentId ?? + connected[0]?.environmentId ?? + null); + const select = (next: WorkflowsSearch) => + void navigate({ to: "/workflows", search: next, replace: true }); + // A level of the page, which the browser's Back should step out of again. + const go = (next: WorkflowsSearch) => void navigate({ to: "/workflows", search: next }); + // Opening a run or file pins the environment it is on, so the same address never means another. + const pinned = environmentId ?? search.env; + const env = pinned === undefined ? {} : { env: pinned }; + const away = + asked !== null && environmentId === null && !turnedOff + ? (environments.find((environment) => environment.environmentId === asked)?.label ?? asked) + : null; + const run = search.run === undefined ? {} : { run: search.run }; + const editing = search.definitions === true || search.file !== undefined; + // An open file stays open while its environment is away, so a draft in it is not lost. + const fileEnvironmentId = + environmentId ?? (search.file === undefined || turnedOff ? null : asked); + const [fileActions, setFileActions] = useState(null); + const definitions = useEnvironmentQuery( + fileEnvironmentId === null || search.file === undefined + ? null + : serverEnvironment.workflowDefinition({ environmentId: fileEnvironmentId, input: {} }), + ); + const fileMenu = useFileContextMenu(fileEnvironmentId); + /** What a right click on the open file's name offers: its path, and the editors on that machine. */ + const showFileMenu = (event: MouseEvent) => { + const api = readLocalApi(); + const directory = definitions.data?.directory; + if (api === undefined || directory === undefined || search.file === undefined) return; + event.preventDefault(); + const path = `${directory}/${search.file}`; + const target = { environmentId: fileEnvironmentId, filePath: path, workspaceRoot: undefined }; + void api.contextMenu + .show([{ id: COPY_PATH, label: gt("Copy path") }, ...fileMenu.buildItems(target)], { + x: event.clientX, + y: event.clientY, + }) + .then((picked) => { + if (picked === null) return; + if (picked === COPY_PATH) return void navigator.clipboard.writeText(path); + return fileMenu.activate(picked as FileContextMenuAction, target); + }); + }; + // The run stays in the address, so the breadcrumb back to the runs reopens it. + const openDefinitions = (file: string | null) => + go({ ...env, ...run, definitions: true, ...(file === null ? {} : { file }) }); + // What is open beside the run, which belongs to the run: picking another one closes it. + const pane: WorkflowPaneState = + environmentId === null || editing || search.pane === undefined + ? {} + : search.tab === undefined + ? { pane: search.pane } + : { pane: search.pane, tab: search.tab }; + const paneOpen = pane.pane !== undefined; + const shownTab = activeWorkflowPaneTab(pane); + // Opening something pins the run it is from, so the address keeps naming the run it belongs to. + const togglePane = (runId: string, tab: Parameters[1]) => + select({ ...env, run: runId, ...toggleWorkflowPaneTab(pane, tab) }); + + return ( + +
    + {/* Below md there is room for one thing, and an open pane is that thing. */} +
    + + + + {editing ? ( + + ) : ( +

    + Workflows +

    + )} +
    + {editing ? ( + <> + + / + + + {search.file === undefined ? ( +

    + Definitions +

    + ) : ( + + )} +
    + + ) : null} + {search.file === undefined ? null : ( + <> + + / + + +

    + + {search.file} + +

    +
    + + )} +
    + {(connected.length > 1 && environmentId !== null) || + ((away !== null || turnedOff) && connected.length > 0) ? ( + + ) : null} + {search.file === undefined ? null : ( +
    + )} + {environmentId === null || editing ? null : ( + + )} + + {editing && fileEnvironmentId !== null ? ( + + Loading the editor… +

    + } + > + +
    + ) : away !== null ? ( + + ) : turnedOff ? ( + + Turn them on for this server in{" "} + + Settings → Labs + + . + + } + /> + ) : environmentId === null ? ( + + ) : ( + openDefinitions(null)} + environmentId={environmentId} + selectedRunId={search.run ?? null} + paneOpen={paneOpen} + shownTab={shownTab} + onSelect={(runId) => select({ ...env, ...(runId === null ? {} : { run: runId }) })} + onOpenThread={(runId, thread) => + togglePane(runId, { + thread: thread.threadId, + ...(thread.environmentId === null ? {} : { env: thread.environmentId }), + }) + } + onOpenReference={(runId, reference: WorkflowRunReference) => + togglePane(runId, { kind: reference.kind, key: reference.key }) + } + /> + )} +
    + {environmentId === null || !paneOpen ? null : ( + + )} +
    + + ); +} diff --git a/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts b/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts new file mode 100644 index 0000000000000..9a8bd4a583b71 --- /dev/null +++ b/apps/web/src/components/workflows/useWorkflowEnvironmentIds.ts @@ -0,0 +1,11 @@ +import type { EnvironmentId } from "@t3tools/contracts"; + +import { useServerConfigs } from "../../state/entities"; +import { useConnectedEnvironmentIds } from "../../state/environments"; + +/** The connected environments whose server has workflows turned on in Labs. */ +export function useWorkflowEnvironmentIds(): ReadonlyArray { + const connectedIds = useConnectedEnvironmentIds(); + const configs = useServerConfigs(); + return connectedIds.filter((id) => configs.get(id)?.settings.workflowsEnabled === true); +} diff --git a/apps/web/src/components/workflows/workflowPane.logic.test.ts b/apps/web/src/components/workflows/workflowPane.logic.test.ts new file mode 100644 index 0000000000000..f9c9b54f926a2 --- /dev/null +++ b/apps/web/src/components/workflows/workflowPane.logic.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + activeWorkflowPaneTab, + closeWorkflowPaneTab, + openWorkflowPaneTab, + readWorkflowPane, + toggleWorkflowPaneTab, + type WorkflowPaneState, +} from "./workflowPane.logic"; + +const issue = { kind: "issue", key: "i412" }; +const pullRequest = { kind: "pullRequest", key: "p418" }; +const transcript = { thread: "workflow:ab", env: "env-2" }; + +describe("the pane beside a run", () => { + it("reads back from the address only what it can, once", () => { + expect( + readWorkflowPane( + [issue, { kind: "issue" }, issue, transcript, { thread: "t1", env: 3 }, "x"], + "0", + ), + ).toEqual({ pane: [issue, transcript, { thread: "t1" }], tab: 0 }); + // The last tab shows unless the address says another; one it cannot have shows the last. + expect(readWorkflowPane([issue, pullRequest], 7)).toEqual({ pane: [issue, pullRequest] }); + expect(readWorkflowPane("nope", 0)).toEqual({}); + }); + + it("opens a tab once, shows it, and closing one shows the tab beside it", () => { + let state: WorkflowPaneState = {}; + state = openWorkflowPaneTab(state, issue); + state = openWorkflowPaneTab(state, pullRequest); + state = openWorkflowPaneTab(state, transcript); + expect(state).toEqual({ pane: [issue, pullRequest, transcript] }); + state = openWorkflowPaneTab(state, { ...issue }); + expect(state).toEqual({ pane: [issue, pullRequest, transcript], tab: 0 }); + state = closeWorkflowPaneTab(state, 0); + expect(activeWorkflowPaneTab(state)).toEqual(pullRequest); + // Closing one that does not show leaves the one that does. + state = closeWorkflowPaneTab(state, 1); + expect(state).toEqual({ pane: [pullRequest] }); + expect(closeWorkflowPaneTab(state, 0)).toEqual({}); + }); + + it("asking for the tab that shows closes it, and any other shows it", () => { + const open = { pane: [issue, transcript] }; + expect(toggleWorkflowPaneTab(open, transcript)).toEqual({ pane: [issue] }); + expect(toggleWorkflowPaneTab(open, issue)).toEqual({ pane: [issue, transcript], tab: 0 }); + }); +}); diff --git a/apps/web/src/components/workflows/workflowPane.logic.ts b/apps/web/src/components/workflows/workflowPane.logic.ts new file mode 100644 index 0000000000000..9cdbc4963423d --- /dev/null +++ b/apps/web/src/components/workflows/workflowPane.logic.ts @@ -0,0 +1,103 @@ +/** + * What is open beside a run: agent transcripts and the things the run touched, one tab each. It + * lives in the address, so a reload or a shared link opens the same tabs. + */ +export type WorkflowPaneTab = + /** An agent's thread, and the linked environment it is in when not the run's own. */ + | { readonly thread: string; readonly env?: string } + /** One of the run's references, by its kind and key. */ + | { readonly kind: string; readonly key: string }; + +export interface WorkflowPaneState { + readonly pane?: ReadonlyArray; + /** Which tab shows; the last one when it names none. */ + readonly tab?: number; +} + +// A link is typed into an address bar: what it holds is capped like the rest of the address. +const MOST_TABS = 12; +const LONGEST = 400; + +const text = (value: unknown): value is string => + typeof value === "string" && value !== "" && value.length <= LONGEST; + +function readTab(raw: unknown): WorkflowPaneTab | null { + if (typeof raw !== "object" || raw === null) return null; + const fields = raw as Readonly>; + if (text(fields.thread)) { + return text(fields.env) + ? { thread: fields.thread, env: fields.env } + : { thread: fields.thread }; + } + return text(fields.kind) && text(fields.key) ? { kind: fields.kind, key: fields.key } : null; +} + +const sameWorkflowPaneTab = (left: WorkflowPaneTab, right: WorkflowPaneTab) => + "thread" in left + ? "thread" in right && left.thread === right.thread && left.env === right.env + : "kind" in right && left.kind === right.kind && left.key === right.key; + +/** The pane an address names, without what it cannot read or holds twice. */ +export function readWorkflowPane(rawPane: unknown, rawTab: unknown): WorkflowPaneState { + const tabs: Array = []; + for (const raw of Array.isArray(rawPane) ? rawPane : []) { + const tab = readTab(raw); + if (tab === null || tabs.some((open) => sameWorkflowPaneTab(open, tab))) continue; + tabs.push(tab); + if (tabs.length === MOST_TABS) break; + } + if (tabs.length === 0) return {}; + const tab = typeof rawTab === "number" ? rawTab : Number(rawTab); + return Number.isInteger(tab) && tab >= 0 && tab < tabs.length - 1 + ? { pane: tabs, tab } + : { pane: tabs }; +} + +/** The index of the tab that shows, or -1 when nothing is open. */ +export function activeWorkflowPaneIndex(state: WorkflowPaneState): number { + const count = state.pane?.length ?? 0; + return state.tab !== undefined && state.tab < count ? state.tab : count - 1; +} + +export function activeWorkflowPaneTab(state: WorkflowPaneState): WorkflowPaneTab | null { + return state.pane?.[activeWorkflowPaneIndex(state)] ?? null; +} + +const stateOf = (tabs: ReadonlyArray, active: number): WorkflowPaneState => + tabs.length === 0 + ? {} + : active === tabs.length - 1 + ? { pane: tabs } + : { pane: tabs, tab: active }; + +/** Shows `tab`, opening it after the others when it is not open yet. */ +export function openWorkflowPaneTab( + state: WorkflowPaneState, + tab: WorkflowPaneTab, +): WorkflowPaneState { + const tabs = state.pane ?? []; + const at = tabs.findIndex((open) => sameWorkflowPaneTab(open, tab)); + if (at !== -1) return stateOf(tabs, at); + const next = [...tabs, tab].slice(-MOST_TABS); + return stateOf(next, next.length - 1); +} + +/** Closes the tab at `index`. The one beside it shows if it was showing. */ +export function closeWorkflowPaneTab(state: WorkflowPaneState, index: number): WorkflowPaneState { + const tabs = state.pane ?? []; + if (index < 0 || index >= tabs.length) return state; + const active = activeWorkflowPaneIndex(state); + const rest = tabs.filter((_, at) => at !== index); + return stateOf(rest, active > index ? active - 1 : Math.min(active, rest.length - 1)); +} + +/** Asking for the tab that shows closes it, as the pressed control that asked says it will. */ +export function toggleWorkflowPaneTab( + state: WorkflowPaneState, + tab: WorkflowPaneTab, +): WorkflowPaneState { + const active = activeWorkflowPaneTab(state); + return active !== null && sameWorkflowPaneTab(active, tab) + ? closeWorkflowPaneTab(state, activeWorkflowPaneIndex(state)) + : openWorkflowPaneTab(state, tab); +} diff --git a/apps/web/src/composer-editor-mentions.ts b/apps/web/src/composer-editor-mentions.ts index 7f3e93b821488..6608d3b2a0439 100644 --- a/apps/web/src/composer-editor-mentions.ts +++ b/apps/web/src/composer-editor-mentions.ts @@ -7,6 +7,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "~/markdown/wordsHast"; export type ComposerPromptSegment = | { @@ -89,7 +90,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray !taken.some((range) => mention.start < range.end && mention.end > range.start), @@ -98,7 +99,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray = []; for (const formula of formulas) { diff --git a/apps/web/src/fork/chunkReloadBuild.ts b/apps/web/src/fork/chunkReloadBuild.ts deleted file mode 100644 index 7d1a060e63c72..0000000000000 --- a/apps/web/src/fork/chunkReloadBuild.ts +++ /dev/null @@ -1,10 +0,0 @@ -// The bundler's entry hash covers the hashed names it imports, so any changed chunk renames the entry. -export function chunkReloadBuild(): string { - if (typeof document === "undefined") return import.meta.env.APP_VERSION; - const buildAssetPrefix = `${import.meta.env.BASE_URL}assets/`; - const entryPath = Array.from( - document.querySelectorAll('script[type="module"][src]'), - (script) => script.getAttribute("src")?.split(/[?#]/, 1)[0], - ).find((path) => path?.startsWith(buildAssetPrefix)); - return entryPath ?? import.meta.env.APP_VERSION; -} diff --git a/apps/web/src/fork/cjkLinkEnd.test.tsx b/apps/web/src/fork/cjkLinkEnd.test.tsx index f96ca32fe7153..9f47b5fa62e8d 100644 --- a/apps/web/src/fork/cjkLinkEnd.test.tsx +++ b/apps/web/src/fork/cjkLinkEnd.test.tsx @@ -1,36 +1,40 @@ -import { - CHAT_MARKDOWN_REHYPE_PLUGINS, - CHAT_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; -import { renderToStaticMarkup } from "react-dom/server"; +import type { Element, Root } from "hast"; import { describe, expect, it } from "vite-plus/test"; -import { createMarkdownRenderer } from "../components/chat/markdownRenderer"; -import { remarkEndLinksAtCjkPunctuation } from "./cjkLinkEnd"; -import { remarkWhiteboardLinks } from "./whiteboard/markdown-whiteboard"; +import { wordsHast, type WordsHastOptions } from "../markdown/wordsHast"; -const render = createMarkdownRenderer({ - remarkPlugins: [ - ...CHAT_MARKDOWN_REMARK_PLUGINS, - remarkWhiteboardLinks, - remarkEndLinksAtCjkPunctuation, - ], - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, - components: {}, - urlTransform: (url) => url, -}); +const CHAT: WordsHastOptions = { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions: {}, + boardLinks: true, +}; + +const URI_ESCAPE = /%[0-9A-F]{2}/i; function anchors(source: string) { - const markup = renderToStaticMarkup(render(source)); - return Array.from(markup.matchAll(/([^<]*)<\/a>/g), ([, href, text]) => ({ - href, - text, - })); + const found: Array<{ href: string; text: string }> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "a") { + const text = child.children + .map((part) => (part.type === "text" ? part.value : "")) + .join(""); + const href = String(child.properties.href); + found.push({ href: URI_ESCAPE.test(href) ? decodeURI(href) : href, text }); + } else visit(child); + } + }; + visit(wordsHast(source, CHAT)); + return found; } -const bare = (href: string, text = href) => ({ href: encodeURI(href), text }); +const bare = (href: string, text = href) => ({ href, text }); -describe("remarkEndLinksAtCjkPunctuation", () => { +describe("endLinksAtCjkPunctuation", () => { it.each([ ["(https://example.com/pull/78),Claude 和", [bare("https://example.com/pull/78")]], [ @@ -58,6 +62,11 @@ describe("remarkEndLinksAtCjkPunctuation", () => { ], ["https://example.com/a,见xhttps://example.com/b", [bare("https://example.com/a")]], ["https://example.com/a,见www.example.com/b", [bare("https://example.com/a")]], + ["https://example.com/中文,见https://", [bare("https://example.com/中文")]], + [ + "https://example.com/中文,见https://example.com/b]", + [bare("https://example.com/中文"), bare("https://example.com/b")], + ], [ "「https://example.com/a」『https://example.com/b』【https://example.com/c】《https://example.com/d》", ["a", "b", "c", "d"].map((path) => bare(`https://example.com/${path}`)), @@ -106,15 +115,17 @@ describe("remarkEndLinksAtCjkPunctuation", () => { expect(anchors(source)).toEqual(links); }); - // Upstream's CJK autolink pass ends these first. The first two differ from GFM at a space. + // Words' own autolink boundaries end these first, and the fork pass leaves them as they are. it.each([ - ["[https://example.com/a],然后", [bare("https://example.com/a]")]], + ["[https://example.com/a],然后", []], [ "https://example.com/a,www.example.com/b?u=https://example.com/c", [ bare("https://example.com/a"), - bare("http://www.example.com/b?u=", "www.example.com/b?u="), - bare("https://example.com/c"), + bare( + "http://www.example.com/b?u=https://example.com/c", + "www.example.com/b?u=https://example.com/c", + ), ], ], ["见 https://example.com/report(1).pdf 页", [bare("https://example.com/report")]], diff --git a/apps/web/src/fork/cjkLinkEnd.ts b/apps/web/src/fork/cjkLinkEnd.ts index 0e40288b758b3..5f2969829313b 100644 --- a/apps/web/src/fork/cjkLinkEnd.ts +++ b/apps/web/src/fork/cjkLinkEnd.ts @@ -1,7 +1,4 @@ -import type { Link, Nodes, Paragraph, PhrasingContent, Root, Text } from "mdast"; -import type { Transform } from "mdast-util-from-markdown"; -import type { Processor } from "unified"; -import type { VFile } from "vfile"; +import type { Element, ElementContent, Root, Text } from "hast"; // Each opening bracket is followed by its closing bracket. const BRACKETS = "()[]{}⦅⦆「」〈〉《》「」『』【】〔〕〖〗〘〙〚〛"; @@ -72,75 +69,103 @@ function trimTrailingPunctuation(url: string): string { } } -/** Cuts a bare link at CJK punctuation and returns the cut-off text, or nothing to cut. */ -function cutBareLink(link: Link, source: string): Text | undefined { +const URL_PREFIX = /^(?:https?:\/\/|www\.)/i; +// GFM's parser starts an http link after anything but an ASCII letter. `www.` is here so a URL +// inside it stays inside. +const URL_START = /(? + (/^www\./i.test(url) ? `http://${url}` : url).replace(/[^\x21-\x7e]+|[\\[\]`{}|^"<>]/gu, (run) => + encodeURIComponent(run), + ); + +const text = (value: string): Text => ({ type: "text", value }); + +const anchor = (url: string): Element => ({ + type: "element", + tagName: "a", + properties: { href: hrefOf(url) }, + children: [text(url)], +}); + +/** Links the URLs in text cut off a bare link, each ended as bareLinkEnd ends it. */ +function linkRest(rest: string): ElementContent[] { + const parts: ElementContent[] = []; + let plain = ""; + let remaining = rest; + while (remaining !== "") { + const found = URL_START.exec(remaining); + if (found === null) break; + const url = bareLinkEnd(remaining.slice(found.index)); + // A bare `https://` or `www.` has no destination, so it stays text. + if (url.length <= found[0].length) { + plain += remaining.slice(0, found.index + found[0].length); + remaining = remaining.slice(found.index + found[0].length); + continue; + } + plain += remaining.slice(0, found.index); + if (plain !== "") parts.push(text(plain)); + plain = ""; + parts.push(anchor(url)); + remaining = remaining.slice(found.index + url.length); + } + plain += remaining; + if (plain !== "") parts.push(text(plain)); + return parts; +} + +/** Cuts one of Words' bare links at CJK punctuation, returning what follows it, or null. */ +function cutBareLink(link: Element, source: string): ElementContent[] | null { const label = link.children.length === 1 ? link.children[0] : undefined; - if (label?.type !== "text") return undefined; - const scheme = link.url === `http://${label.value}` ? "http://" : ""; - if (link.url !== scheme + label.value) return undefined; - const cut = blankCjkPunctuation(label.value).indexOf(" "); - if (cut === -1) return undefined; - const { position } = link; + const start = link.position?.start.offset; + const end = link.position?.end.offset; + if (label?.type !== "text" || start === undefined || end === undefined) return null; // `` and `[url](url)` were ended by their author. - if (position && source.slice(position.start.offset, position.end.offset) !== label.value) { - return undefined; - } - const kept = trimTrailingPunctuation(label.value.slice(0, cut)); - const rest: Text = { type: "text", value: label.value.slice(kept.length) }; + if (!URL_PREFIX.test(label.value) || source.slice(start, end) !== label.value) return null; + const kept = bareLinkEnd(label.value); + if (kept === label.value) return null; label.value = kept; - link.url = scheme + kept; - if (position?.start.offset !== undefined) { - // A bare link never spans lines. - const boundary = { + link.properties.href = hrefOf(kept); + const position = link.position!; + // A bare link never spans lines. + link.position = { + start: position.start, + end: { line: position.start.line, column: position.start.column + kept.length, - offset: position.start.offset + kept.length, - }; - rest.position = { start: boundary, end: position.end }; - link.position = { start: position.start, end: boundary }; - label.position = link.position; - } - return rest; + offset: start + kept.length, + }, + }; + return linkRest(source.slice(start + kept.length, end)); } -// GFM's parser starts an http link after anything but an ASCII letter. Its transform, which is what -// can run on a text node, needs punctuation first. `www.` is here so a URL inside it stays inside. -const URL_START = /(? (extension.enter?.literalAutolink ? (extension.transforms ?? []) : [])); - const linkUrls = (text: Text): PhrasingContent[] => { - const start = text.value.search(URL_START); - if (start === -1) return [text]; - // The transform accepts a URL at the start of a text node. Later URLs are found when this link - // is cut in turn. - const paragraph: Paragraph = { - type: "paragraph", - children: [ - { type: "text", value: text.value.slice(0, start) }, - { type: "text", value: text.value.slice(start) }, - ], - }; - for (const transform of autolinkTransforms) transform({ type: "root", children: [paragraph] }); - return paragraph.children; - }; - return (tree: Root, file: VFile) => { - const source = String(file); - const visit = (node: Nodes) => { - if (!("children" in node) || node.type === "link" || node.type === "linkReference") return; - for (let index = 0; index < node.children.length; index++) { - const child = node.children[index]!; - const rest = child.type === "link" ? cutBareLink(child, source) : undefined; - if (rest) (node.children as PhrasingContent[]).splice(index + 1, 0, ...linkUrls(rest)); - else visit(child); +export function endLinksAtCjkPunctuation(tree: Root, source: string): void { + const visit = (node: Root | Element) => { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + if (child.tagName === "a") { + const rest = cutBareLink(child, source); + if (rest) { + children.splice(index + 1, 0, ...rest); + index += rest.length; + } + } else if (child.tagName !== "code" && child.tagName !== "pre" && child.tagName !== "svg") { + visit(child); } - }; - visit(tree); + } }; + visit(tree); } diff --git a/apps/web/src/fork/dashboard/dashboardMarkdown.tsx b/apps/web/src/fork/dashboard/dashboardMarkdown.tsx index f3eb24c13b2ad..81088e5535959 100644 --- a/apps/web/src/fork/dashboard/dashboardMarkdown.tsx +++ b/apps/web/src/fork/dashboard/dashboardMarkdown.tsx @@ -6,23 +6,17 @@ import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination, } from "@t3tools/shared/markdownLinks"; -import { - ASSISTANT_MARKDOWN_REMARK_PLUGINS, - CHAT_MARKDOWN_REHYPE_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; -import type { Root } from "mdast"; import { createContext, use } from "react"; -import { defaultUrlTransform } from "react-markdown"; -import ChatMarkdown from "../../components/ChatMarkdown"; +import ChatMarkdown, { safeUrl } from "../../components/ChatMarkdown"; import { nodeToPlainText } from "../../components/chat/MarkdownCodeBlock.logic"; import { createMarkdownRenderer } from "../../components/chat/markdownRenderer"; +import type { WordsHastOptions } from "../../markdown/wordsHast"; import { resolveInlineCodeFileLinkMeta, resolveMarkdownFileLinkMeta, rewriteMarkdownFileUriHref, } from "../../markdown-links"; -import { remarkEndLinksAtCjkPunctuation } from "../cjkLinkEnd"; import { hostFileAnchorHref, hostFileLinkHref, @@ -48,16 +42,6 @@ interface SlotCopy { const SlotCopyContext = createContext({ text: "", filePaths: [], hostFileOrigins: [] }); -function remarkUnwrapSoleParagraph() { - return (tree: Root) => { - const [only] = tree.children; - if (tree.children.length === 1 && only?.type === "paragraph") tree.children = only.children; - }; -} - -// A chip sits inside the slot's own paragraph, so its markdown must not add another `

    `. -const CHIP_PLUGINS = [remarkUnwrapSoleParagraph]; - /** * Chat's own file chip. `markdown` is a code span or an empty-label link built here, never * text from the slot, so nothing in it can suspend or parse differently from the slot. @@ -70,7 +54,6 @@ function ChatFileChip(props: { readonly markdown: string; readonly scope: LinkSc text={props.markdown} cwd={props.scope.cwd} threadRef={props.scope.threadRef} - extraRemarkPlugins={CHIP_PLUGINS} fileLinkPeerPaths={filePaths} /> ); @@ -113,9 +96,18 @@ function slotFilePaths( return [...paths]; } +// Agent text without math, breaks or insights; no board on the Dashboard. +const DASHBOARD_MARKDOWN: WordsHastOptions = { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions: {}, + agentText: true, +}; + const renderMarkdown = createMarkdownRenderer({ - remarkPlugins: [...ASSISTANT_MARKDOWN_REMARK_PLUGINS, remarkEndLinksAtCjkPunctuation], - rehypePlugins: CHAT_MARKDOWN_REHYPE_PLUGINS, + markdown: DASHBOARD_MARKDOWN, components: { a: function DashboardLink({ node, children, ...props }) { const scope = use(DashboardLinkScope); @@ -164,7 +156,7 @@ const renderMarkdown = createMarkdownRenderer({ }, urlTransform: (url) => rewriteMarkdownFileUriHref(url) ?? - (isWindowsDrivePathHref(url) || parseDashboardHref(url) ? url : defaultUrlTransform(url)), + (isWindowsDrivePathHref(url) || parseDashboardHref(url) ? url : safeUrl(url)), }); /** @@ -179,11 +171,11 @@ export function DashboardMarkdown(props: { readonly text: string; readonly paire scope?.cwd, hostFileOrigins, ); - const element = renderMarkdown(props.text); - renderMarkdown.remember(props.text, element); + const entry = renderMarkdown.parse(props.text); + renderMarkdown.remember(props.text, entry); return ( - {element} + {renderMarkdown.element(entry)} ); } diff --git a/apps/web/src/fork/forkMarkdown.test.ts b/apps/web/src/fork/forkMarkdown.test.ts new file mode 100644 index 0000000000000..ce2369aa4fafc --- /dev/null +++ b/apps/web/src/fork/forkMarkdown.test.ts @@ -0,0 +1,97 @@ +import type { Element, Root } from "hast"; +import { describe, expect, it } from "vite-plus/test"; + +import { wordsHast, type WordsHastOptions } from "../markdown/wordsHast"; + +const CHAT: WordsHastOptions = { + math: true, + breaks: false, + escapeHtml: false, + insights: false, + extensions: {}, +}; + +function elements(node: Root | Element, tagName: string): Element[] { + return node.children.flatMap((child) => + child.type !== "element" + ? [] + : [...(child.tagName === tagName ? [child] : []), ...elements(child, tagName)], + ); +} + +const glyphs = (svg: Element) => + elements(svg, "text") + .flatMap((text) => text.children.map((child) => (child.type === "text" ? child.value : ""))) + .join(""); + +describe("forkSource", () => { + it("draws \\eps in math as \\varepsilon and copies it as written", () => { + const tree = wordsHast("$\\eps_1$ and `\\eps`", CHAT); + const [svg] = elements(tree, "svg"); + const [varepsilon] = elements(wordsHast("$\\varepsilon_1$", CHAT), "svg"); + expect(glyphs(svg!)).toBe(glyphs(varepsilon!)); + expect(svg!.properties.ariaLabel).toBe("\\eps_1"); + const [wrapper] = elements(tree, "span").filter( + (span) => span.properties.dataMarkdownMath !== undefined, + ); + expect(wrapper!.properties.dataMarkdownCopy).toBe("\\(\\eps_1\\)"); + expect(elements(tree, "code")[0]!.children).toEqual([ + expect.objectContaining({ type: "text", value: "\\eps" }), + ]); + }); + + it.each([ + ["a quote", "> $$\n> \\eps +\n> \\eps\n> $$"], + ["a list item", "- $$\n \\eps +\n \\eps\n $$"], + ])("copies multiline math inside %s as written", (_, text) => { + const formula = (tree: Root) => { + const [wrapper] = [...elements(tree, "div"), ...elements(tree, "span")].filter( + (node) => node.properties.dataMarkdownMath !== undefined, + ); + const [svg] = elements(wrapper!, "svg"); + return { copy: wrapper!.properties.dataMarkdownCopy, label: svg!.properties.ariaLabel, svg }; + }; + const swapped = formula(wordsHast(text, CHAT)); + const drawn = formula(wordsHast(text.replaceAll("\\eps", "\\varepsilon"), CHAT)); + const asWritten = (value: unknown) => String(value).replaceAll("\\varepsilon", "\\eps"); + expect(glyphs(swapped.svg!)).toBe(glyphs(drawn.svg!)); + expect(swapped.label).toBe(asWritten(drawn.label)); + expect(swapped.copy).toBe(asWritten(drawn.copy)); + expect(swapped.copy).toContain("\\eps +\n\\eps"); + }); + + it("keeps a written {ε } beside a swapped \\eps, in the formula or its fence's info string", () => { + const [svg] = elements(wordsHast("$\\eps {ε }$", CHAT), "svg"); + expect(svg!.properties.ariaLabel).toBe("\\eps {ε }"); + const [fenced] = elements(wordsHast("```math {ε } note\n\\eps + 1\n```", CHAT), "svg"); + expect(fenced!.properties.ariaLabel).toBe("\\eps + 1\n"); + }); + + it("leaves \\epsilon, an escaped \\eps and math that is off as written", () => { + const [epsilon] = elements(wordsHast("$\\epsilon$", CHAT), "svg"); + expect(epsilon!.properties.ariaLabel).toBe("\\epsilon"); + expect(glyphs(elements(wordsHast("$a\\\\eps$", CHAT), "svg")[0]!)).not.toContain("𝜀"); + expect(elements(wordsHast("$\\eps$", { ...CHAT, math: false }), "svg")).toEqual([]); + }); + + it("keeps offsets after a swapped formula", () => { + const text = "$\\eps$\n\n- [ ] task"; + const [item] = elements(wordsHast(text, CHAT), "li"); + expect(item!.position?.start.offset).toBe(text.indexOf("- [ ]")); + }); +}); + +describe("forkHast inline", () => { + it("renders a sole paragraph as its content, but not in a preview", () => { + const inline = wordsHast("[]()", { ...CHAT, inline: true }); + expect(inline.children.map((child) => child.type === "element" && child.tagName)).toEqual([ + "a", + ]); + const preview = wordsHast("text", { + ...CHAT, + inline: true, + extensions: { preview: { fallback: "", maxLength: 100 } }, + }); + expect(elements(preview, "p")).toEqual([]); + }); +}); diff --git a/apps/web/src/fork/forkMarkdown.ts b/apps/web/src/fork/forkMarkdown.ts new file mode 100644 index 0000000000000..d915d5186330d --- /dev/null +++ b/apps/web/src/fork/forkMarkdown.ts @@ -0,0 +1,114 @@ +import type { Element, ElementContent, Root } from "hast"; + +import type { MarkdownExtensions } from "../markdown/wordsHast"; +import { endLinksAtCjkPunctuation } from "./cjkLinkEnd"; +import { linkBoardUrls } from "./whiteboard/markdown-whiteboard"; + +/** The fork's flags on wordsHast's options. ChatMarkdown keys its cached options by them. */ +export interface ForkWordsOptions { + /** Agent-authored text: only `~~` strikes (early port of open pingdotgg/t3code#29270). */ + readonly agentText?: boolean; + /** Bare `board://` URLs link. The Dashboard has no board, so it leaves them as text. */ + readonly boardLinks?: boolean; + /** Markdown shown inside a line: a sole paragraph renders as its content. */ + readonly inline?: boolean; +} + +/** What the user wrote, outside a sent message: a single `~` stays text, as in their message. */ +export const USER_TEXT_MARKDOWN: MarkdownExtensions = { + userMessage: true, + leadingWhitespace: true, +}; + +/** + * Words' parse options the fork sets: a single `~` strikes only outside user and agent text, and + * emphasis works beside CJK punctuation. + */ +export function forkRenderOptions( + options: ForkWordsOptions & { readonly extensions: MarkdownExtensions }, +): { readonly singleTilde: boolean; readonly cjk: true } { + return { singleTilde: !options.extensions.userMessage && !options.agentText, cjk: true }; +} + +const EPS = /(?<=(?:^|[^\\])(?:\\\\)*)\\eps(?![A-Za-z])/g; +// The same length as `\eps`, so every offset Words writes is still an offset into the written text. +const EPS_SHOWN = "{ε }"; + +/** + * `\eps` in math as `\varepsilon` draws it, as chat's KaTeX macro did. wordsHast passes its + * `markdownMathRanges`, so this module needs no runtime import of it. + */ +export function forkSource( + written: string, + mathRanges: ((text: string) => ReadonlyArray<{ start: number; end: number }>) | null, +): string { + if (mathRanges === null || !written.includes("\\eps")) return written; + let source = ""; + let cursor = 0; + for (const { start, end } of mathRanges(written)) { + source += written.slice(cursor, start) + written.slice(start, end).replace(EPS, EPS_SHOWN); + cursor = end; + } + return source + written.slice(cursor); +} + +/** Replaces the k-th `{ε }` with `\\eps` where `written[k]` says forkSource swapped it. */ +function unswap(text: string, written: ReadonlyArray): string { + let k = 0; + return text.replaceAll(EPS_SHOWN, (shown) => (written[k++] ? "\\eps" : shown)); +} + +/** + * A formula's copy text and label show the TeX as written, not forkSource's swap. Words drops a + * quote or list prefix from them, so swaps are matched by order, not by offset. + */ +function restoreMathSource(node: Root | Element, written: string, source: string) { + for (const child of node.children) { + if (child.type !== "element") continue; + const svg = child.children[0]; + if (child.properties.dataMarkdownMath === undefined || svg?.type !== "element") { + restoreMathSource(child, written, source); + continue; + } + const start = svg.position?.start.offset; + const end = svg.position?.end.offset; + if (start === undefined || end === undefined) continue; + const swapped: boolean[] = []; + for (let at = source.indexOf(EPS_SHOWN, start); at !== -1 && at < end;) { + swapped.push(written.startsWith("\\eps", at)); + at = source.indexOf(EPS_SHOWN, at + EPS_SHOWN.length); + } + const label = String(svg.properties.ariaLabel ?? ""); + // The range starts at a fence's opening line, whose info string is not in the label. + swapped.splice(0, swapped.length - (label.split(EPS_SHOWN).length - 1)); + if (!swapped.includes(true)) continue; + svg.properties.ariaLabel = unswap(label, swapped); + const copy = child.properties.dataMarkdownCopy; + if (typeof copy === "string" && copy.split(EPS_SHOWN).length - 1 === swapped.length) { + child.properties.dataMarkdownCopy = unswap(copy, swapped); + } + } +} + +function unwrapSoleParagraph(tree: Root) { + const blocks = tree.children.filter( + (child) => !(child.type === "text" && child.value.trim() === ""), + ); + const [only] = blocks; + if (blocks.length === 1 && only?.type === "element" && only.tagName === "p") { + tree.children = only.children as ElementContent[]; + } +} + +/** The fork's passes over wordsHast's sanitized tree; `source` is forkSource's output. */ +export function forkHast( + tree: Root, + written: string, + source: string, + options: ForkWordsOptions & { readonly extensions: MarkdownExtensions }, +): void { + if (source !== written) restoreMathSource(tree, written, source); + if (options.boardLinks && written.includes("board://")) linkBoardUrls(tree); + if (/\P{ASCII}/u.test(written)) endLinksAtCjkPunctuation(tree, written); + if (options.inline && !options.extensions.preview) unwrapSoleParagraph(tree); +} diff --git a/apps/web/src/fork/whiteboard/markdown-whiteboard.test.ts b/apps/web/src/fork/whiteboard/markdown-whiteboard.test.ts index 05a089607a12e..4a97cdd96c681 100644 --- a/apps/web/src/fork/whiteboard/markdown-whiteboard.test.ts +++ b/apps/web/src/fork/whiteboard/markdown-whiteboard.test.ts @@ -1,30 +1,31 @@ +import { toHtml } from "hast-util-to-html"; import { describe, expect, it } from "vite-plus/test"; -import { boardMentionParts, remarkWhiteboardLinks } from "./markdown-whiteboard"; +import { wordsHast, type WordsHastOptions } from "../../markdown/wordsHast"; +import { boardMentionParts } from "./markdown-whiteboard"; + +const CHAT: WordsHastOptions = { + math: false, + breaks: false, + escapeHtml: false, + insights: false, + extensions: {}, + boardLinks: true, +}; + +describe("linkBoardUrls", () => { + const source = "See board://r/1,2,3,4. [Area 1](board://r/5,6,7,8) `board://r/9,10,11,12`"; -describe("remarkWhiteboardLinks", () => { it("links bare board URLs but leaves existing links and code alone", () => { - const tree = { - type: "root", - children: [ - { type: "text", value: "See board://r/1,2,3,4." }, - { type: "link", url: "board://r/5,6,7,8", children: [{ type: "text", value: "Area 1" }] }, - { type: "inlineCode", value: "board://r/9,10,11,12" }, - ], - }; + expect(toHtml(wordsHast(source, CHAT))).toBe( + '

    See board://r/1,2,3,4. Area 1 board://r/9,10,11,12

    ', + ); + }); - remarkWhiteboardLinks()(tree); - expect(tree.children).toEqual([ - { type: "text", value: "See " }, - { - type: "link", - url: "board://r/1,2,3,4", - children: [{ type: "text", value: "board://r/1,2,3,4" }], - }, - { type: "text", value: "." }, - { type: "link", url: "board://r/5,6,7,8", children: [{ type: "text", value: "Area 1" }] }, - { type: "inlineCode", value: "board://r/9,10,11,12" }, - ]); + it("leaves bare board URLs as text without boardLinks, as on the Dashboard", () => { + expect(toHtml(wordsHast(source, { ...CHAT, boardLinks: false }))).toContain( + "See board://r/1,2,3,4. ", + ); }); }); diff --git a/apps/web/src/fork/whiteboard/markdown-whiteboard.ts b/apps/web/src/fork/whiteboard/markdown-whiteboard.ts index f56cf20e140fa..03c050a1db534 100644 --- a/apps/web/src/fork/whiteboard/markdown-whiteboard.ts +++ b/apps/web/src/fork/whiteboard/markdown-whiteboard.ts @@ -1,46 +1,52 @@ // A board reference is a `board://r/x,y,w,h` URL naming a rectangle on the // whiteboard that embeds this app. Rendered chat text turns those URLs into // links that point at the board instead of at a page. -export { postWhiteboardHover } from "./boardChannel"; +import type { Element, ElementContent, Root } from "hast"; -type MarkdownNode = { - type?: string; - value?: string; - url?: string; - children?: MarkdownNode[]; -}; +import { bareLinkEnd } from "../cjkLinkEnd"; -const BOARD_URL_REGEX = /board:\/\/[^\s<>]+/g; +const BOARD_URL = /board:\/\/[^\s<>]+/g; -/** Autolink bare board URLs in prose, leaving existing links and code alone. */ -export function remarkWhiteboardLinks() { - return (tree: MarkdownNode) => { - const visit = (node: MarkdownNode) => { - if (node.type === "link" || node.type === "code" || node.type === "inlineCode") return; - if (node.children) { - node.children = node.children.flatMap((child) => { - if (child.type !== "text" || !child.value?.includes("board://")) { - visit(child); - return child; - } - const children: MarkdownNode[] = []; - let cursor = 0; - for (const match of child.value.matchAll(BOARD_URL_REGEX)) { - const start = match.index ?? 0; - const url = (match[0] ?? "").replace(/[),.;!?]+$/, ""); - if (start > cursor) - children.push({ type: "text", value: child.value.slice(cursor, start) }); - children.push({ type: "link", url, children: [{ type: "text", value: url }] }); - cursor = start + url.length; - } - if (cursor < child.value.length) - children.push({ type: "text", value: child.value.slice(cursor) }); - return children; - }); - } - }; - visit(tree); - }; +function linkText(value: string): ElementContent[] { + const parts: ElementContent[] = []; + const pattern = new RegExp(BOARD_URL); + let cursor = 0; + for (let match = pattern.exec(value); match; match = pattern.exec(value)) { + // A URL cut at CJK punctuation lets the next one start after it. + const url = bareLinkEnd(match[0]).replace(/[),.;!?]+$/, ""); + if (match.index > cursor) parts.push({ type: "text", value: value.slice(cursor, match.index) }); + parts.push({ + type: "element", + tagName: "a", + properties: { href: url }, + children: [{ type: "text", value: url }], + }); + cursor = match.index + url.length; + pattern.lastIndex = cursor; + } + if (cursor < value.length) parts.push({ type: "text", value: value.slice(cursor) }); + return parts; +} + +/** Links bare board URLs in prose, leaving links, code and math alone. */ +export function linkBoardUrls(tree: Root | Element): void { + const children = tree.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type === "text" && child.value.includes("board://")) { + const parts = linkText(child.value); + children.splice(index, 1, ...parts); + index += parts.length - 1; + } else if ( + child.type === "element" && + child.tagName !== "a" && + child.tagName !== "code" && + child.tagName !== "pre" && + child.tagName !== "svg" + ) { + linkBoardUrls(child); + } + } } // The board mentions the composer tokenizer makes: `[label](board://...)` with `\` escapes in the diff --git a/apps/web/src/hooks/useHandleNewThread.test.ts b/apps/web/src/hooks/useHandleNewThread.test.ts index 7c64d0077cc2b..07df36fe906a4 100644 --- a/apps/web/src/hooks/useHandleNewThread.test.ts +++ b/apps/web/src/hooks/useHandleNewThread.test.ts @@ -2,9 +2,15 @@ import { describe, expect, it, vi } from "vite-plus/test"; import type { EnvironmentId, ProjectId, RuntimeMode } from "@t3tools/contracts"; const testState = vi.hoisted(() => { - let completeProjectFileRead: (value: null) => void = () => undefined; - let projectFileRead = Promise.resolve(null); - let projectRemoved = false; + type ProjectFile = { readonly defaultThreadEnvMode?: "local" | "worktree" } | null; + let completeProjectFileRead: (value: ProjectFile) => void = () => undefined; + let projectFileRead = Promise.resolve(null); + let draftSession = { + envMode: "local", + worktreePath: null, + branch: null as string | null, + environmentSelection: undefined as "manual" | undefined, + }; let connectedEnvironmentIds = ["environment-primary", "environment-ssh"]; let targetSettings = { defaultThreadEnvMode: "local" as "local" | "worktree" | null, @@ -19,7 +25,6 @@ const testState = vi.hoisted(() => { readonly threadId: string; } | null = null; let openDraftRoute: { readonly kind: "draft"; readonly draftId: string } | null = null; - let draftsWithUserText = new Set(); const router = { state: { location: { href: "/" }, @@ -37,7 +42,7 @@ const testState = vi.hoisted(() => { getDraftSessionByLogicalProjectKey: vi.fn(() => storedDraft), getDraftSession: vi.fn(() => openDraftRoute === null - ? null + ? { ...draftSession, promotedTo: null, startFromOrigin: false } : { logicalProjectKey: "remote-project", promotedTo: null, @@ -56,34 +61,29 @@ const testState = vi.hoisted(() => { }; return { - completeProjectFileRead: (value: null) => completeProjectFileRead(value), + completeProjectFileRead: (value: ProjectFile) => completeProjectFileRead(value), + discoverBranch(branch: string) { + draftSession = { ...draftSession, branch }; + }, + keepEarlierManualChoice() { + draftSession = { ...draftSession, environmentSelection: "manual" }; + }, + pickBranch(branch: string) { + draftSession = { ...draftSession, branch, environmentSelection: "manual" }; + }, draftStore, get projectFileRead() { return projectFileRead; }, - get projectRemoved() { - return projectRemoved; - }, get connectedEnvironmentIds() { return connectedEnvironmentIds; }, disconnect(environmentId: string) { connectedEnvironmentIds = connectedEnvironmentIds.filter((id) => id !== environmentId); }, - removeProject() { - projectRemoved = true; - }, - hasUserText: (draft: { readonly draftId?: string } | null | undefined) => - draft?.draftId !== undefined && draftsWithUserText.has(draft.draftId), - giveUserText(draftId: string) { - draftsWithUserText = new Set([...draftsWithUserText, draftId]); - }, get openDraftRoute() { return openDraftRoute; }, - registerDraft(draft: NonNullable) { - storedDraft = draft; - }, openEmptyDraft(draftId: string) { openDraftRoute = { kind: "draft", draftId }; }, @@ -99,8 +99,12 @@ const testState = vi.hoisted(() => { ) { storedDraft = nextStoredDraft; openDraftRoute = null; - draftsWithUserText = new Set(); - projectRemoved = false; + draftSession = { + envMode: "local", + worktreePath: null, + branch: null, + environmentSelection: undefined, + }; connectedEnvironmentIds = ["environment-primary", "environment-ssh"]; targetSettings = { defaultThreadEnvMode: workspaceDefaults.envMode, @@ -113,7 +117,7 @@ const testState = vi.hoisted(() => { draftStore.setDraftThreadContext.mockClear(); draftStore.setLogicalProjectDraftThreadId.mockClear(); draftStore.setPrompt.mockClear(); - projectFileRead = new Promise((resolve) => { + projectFileRead = new Promise((resolve) => { completeProjectFileRead = resolve; }); }, @@ -186,6 +190,7 @@ vi.mock("@tanstack/react-router", () => ({ useParams: () => null, useRouter: () => testState.router, })); +vi.mock("react-dom", () => ({ flushSync: (update: () => void) => update() })); vi.mock("react", () => ({ useCallback: (callback: T) => callback, useMemo: (factory: () => T) => factory(), @@ -198,8 +203,7 @@ vi.mock("../composerDraftStore", () => { getState: () => testState.draftStore, }); return { - composerDraftHasUserContent: (draft: { readonly draftId?: string } | null | undefined) => - testState.hasUserText(draft), + composerDraftHasUserContent: () => false, markPromotedDraftThreadByRef: vi.fn(), useComposerDraftStore, }; @@ -212,6 +216,7 @@ vi.mock("../lib/chatThreadActions", async (importOriginal) => ({ vi.mock("../providerInstances", () => ({ resolveDefaultProviderModelSelection: () => null })); vi.mock("../lib/t3ProjectFileDefaults", () => ({ readT3ProjectFile: () => testState.projectFileRead, + peekT3ProjectFile: () => undefined, })); vi.mock("../lib/utils", () => ({ newDraftId: () => "draft-delayed", @@ -231,8 +236,7 @@ vi.mock("../state/entities", () => { defaultModelSelection: null, }; return { - readProject: () => (testState.projectRemoved ? null : project), - readProjects: () => (testState.projectRemoved ? [] : [project]), + readProjects: () => [project], readThreadShell: () => null, readThreadShells: () => [], useProjects: () => [], @@ -257,7 +261,11 @@ vi.mock("../uiStateStore", () => ({ })); vi.mock("./useSettings", () => ({ getClientSettings: () => ({}) })); -import { resolveDefaultProjectRef, useNewThreadHandler } from "./useHandleNewThread"; +import { + readPendingWorkspaceDefault, + resolveDefaultProjectRef, + useNewThreadHandler, +} from "./useHandleNewThread"; describe.each([ ["new", null], @@ -271,58 +279,79 @@ describe.each([ }, ], ])("useNewThreadHandler with a %s draft", (_, draft) => { - it("abandons a delayed draft open when the user navigates elsewhere", async () => { - testState.reset(draft); - const openThread = useNewThreadHandler(); - const pendingOpen = openThread( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, + it("opens the draft before the project file is read, then applies its workspace default", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + const opened = await useNewThreadHandler()({ + environmentId: "environment-ssh", + projectId: "project-remote", + } as never); + + expect(testState.router.navigate).toHaveBeenCalledOnce(); + expect(testState.draftStore.setLogicalProjectDraftThreadId).toHaveBeenCalledWith( + "remote-project", + expect.anything(), + opened?.draftId, + expect.objectContaining({ envMode: "local" }), ); + testState.draftStore.setDraftThreadContext.mockClear(); - testState.router.state.location.href = "/usage"; - testState.completeProjectFileRead(null); - await pendingOpen; + testState.discoverBranch("main"); + const pendingDefault = readPendingWorkspaceDefault(opened!.draftId); + expect(pendingDefault).not.toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await pendingDefault; - expect(testState.router.state.location.href).toBe("/usage"); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); - }); + expect(readPendingWorkspaceDefault(opened!.draftId)).toBeNull(); - it("resolves to the draft another opener showed for the same project meanwhile", async () => { - testState.reset(draft); - const pendingOpen = useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, - ); + expect(testState.draftStore.setDraftThreadContext).toHaveBeenCalledWith(opened?.draftId, { + envMode: "worktree", + startFromOrigin: false, + }); + }); - // The location moves before the route matches do. - testState.registerDraft({ - draftId: "draft-home", + it("applies the project file's default to a draft chosen manually before it opened", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + testState.keepEarlierManualChoice(); + const opened = await useNewThreadHandler()({ environmentId: "environment-ssh", - promotedTo: null, - threadId: "thread-home", - }); - testState.router.state.location.href = "/draft/draft-home"; - testState.completeProjectFileRead(null); + projectId: "project-remote", + } as never); + testState.draftStore.setDraftThreadContext.mockClear(); - await expect(pendingOpen).resolves.toEqual({ - draftId: "draft-home", - threadId: "thread-home", + const pendingDefault = readPendingWorkspaceDefault(opened!.draftId); + expect(pendingDefault).not.toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await pendingDefault; + + expect(testState.draftStore.setDraftThreadContext).toHaveBeenCalledWith(opened?.draftId, { + envMode: "worktree", + startFromOrigin: false, }); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); + }); + + it("keeps a branch the user picked while the project file loaded", async () => { + testState.reset(draft, { envMode: null, startFromOrigin: false }); + const opened = await useNewThreadHandler()({ + environmentId: "environment-ssh", + projectId: "project-remote", + } as never); + testState.draftStore.setDraftThreadContext.mockClear(); + + testState.pickBranch("feature"); + expect(readPendingWorkspaceDefault(opened!.draftId)).toBeNull(); + testState.completeProjectFileRead({ defaultThreadEnvMode: "worktree" }); + await testState.projectFileRead; + + expect(testState.draftStore.setDraftThreadContext).not.toHaveBeenCalled(); }); it("sets the prompt before the draft shows", async () => { testState.reset(draft); - const pendingOpen = useNewThreadHandler()( + const opened = await useNewThreadHandler()( { environmentId: "environment-ssh", projectId: "project-remote" } as never, { prompt: "Read the playbook. " }, ); - testState.completeProjectFileRead(null); - const opened = await pendingOpen; - expect(testState.draftStore.setPrompt).toHaveBeenCalledWith( opened?.draftId, "Read the playbook. ", @@ -331,46 +360,9 @@ describe.each([ testState.router.navigate.mock.invocationCallOrder[0] ?? 0, ); }); - - it("abandons a delayed draft open when the project is removed meanwhile", async () => { - testState.reset(draft); - const pendingOpen = useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { replace: true }, - ); - - testState.removeProject(); - testState.completeProjectFileRead(null); - - await expect(pendingOpen).resolves.toBeNull(); - expect(testState.router.navigate).not.toHaveBeenCalled(); - expect(testState.draftStore.setLogicalProjectDraftThreadId).not.toHaveBeenCalled(); - }); }); describe("useNewThreadHandler", () => { - it("keeps the text of a draft that gained some while it waited", async () => { - testState.reset(null); - const raced = { - draftId: "draft-raced", - environmentId: "environment-ssh", - promotedTo: null, - threadId: "thread-raced", - }; - testState.draftStore.getDraftSessionByLogicalProjectKey - .mockReturnValueOnce(null) - .mockReturnValueOnce(raced as never); - testState.giveUserText("draft-raced"); - - const opened = await useNewThreadHandler()( - { environmentId: "environment-ssh", projectId: "project-remote" } as never, - { prompt: "Read the playbook. " }, - ); - - expect(opened?.draftId).toBe("draft-raced"); - expect(testState.draftStore.setPrompt).not.toHaveBeenCalled(); - }); - it("seeds the prompt into the empty draft that is already open", async () => { testState.reset(null); testState.openEmptyDraft("draft-open"); diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index 1be24bd9a3489..ea9c42b2649b5 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -3,12 +3,19 @@ import { scopeProjectRef, scopeThreadRef, } from "@t3tools/client-runtime/environment"; -import { DEFAULT_SERVER_SETTINGS, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts"; +import { + DEFAULT_SERVER_SETTINGS, + type ScopedProjectRef, + type T3ProjectFile, + type ThreadId, +} from "@t3tools/contracts"; import { type AnyRouter, useRouter } from "@tanstack/react-router"; +import { flushSync } from "react-dom"; import { composerDraftHasUserContent, markPromotedDraftThreadByRef, type DraftId, + type DraftSessionState, type DraftThreadEnvMode, type DraftThreadState, useComposerDraftStore, @@ -24,7 +31,6 @@ import { } from "@t3tools/client-runtime/state/project-grouping"; import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { - readProject, readProjects, readThreadShell, readThreadShells, @@ -39,7 +45,7 @@ import { threadHasStarted, } from "../lib/chatThreadActions"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; -import { readT3ProjectFile } from "../lib/t3ProjectFileDefaults"; +import { peekT3ProjectFile, readT3ProjectFile } from "../lib/t3ProjectFileDefaults"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentSummaries } from "../state/presentation"; import { environmentServerConfigsAtom } from "../state/server"; @@ -66,6 +72,39 @@ export function readLastUsedProjectKey(): string | null { } } +// Drafts that opened before their project's t3.json was read. A send waits for the file's +// workspace default unless the user has already chosen a workspace. +interface ProvisionalWorkspace { + readonly envMode: DraftThreadEnvMode; + // A reused draft keeps an earlier "manual" marker; only a switch to manual after opening is a choice. + readonly openedManual: boolean; +} + +const pendingWorkspaceDefaults = new Map< + DraftId, + ProvisionalWorkspace & { readonly settled: Promise } +>(); + +function keepsProvisionalWorkspace( + draft: DraftSessionState | null, + provisional: ProvisionalWorkspace, +): draft is DraftSessionState { + return ( + draft !== null && + draft.promotedTo == null && + draft.envMode === provisional.envMode && + draft.worktreePath === null && + (provisional.openedManual || draft.environmentSelection !== "manual") + ); +} + +export function readPendingWorkspaceDefault(draftId: DraftId): Promise | null { + const pending = pendingWorkspaceDefaults.get(draftId); + if (pending === undefined) return null; + const draft = useComposerDraftStore.getState().getDraftSession(draftId); + return keepsProvisionalWorkspace(draft, pending) ? pending.settled : null; +} + interface NewThreadWorkspaceOptions { branch?: string | null; worktreePath?: string | null; @@ -129,8 +168,6 @@ export function createNewThreadHandler(router: AnyRouter) { if (composerDraftHasUserContent(getComposerDraft(draftId))) return; setPrompt(draftId, options.prompt); }; - const requestingRouteHref = router.state.location.href; - const routeChangedSinceRequest = () => router.state.location.href !== requestingRouteHref; const currentRouteTarget = getCurrentRouteTarget(); const carrySourceShell = currentRouteTarget?.kind === "server" ? readThreadShell(currentRouteTarget.threadRef) : null; @@ -163,8 +200,6 @@ export function createNewThreadHandler(router: AnyRouter) { candidate.id === projectRef.projectId && candidate.environmentId === projectRef.environmentId, ); - const abandonedSinceRequest = () => - routeChangedSinceRequest() || (project !== undefined && readProject(projectRef) === null); const projectSettings = resolveProjectSettings( targetServerSettings, project?.id ?? null, @@ -199,19 +234,8 @@ export function createNewThreadHandler(router: AnyRouter) { currentRouteTarget?.kind === "draft" ? currentRouteTarget.draftId : null, destinationDraftId, }); - const resolveDefaultEnvMode = async (): Promise => { - // Environment queries wait for a connection, so reading the project file on an - // offline machine would never settle and the draft would never open. - const consultProjectFile = - project !== undefined && - projectSettings.settings.defaultThreadEnvMode === null && - appAtomRegistry - .get(environmentSummaries.connectedEnvironmentIdsAtom) - .includes(project.environmentId); - const projectFile = consultProjectFile - ? await readT3ProjectFile(project.environmentId, project.workspaceRoot) - : null; - return resolveNewThreadEnvMode({ + const envModeFor = (projectFile: T3ProjectFile | null): DraftThreadEnvMode => + resolveNewThreadEnvMode({ projectSettings: resolveProjectSettings( targetServerSettings, project?.id ?? null, @@ -231,25 +255,60 @@ export function createNewThreadHandler(router: AnyRouter) { [], ) > 0, }); + const startFromOriginFor = (envMode: DraftThreadEnvMode) => + resolveNewDraftStartFromOrigin({ + envMode, + newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, + }); + // The draft opens without waiting on t3.json: a cold read takes seconds on a loaded host. + // Its workspace default lands afterwards unless the user picked a workspace or sent first. + const resolveDefaultEnvMode = () => { + // Environment queries wait for a connection, so an offline machine's file is never read. + const consultProjectFile = + project !== undefined && + projectSettings.settings.defaultThreadEnvMode === null && + appAtomRegistry + .get(environmentSummaries.connectedEnvironmentIdsAtom) + .includes(project.environmentId); + if (!consultProjectFile) return { envMode: envModeFor(null), applyProjectFile: () => {} }; + const projectFileRead = readT3ProjectFile(project.environmentId, project.workspaceRoot); + const cachedProjectFile = peekT3ProjectFile(project.environmentId, project.workspaceRoot); + if (cachedProjectFile !== undefined) { + return { envMode: envModeFor(cachedProjectFile), applyProjectFile: () => {} }; + } + const envMode = envModeFor(null); + const applyProjectFile = (draftId: DraftId) => { + const provisional: ProvisionalWorkspace = { + envMode, + openedManual: getDraftSession(draftId)?.environmentSelection === "manual", + }; + const settled = projectFileRead + .then((projectFile) => { + const fileEnvMode = envModeFor(projectFile); + const draft = getDraftSession(draftId); + if (fileEnvMode === envMode || !keepsProvisionalWorkspace(draft, provisional)) return; + // Commit before a waiting send re-reads the composer's workspace. + flushSync(() => + setDraftThreadContext(draftId, { + envMode: fileEnvMode, + ...(draft.startFromOrigin === startFromOriginFor(envMode) + ? { startFromOrigin: startFromOriginFor(fileEnvMode) } + : {}), + }), + ); + }) + .finally(() => { + if (pendingWorkspaceDefaults.get(draftId)?.settled === settled) { + pendingWorkspaceDefaults.delete(draftId); + } + }); + pendingWorkspaceDefaults.set(draftId, { ...provisional, settled }); + }; + return { envMode, applyProjectFile }; }; const logicalProjectKey = project ? deriveLogicalProjectKeyFromSettings(project, projectGroupingSettings) : scopedProjectKey(projectRef); - // Another opener (home's own first-project draft) may have reached this project's draft first. - // Matches lag the location during a navigation, so compare against the location. - const resultIfAbandoned = () => { - const draft = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if (draft === null || draft.promotedTo != null || readProject(projectRef) === null) { - return null; - } - const draftHref = router.buildLocation({ - to: "/draft/$draftId", - params: { draftId: draft.draftId }, - }).href; - return router.state.location.href === draftHref - ? { draftId: draft.draftId, threadId: draft.threadId } - : null; - }; const hasBranchOption = options?.branch !== undefined; const hasWorktreePathOption = options?.worktreePath !== undefined; const hasEnvModeOption = options?.envMode !== undefined; @@ -286,37 +345,17 @@ export function createNewThreadHandler(router: AnyRouter) { const hasExplicitWorkspaceOption = hasBranchOption || hasWorktreePathOption || hasEnvModeOption || hasStartFromOriginOption; let workspaceContext: NewThreadWorkspaceOptions | null = null; + let applyProjectFile: ((draftId: DraftId) => void) | null = null; if (hasExplicitWorkspaceOption) { workspaceContext = pickExplicitWorkspaceOptions(options); } else if (!isDraftAlreadyOpen) { - const defaultEnvMode = await resolveDefaultEnvMode(); - if (abandonedSinceRequest()) { - return resultIfAbandoned(); - } - // Concurrent calls may change the draft; stale resets, remaps, or navigation could clobber it. - const routeTargetNow = getCurrentRouteTarget(); - const openedMeanwhile = - routeTargetNow?.kind === "draft" && - routeTargetNow.draftId === emptyStoredDraftThread.draftId; - const promotedMeanwhile = - storedDraftThreadRef !== null && readThreadShell(storedDraftThreadRef) !== null; - const remappedMeanwhile = - getDraftSessionByLogicalProjectKey(logicalProjectKey)?.draftId !== - emptyStoredDraftThread.draftId; - const investedMeanwhile = composerDraftHasUserContent( - getComposerDraft(emptyStoredDraftThread.draftId), - ); - if (openedMeanwhile || promotedMeanwhile || remappedMeanwhile || investedMeanwhile) { - return null; - } + const defaultEnvMode = resolveDefaultEnvMode(); + applyProjectFile = defaultEnvMode.applyProjectFile; workspaceContext = { branch: null, worktreePath: null, - envMode: defaultEnvMode, - startFromOrigin: resolveNewDraftStartFromOrigin({ - envMode: defaultEnvMode, - newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, - }), + envMode: defaultEnvMode.envMode, + startFromOrigin: startFromOriginFor(defaultEnvMode.envMode), }; } if (workspaceContext) { @@ -356,6 +395,7 @@ export function createNewThreadHandler(router: AnyRouter) { threadId: emptyStoredDraftThread.threadId, }; seedPrompt(emptyStoredDraftThread.draftId); + applyProjectFile?.(emptyStoredDraftThread.draftId); const routeTargetAfterWrites = getCurrentRouteTarget(); if ( routeTargetAfterWrites?.kind === "draft" && @@ -405,44 +445,15 @@ export function createNewThreadHandler(router: AnyRouter) { const threadId = newThreadId(); const createdAt = new Date().toISOString(); return (async () => { - const initialEnvMode = options?.envMode ?? (await resolveDefaultEnvMode()); - if (abandonedSinceRequest()) { - return resultIfAbandoned(); - } - // Reuse drafts registered while awaiting so their pending navigation cannot lose them. - const racedDraft = getDraftSessionByLogicalProjectKey(logicalProjectKey); - if ( - racedDraft && - racedDraft.draftId !== storedDraftThread?.draftId && - readThreadShell(scopeThreadRef(racedDraft.environmentId, racedDraft.threadId)) === null - ) { - setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, racedDraft.draftId, { - threadId: racedDraft.threadId, - createdAt: racedDraft.createdAt, - runtimeMode: racedDraft.runtimeMode, - interactionMode: racedDraft.interactionMode, - ...pickExplicitWorkspaceOptions(options), - }); - seedPrompt(racedDraft.draftId); - await router.navigate({ - to: "/draft/$draftId", - params: { draftId: racedDraft.draftId }, - replace: options?.replace ?? false, - }); - return { draftId: racedDraft.draftId, threadId: racedDraft.threadId }; - } + const defaultEnvMode = options?.envMode === undefined ? resolveDefaultEnvMode() : null; + const initialEnvMode = options?.envMode ?? defaultEnvMode?.envMode ?? "local"; setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, { threadId, createdAt, branch: options?.branch ?? null, worktreePath: options?.worktreePath ?? null, envMode: initialEnvMode, - startFromOrigin: - options?.startFromOrigin ?? - resolveNewDraftStartFromOrigin({ - envMode: initialEnvMode, - newWorktreesStartFromOrigin: projectSettings.settings.newWorktreesStartFromOrigin, - }), + startFromOrigin: options?.startFromOrigin ?? startFromOriginFor(initialEnvMode), runtimeMode: defaultRuntimeMode, ...(carryInteractionMode ? { interactionMode: carryInteractionMode } : {}), }); @@ -452,6 +463,7 @@ export function createNewThreadHandler(router: AnyRouter) { setModelSelection(draftId, modelSelectionOverride, { replaceOptions: true }); } seedPrompt(draftId); + defaultEnvMode?.applyProjectFile(draftId); await router.navigate({ to: "/draft/$draftId", params: { draftId }, diff --git a/apps/web/src/i18n/I18nProvider.tsx b/apps/web/src/i18n/I18nProvider.tsx index d676e7f72b58e..5fbd532a86b48 100644 --- a/apps/web/src/i18n/I18nProvider.tsx +++ b/apps/web/src/i18n/I18nProvider.tsx @@ -1,10 +1,14 @@ import { GTProvider } from "gt-react"; import { useSyncExternalStore, type ReactNode } from "react"; -import { getI18nSnapshot, persistGTLocale, subscribeI18n } from "./runtime"; +import { getFormattingLocale, getI18nSnapshot, persistGTLocale, subscribeI18n } from "./runtime"; const reloadToSetting = (state: { readonly locale: string }) => persistGTLocale(state.locale); +export function useFormattingLocale(): string | undefined { + return useSyncExternalStore(subscribeI18n, getFormattingLocale); +} + export function I18nProvider({ children }: { readonly children: ReactNode }) { const { locale, translations } = useSyncExternalStore(subscribeI18n, getI18nSnapshot); return ( diff --git a/apps/web/src/i18n/locales.test.ts b/apps/web/src/i18n/locales.test.ts new file mode 100644 index 0000000000000..66d23e2170ba7 --- /dev/null +++ b/apps/web/src/i18n/locales.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveWebLocaleSelection } from "./locales"; + +describe("resolveWebLocaleSelection", () => { + it.each([ + ["system", ["en-GB"], "en", undefined], + ["system", ["zh-TW", "en-GB"], "en", undefined], + ["en", ["en-GB"], "en", undefined], + ["en", ["de-DE"], "en", "en"], + ["de", ["en-US"], "de", "de"], + ] as const)("%s with browser languages %j", (language, browserLocales, catalog, formatting) => { + expect(resolveWebLocaleSelection(language, browserLocales)).toEqual({ + catalogLocale: catalog, + formattingLocale: formatting, + }); + }); +}); diff --git a/apps/web/src/i18n/locales.ts b/apps/web/src/i18n/locales.ts index 26ac5721e4915..a9c6e20eddedd 100644 --- a/apps/web/src/i18n/locales.ts +++ b/apps/web/src/i18n/locales.ts @@ -1,4 +1,15 @@ +import { resolveLocale } from "@t3tools/client-runtime/locales"; + import gtConfig from "../../gt.config.json"; export const DEFAULT_LOCALE = gtConfig.defaultLocale; export const SUPPORTED_LOCALES: ReadonlyArray = [DEFAULT_LOCALE, ...gtConfig.locales]; + +export function resolveWebLocaleSelection(language: string, browserLocales: ReadonlyArray) { + const catalogLocale = resolveLocale(language, browserLocales, SUPPORTED_LOCALES, DEFAULT_LOCALE); + // Undefined formats with the host locale: "system", and English over a regional English browser. + const keepEnglishRegion = + language === DEFAULT_LOCALE && /^en(?:-|$)/i.test(browserLocales[0] ?? ""); + const formattingLocale = language === catalogLocale && !keepEnglishRegion ? language : undefined; + return { catalogLocale, formattingLocale }; +} diff --git a/apps/web/src/i18n/runtime.ts b/apps/web/src/i18n/runtime.ts index 188d296befd48..940a3a3f0b70c 100644 --- a/apps/web/src/i18n/runtime.ts +++ b/apps/web/src/i18n/runtime.ts @@ -1,4 +1,3 @@ -import { resolveLocale } from "@t3tools/client-runtime/locales"; import { getTranslationsSnapshot } from "gt-react"; import { @@ -7,21 +6,29 @@ import { updateClientSettings, } from "../hooks/useSettings"; import { initializeI18n } from "./initializeI18n"; -import { DEFAULT_LOCALE, SUPPORTED_LOCALES } from "./locales"; +import { DEFAULT_LOCALE, resolveWebLocaleSelection } from "./locales"; import { setActiveLocale } from "./messages"; type LocaleTranslations = Awaited>; export interface I18nSnapshot { readonly locale: string; + readonly formattingLocale: string | undefined; 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; +let snapshot: I18nSnapshot = { + locale: DEFAULT_LOCALE, + formattingLocale: undefined, + translations: { ...loadedTranslations }, +}; +let requestedLocale: ReturnType = { + catalogLocale: DEFAULT_LOCALE, + formattingLocale: undefined, +}; function loadLocale(locale: string): Promise { if (locale in loadedTranslations) return Promise.resolve(); @@ -42,11 +49,16 @@ function loadLocale(locale: string): Promise { } function activateLocale(locale: string): void { - if (requestedLocale !== locale) return; - if (snapshot.locale === locale && snapshot.translations[locale] === loadedTranslations[locale]) { + if (requestedLocale.catalogLocale !== locale) return; + const { formattingLocale } = requestedLocale; + if ( + snapshot.locale === locale && + snapshot.formattingLocale === formattingLocale && + snapshot.translations[locale] === loadedTranslations[locale] + ) { return; } - snapshot = { locale, translations: { ...loadedTranslations } }; + snapshot = { locale, formattingLocale, translations: { ...loadedTranslations } }; setActiveLocale(locale); document.documentElement.lang = locale; for (const listener of listeners) listener(); @@ -54,12 +66,7 @@ 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, - SUPPORTED_LOCALES, - DEFAULT_LOCALE, - ); + requestedLocale = resolveWebLocaleSelection(getClientSettings().language, navigator.languages); void whenLocaleReady(); } @@ -76,7 +83,7 @@ export function startI18n(): void { /** Resolves once the requested locale's translations are ready; immediate for English. */ export function whenLocaleReady(): Promise { - const locale = requestedLocale; + const locale = requestedLocale.catalogLocale; return loadLocale(locale).then(() => activateLocale(locale)); } @@ -90,3 +97,7 @@ export function subscribeI18n(listener: () => void): () => void { export function getI18nSnapshot(): I18nSnapshot { return snapshot; } + +export function getFormattingLocale(): string | undefined { + return snapshot.formattingLocale; +} diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 48ad4af96df9f..caa82b0777d44 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installiere {fj} 0.6 oder neuer von {fjUrl} und führe {fjLogin} aus, oder installiere {tea} 0.16 oder neuer von {teaUrl} und führe {teaLogin} für jeden Forgejo- oder Gitea-Server aus.", "d026a85e2e50e675": "Installiere die GitCafe CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", "22d3c0c48a34b5b3": "Installiere die TanStack Source CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", + "756c80ad262ef315": "Wartet im ursprünglichen Thread", + "d8df14f9905f38eb": "Gesendet", + "e7c59185f8ab3987": "Nicht gesendet", + "b54ddec9084fa955": "Ohne Senden geschlossen", + "fbaa7ab5da716e50": "Fehler", + "01bac997ea55272e": "Unverständlich", + "0f53bc8f74dfe56a": "Fehlende Funktion", + "055560f307e15e30": "Falsche Dokumentation", + "78344b60f407928e": "Sonstiges", + "f653846a95cd6e8f": "Art", + "f41ea186c275b56e": "Info", + "2f6e4f7cd364da73": "Erwartet", + "9d11c93d4035de3e": "Tatsächlich passiert", + "c87d0595693704f9": "Stattdessen getan", + "d7a4ea6ce5af44e0": "{speaker} · {count} Zeichen", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Runde {turn} · {what}", + "dfdaa6255a416140": "Übersicht über {turns, plural, one {{turns} letzte Runde} other {{turns} letzte Runden}}, {textTurns, plural, =0 {ohne Nachrichtentext} one {mit dem Nachrichtentext der letzten Runde} other {mit den Nachrichtentexten der letzten {textTurns} Runden}}{truncated, select, yes {, passend gekürzt} other {}}", + "afac52a5cc2dc801": "Deine Antwort konnte nicht gesendet werden. Versuche es erneut.", "79d776428f4d0650": "Die Datei konnte nicht geladen werden. Verbinde dich erneut und versuch es noch einmal.", "3ea34cbb1ca5ba9b": "Vorschau abgebrochen.", "7c0af279ecb3da3a": "Streamende Dateivorschauen sind in dieser Laufzeitumgebung nicht verfügbar.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} an", "77cc5f738cb7d459": "{label} aus", - "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", "aba3bb73ce212f0c": "{names} erfordert {providerName} {version} oder neuer, aber der Homebrew-Cask claude-code hat nur {latestVersion}. Wechsle zum Cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", "d887bea446534de5": "Kein Projekt in dieser Umgebung kann {host}/{repository} lesen.", "4e466d60e2f7736b": "Füge die vollständige Pull-Request-URL ein. Dieser Thread hat kein Repository, in dem die Nummer aufgelöst werden kann.", "302625058bacbe38": "Füge eine vollständige URL ein. Für den Host dieses Projekts ist kein {changeRequest}-URL-Format bekannt.", @@ -376,6 +396,31 @@ "476ca970255eaea4": "Verknüpfe diese Umgebung mit T3 Connect, um eine öffentliche URL zu erhalten.", "6b80f5b38a8f9950": "Nur dieser Computer kann diese Adresse aufrufen. Verknüpfe T3 Connect für eine öffentliche URL.", "c5a7b1d3891dd0b8": "Funktioniert überall, wo die Adresse dieser Umgebung erreichbar ist, zum Beispiel über Tailscale oder deinen eigenen Proxy. Verknüpfe T3 Connect für eine öffentliche URL.", + "3669395daf36fd33": "Auf diesem Server nicht mehr registriert", + "fe513cf316e796e3": "Läuft als Teil anderer Workflows", + "ccf00b97925efab3": "Wird von Hand gestartet", + "421e585eb092b07b": "Startet bei {triggers}", + "7bd7c58592671384": "Braucht dich", + "834ca879c14c167b": "Arbeitet", + "582d6df7dfab86fb": "Pausiert", + "ea6583ce92507ee3": "Schläft", + "7ea8cb8af281ce93": "Wartet", + "1347868f2523140e": "Fertig", + "57d76c4614054271": "Gestoppt", + "5c7344bd51d0b966": "Übersprungen", + "b2074e9bd23049a6": "Abgebrochen", + "5bb7401807ee2fb5": "Fragt: {question} und {more} weitere", + "9e4286183d5f9e34": "Fragt: {question}", + "474c18d001bd6717": "Ein Schritt ist fehlgeschlagen", + "d3890f4eb1508781": "Führt eigene Schritte aus", + "3e7ced10c9482af0": "{step} arbeitet", + "237e1bcb1cf1bdec": "Schläft bei {step}", + "3f7b17ac5a20c8d2": "Führt {run} aus", + "0306f5f324b8aaa5": "{count} Ausführungen laufen", + "e8fd779b84a202a2": "Wartet", + "b6d55657e1a027b8": "Wartet auf {step}", + "e942562a42aede34": "Abgeschlossen", + "26b2b9727fe11289": "Vorzeitig beendet", "1bb995dcec481554": "Genehmige dieses Gerät auf {host}. Dort wird der Code {verificationCode} angezeigt.", "8696a33219944832": "Der Autorisierungsnachweis für die WebSocket-Verbindung konnte nicht erstellt werden.", "5678f133a8631f7d": "Deine Cloud-Anmeldung hat sich geändert. Melde dich erneut an, um die Umgebung zu autorisieren.", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -1719,6 +1767,8 @@ "2e995206e087c3fc": "Versuche zu antworten, sobald die Verbindung oder ausstehende Eingabe geklärt ist.", "604ec3067171a0d7": "Unterhaltung", "d6182a057ea12624": "Übergeordneter Thread", + "f2d8537c33cc55a5": "Schritt der Workflow-Ausführung", + "ba8337dca3232880": "Ausführung öffnen", "30fa4a764d11ae42": "{name} konnte nicht heruntergeladen werden", "4952f87dc98191a7": "Der Anhang ist nicht verfügbar.", "2fd6d178493fb407": "Die aktuelle Runde konnte nicht unterbrochen werden.", @@ -1804,6 +1854,7 @@ "04fd71efaa2c3b92": "Pull Requests öffnen", "57e875b79b98ab82": "Issues öffnen", "f1db0a234c777a1d": "T3 Code in einer anderen App verwenden (MCP)", + "6050f22f63e2bcb5": "Workflows öffnen", "a0cc19e60dd99851": "Nutzung öffnen", "46694969044eee98": "Nächsten Arbeitsbereich fokussieren", "0a1011328ba42eef": "Vorherigen Arbeitsbereich fokussieren", @@ -2496,8 +2547,7 @@ "2d1c111e1b4ae0b0": "Thread „{title}“ löschen?", "c568ab8dad798ec5": "Dadurch wird der Gesprächsverlauf dieses Threads dauerhaft gelöscht.", "0fd1c746a0e38003": "Thread konnte nicht gelöscht werden", - "0ecde875b0dd2f93": "Threads nach Projekt filtern: {projects}", - "1ef65b647231ff0b": "Threads nach Projekt filtern", + "1c8fc3c4a42949ab": "Projekte: {projects}", "165511761be2855c": "Projekte durchsuchen", "a46a6467883575a4": "Projekte durchsuchen...", "fdc0e086438a3045": "Projekteinstellungen für {project}", @@ -2560,10 +2610,9 @@ }, " installieren" ], + "b4b98a0287c282e2": "Auf einem anderen Rechner, daher kann der Agent dieses Rechners es nicht lesen. Entferne es oder wechsle zum Senden zurück.", "5bbac0e5afeec779": "Aktueller Thread", "33c7e68fca089036": "Thread, {title}", - "b4b98a0287c282e2": "Auf einem anderen Rechner, daher kann der Agent dieses Rechners es nicht lesen. Entferne es oder wechsle zum Senden zurück.", - "c6196d99000642b4": "Thread öffnen", "34cc63390ad793cc": "Thread wählen", "8f12309ead62e38a": "Threads oder Projekte durchsuchen...", "2f664754d005d9a7": "Keine aktiven Threads gefunden.", @@ -2573,6 +2622,7 @@ "a3178769f8308cbc": "Thread fehlgeschlagen", "89b5e8f3887812da": "Gastanfrage", "62e626804919b294": "Eingabe nötig", + "c6196d99000642b4": "Thread öffnen", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", @@ -2596,8 +2646,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminal-Prozess läuft", "fc2c9a91f498ad6b": "{count, plural, one {{count} Terminal-Prozess läuft. Terminal öffnen} other {{count} Terminal-Prozesse laufen. Terminal öffnen}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "Stack", "6831e9a46cbd8939": "Kette", "9aa9e74a3b7eee91": "Zum Chat hinzufügen", @@ -3034,8 +3082,8 @@ "6f85f14f35b3f547": "{provider} über {environment}", "7c59a888a062a8bd": "Die Spracheingabe hat keinen Entwurf, in den sie aufnehmen kann.", "62450481c00d2ef3": "Die Umgebung des Entwurfs ist für die Transkriptbereinigung nicht verfügbar.", - "c64cb58d9cecbcd2": "Transkriptbereinigung fehlgeschlagen", "0674544195fcdc39": "Das ursprüngliche Transkript wurde eingefügt.", + "c64cb58d9cecbcd2": "Transkriptbereinigung fehlgeschlagen", "296496693cdac0db": "Der t3-Befehl ist nicht verfügbar.", "efbcef7bc9bbda01": "Der Status des t3-Befehls konnte nicht geladen werden.", "1bf6910332426e62": "Netzwerkzugriff des Desktops ist nicht verfügbar.", @@ -3278,6 +3326,7 @@ "4d493d0bda4d403d": "Hänge die unterbrochene Datei erneut an oder entferne sie", "c9cad1d84d5f1a32": "Hänge die unterbrochenen Dateien erneut an oder entferne sie", "536a820f2ff726da": "Wähle mindestens ein Modell.", + "48d6389202ad6754": "Wird gesendet, sobald bereit", "fbafbe78b5e37966": "Thread fortsetzen", "bcd7eb979dd38dae": "Eingabefeld öffnen, um zu komprimieren und zu senden", "95ee62a0d6968b89": "Nachricht senden", @@ -3454,6 +3503,9 @@ "e778e4f446fdf873": "Deine nächste Nachricht startet eine neue Sitzung", "0e2f2da4f2d94785": "Der Agent sieht frühere Nachrichten in diesem Thread nicht.", "e1189d2e582b008d": "Aktuelle Sitzung behalten", + "2bb448d605877a22": "Zum Abbrechen bearbeiten oder Esc drücken", + "1a1f128d70c62304": "{count, plural, one {Wird gesendet, sobald das Bild bereit ist} other {Wird gesendet, sobald {count} Bilder bereit sind}}", + "5af3ab719a9725fb": "Nachricht wird gesendet", "461c9f865f2e9b92": "{option} an", "f2aa17b5c620f2a4": "{option} aus", "f59314a884aae1ff": "Standard", @@ -3577,6 +3629,14 @@ "c53bc5a4b0314342": "Nächstes Medium", "2950b1424a3cddf5": "Verbinde dich erneut mit dieser Umgebung und öffne das Medium noch einmal.", "ef638bf1479a5461": "Die Umgebung hat eine ungültige Medien-URL zurückgegeben.", + "3ccfbf7e86868c35": "Feedback für das T3-Team", + "4e0710d19dfc2e7e": "Diesen Bericht an das T3-Team senden?", + "87d0ae0723ba75d1": "Das ist alles, was deinen Rechner verlässt. Erst wenn du auf Senden klickst, wird etwas gesendet.", + "bf19826f81484328": "Unterhaltung mitsenden", + "260c6b45f52d2f27": "Fügt den Text deiner Nachrichten und der Antworten des Agenten aus {textTurns, plural, one {der letzten Runde} other {den letzten {textTurns} Runden}} hinzu.", + "ddb7e6f8ce99e657": "Nur wer auf diesem Rechner Agenten ausführen kann, kann den Bericht senden oder ablehnen.", + "03c1eb603c112f47": "Nicht senden", + "653405e4ed498d9f": "Senden", "262955d6eb632f9b": "Die Zwischenablage-API ist beim Kopieren des Gast-Links nicht verfügbar.", "f1a4f2b04cdbb4ef": "Der Gast-Link konnte nicht in die Zwischenablage kopiert werden.", "cf3490a604e44d31": "Gastlink konnte nicht erstellt werden.", @@ -3597,7 +3657,6 @@ "abd89e9eefedf11b": "Fertig", "18d166056c1ab6ff": "Freigabe beenden", "7a2d510eac9e4587": "Gastlink abgelaufen", - "653405e4ed498d9f": "Senden", "21888e302219891d": "Vergrößerte Vorschau von {title}", "419719298a7acaea": "Verkleinern", "ed8d5db95359cff4": "Zoom zurücksetzen", @@ -3693,7 +3752,6 @@ "7c1923203049d602": "Code kopieren", "637817e4ff79c90e": "Aktionen für Codeblock", "ebf3a2b1e314aa5f": "Im Terminal ausführen", - "fe219642547fa0bf": "Im Terminal ausführen", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Vollständiger Pfad", "f37e7d36b51c5b28": "Relativen Pfad kopieren", @@ -3705,10 +3763,6 @@ "4967584e8d0fb1c2": "Medienvorschau", "67589dd912eacb7c": "Im integrierten Browser öffnen", "a3c98d4c4b24cecb": "Dateioptionen für {label}", - "b4fe8a076e9fd2f8": "Abgesetzte Formel", - "085d1407e8c92cce": "Formel im Text", - "a2ef393fa7b48ae8": "Abgesetzte Formel scrollen", - "e94685ea5642e088": "Formel im Text scrollen", "3a04583c8500e23d": "Diagramm anzeigen", "16d64f650840fe06": "Code anzeigen", "6d329f7d3a50c7e7": "Tabelle kopieren", @@ -3987,9 +4041,11 @@ "973e99fa86d7f531": "Eingereihte Nachricht {position} von {total}, nicht gesendet", "0f6087c4f53c7f17": "Eine Runde mit dieser Nachricht starten ({shortcut})", "adab89933af02669": "Komprimierung überspringen und diese Nachricht senden ({shortcut})", + "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", "3de4016452e8d2bd": "In die aktuelle Runde senden ({shortcut})", "259cc9568148e8ad": "Eine Runde mit dieser Nachricht starten", "bb7fddb812d5d29e": "Komprimierung überspringen und diese Nachricht senden", + "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben", "a5fe1ee609b29a9f": "In die aktuelle Runde senden", "2b7fd345e4f4fd6e": "Bearbeiten der eingereihten Nachricht abbrechen", "47f1726bf106d2c8": "Eingereihte Nachricht bearbeiten", @@ -5599,7 +5655,6 @@ }, ". Prüfe den Pfad des Links oder suche die Datei unter Dateien." ], - "b9b6bbd1e1ea189f": "Ganze Datei", "d715e9494fdbaaf6": "Die Schriftart konnte nicht geladen werden.", "ff17c777a72b4408": "Schriftvorschauen sind auf 10 MB begrenzt.", "6bd41ad699e22f10": "Die Schriftart ist nicht verfügbar.", @@ -5609,6 +5664,7 @@ "a9abaaa4220eae21": "{error} Speichere sie, um sie in einer anderen App zu öffnen.", "c508c9000d9656f8": "Schriftvorschau", "1c416d621d250be8": "Victor jagt zwölf Boxkämpfer quer über den großen Sylter Deich.", + "d7d08260f16b7828": "Die Datei wird noch geladen. Versuche es gleich noch einmal.", "76ebb03de52c92d6": "Der Textbetrachter wurde beendet.", "f48162e8e8c12af7": "Der Textbetrachter konnte nicht geladen werden. Schließe die Datei und versuche es erneut.", "bc4c5b13d38a5da7": "Vorschau geschlossen.", @@ -5616,8 +5672,6 @@ "9450d1827ef336a1": "Ein anderer Kopiervorgang läuft.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} Zeile} other {{formatted} Zeilen}}", "13b14784f8707ddd": "0 Byte", - "f6e9581cba3467fa": "Wird indiziert…", - "2d1f293ac12463fc": "Der Rest der Datei wird geladen…", "b75105bef8f564a4": "Die ersten 1.024 Spalten werden angezeigt. Quelltext und Speichern behalten alle Spalten.", "2a6e1b1f209c3888": "Diese Datei ist leer.", "192fc79eb3b5b2cb": "Dieses Diagramm enthält Ressourcen-URLs, Markup, Knotenmetadaten oder eine benutzerdefinierte Konfiguration. Zeige den Mermaid-Quelltext an, um es sicher zu prüfen.", @@ -5804,7 +5858,6 @@ "0061fff77e36bd4f": "Der Server ist nicht erreichbar.", "04dfdd46e3dd4a2e": "Etwas ist schiefgelaufen. Versuche es erneut.", "084bb2d8127a508d": "Gesendet", - "e7c59185f8ab3987": "Nicht gesendet", "77c01a15bd36d17c": "Dieser Link ist abgelaufen oder ungültig", "e0e736810f3cbef2": "Bitte den Besitzer um einen neuen Link. Jeder Link funktioniert in einem Browser.", "c3c53aa46f7330e5": "Dieser Link ist abgelaufen", @@ -8829,6 +8882,12 @@ "d3866ead082d14e5": "Tastenkürzel hinzufügen", "d4345c90894a3220": "keybindings.json öffnen", "e56a8d51219efaa0": "Keine Tastenkürzel entsprechen deiner Suche.", + "90a258fff61fd77e": "Aus", + "4060244a7079a0d2": "Wenn ich darum bitte", + "e88c9d8769544731": "Automatisch", + "f29d1dade4dde8aa": "Agenten senden kein Feedback an das T3-Team.", + "93c4c53562d30a98": "Wenn du darum bittest, zeigen Agenten dir einen kurzen Bericht über T3 Code und senden ihn mit deiner Zustimmung an das T3-Team.", + "cd9ee803e8727017": "Agenten melden auch selbstständig Probleme mit T3 Code, auf die sie stoßen, etwa ein fehlgeschlagenes T3-Tool.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Threads in der Seitenleiste in Projektordnern gruppieren. Angeheftete Threads bleiben oben, Zurückgestellte und Erledigte bleiben unter den Ordnern.", "e4e91d155cb6a9b4": "Schlichte Seitenleiste (nach Projekt gruppieren)", @@ -8837,11 +8896,16 @@ "9ae293971d93c819": "Teile einen Thread mit einem Gast, der ihn live im Browser verfolgt und Nachrichten sendet, die du genehmigst. Melde dich bei T3 Connect an, um Gastlinks zu nutzen.", "0aa5406ac4d7f7c7": "Gastlinks", "f0e853acd2006d53": "Verknüpfte Umgebungen", + "ef10c2dff987f3ea": "Führe mehrstufige Workflows aus Dateien im Ordner workflows des T3-Home dieses Servers aus. Öffne sie über die Befehlspalette. Solange es aus ist, läuft nichts aus diesem Ordner; Läufe warten, bis es wieder an ist.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Nach einer Claude- oder Codex-Runde eine vorhergesagte nächste Nachricht im leeren Eingabefeld anzeigen. Tab übernimmt sie. Jede ist eine zusätzliche gecachte Anfrage in deinem Tarif. Erfordert Codex 0.165+. Claude-Threads werden nach einem Neustart aktualisiert.", "d4b2a2ec812aafb0": "Nächsten Prompt vorschlagen", "298c7150a7621c80": "Simlock-Geräte-Hosts", "67937aa49179285e": "Auf einem Mac neue Worktrees aus einem im T3-Home-Ordner zwischengespeicherten Checkout klonen, statt jede Datei zu schreiben. Verwendet den normalen Git-Checkout, wenn das nicht geht. Beim Ausschalten wird der Cache gelöscht.", "f9904f78d3003f58": "Schneller Worktree-Checkout", + "9c2f647882522302": "Die ausgewählten Rechner verwenden unterschiedliche Modi für Agenten-Feedback.", + "31bbf7bf8c0a5279": "Agenten-Feedback", + "d52b3d6bf9f2a013": "Gemischt", "ec7623deed751c05": [ "Teile einen Thread mit einem Gast, der ihn live im Browser verfolgt und Nachrichten sendet, die du genehmigst. Erfordert T3 Connect: Melde dich an und verknüpfe diesen Rechner unter", " ", @@ -8925,7 +8989,9 @@ "fb71127e5746a6bc": "Unter „Freigabe & Zugriff“ dort oder mit t3 pair", "1e3fee7084791773": "Auch {target} zurück mit {source} verknüpfen", "ea34a190b0bd804c": "Agenten auf {target} können dann auch auf {source} arbeiten.", - "ad5ed0ce61b966eb": "{label} vergessen? Agenten von hier arbeiten dort nicht mehr. Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", + "974f8c65e8b5f492": "{label} vergessen? Agenten hier arbeiten dort nicht mehr, und ihre Sitzung auf {label} endet ebenfalls, wenn es antwortet.", + "6cf9e3083b15614f": "{label} hat nicht geantwortet", + "34ccbdf619b83be3": "Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", "81c9796bf61b306a": "Verknüpfung konnte nicht vergessen werden", "130e51beb6cf5aad": "Umgebung verknüpfen", "122c3e355699e69d": "Agenten hier können dort dann Threads starten, ihnen Nachrichten senden und auf sie warten. Sie erscheint unter „Autorisierte Clients“ in „Freigabe & Zugriff“ dieser Umgebung und kann dort widerrufen werden.", @@ -9154,7 +9220,6 @@ "0b4779a1825c85bc": "Der gemeinsame Name dieser Projektgruppe in der Seitenleiste und in Thread-Listen.", "f68cbda4df83d739": "Projektname auf Standard zurücksetzen", "56e37b85027e8431": "Projektsymbol", - "e88c9d8769544731": "Automatisch", "c99736317da5b1fa": "Projektsymbol auf Standard zurücksetzen", "6afaa3e3739dc570": "Projektsymbol auswählen", "51651ce45d481a20": "Datei für Projektsymbol auswählen", @@ -10128,7 +10193,6 @@ "a0eb0e4f76608833": "Verknüpfte Pull Requests zuerst öffnen. Andernfalls „Änderungen“ bei Bearbeitungen an mindestens 3 Dateien oder 50 Zeilen öffnen.", "16bdc70b858c223f": "Proaktive Panels auf Standard zurücksetzen", "3e99c5c14f4939c8": "Inaktive Threads komprimieren auf Standard zurücksetzen", - "d52b3d6bf9f2a013": "Gemischt", "cd72fe451ba0d6aa": "Neue Projekte", "394c3bd0a1782c8e": "Leer lassen, um „~/“ zu verwenden, wenn sich der Dialog „Projekt hinzufügen“ öffnet.", "f9b912a818bd869d": "Basisverzeichnis für neue Projekte auf Standard zurücksetzen", @@ -11030,7 +11094,6 @@ "4a237f41ce592b7f": "Die Worktrees dieses Projekts behalten, bis du sie manuell löschst.", "00b8ffd8ea6e6a93": "Diese Regeln für dieses Projekt verwenden.", "72c279824d15a999": "Die Worktree-Bereinigungseinstellungen jedes Rechners verwenden.", - "90a258fff61fd77e": "Aus", "b5702d0b64866b08": "Benutzerdefiniert", "c009c901f3eefe78": "Worktrees gelöschter Threads löschen", "431c7cd6d50102b7": "Ungenutzte Worktrees entfernen, wenn aktive oder archivierte Threads gelöscht werden. Worktrees mit lokalen Änderungen bleiben erhalten.", @@ -11727,7 +11790,6 @@ "4c70e3e7b3e6c493": "Geheimnisse", "79b768229c9ef672": "Wartung", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Info", "af4b7734da1d5ce7": "Spracheingabe", "4ec62c39ca3192bf": "Versionskontrolle & Issues", "f2bf529f85e05494": "Freigabe & Zugriff", @@ -11782,6 +11844,7 @@ "d443390c4d2dcfd4": "barrierefreiheit a11y screenreader nvda jaws voiceover orca sprachausgabe fenstertitel tab-titel alt tab taskleiste thread status reihenfolge arbeitet genehmigung", "6826fa9579c22035": "beta teilen gast einladen link teammitglied zuschauen t3 connect tunnel", "f10c06cba0cdf7fe": "beta anderen rechner verknüpfen vps peer agenten dort arbeiten delegieren", + "bc0b409d89ce086e": "beta workflow dauerhafte läufe automatisierung schritte zeitplan webhook ordner", "4a21cf825a2045b0": "beta tab autovervollständigung nächste nachricht vorhersagen claude codex ghost text", "fea2dc36585c4a20": "Simlock-Geräte-Hosts (Alpha)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", @@ -11853,6 +11916,7 @@ "901a823214edc8c4": "telemetrie analyse nutzungsdaten tracking rechtliches deaktivieren", "82136480255a5106": "OTel OTLP telemetrie export endpunkte logs traces metriken Grafana", "659d081051faf7ff": "logs traces prozesse ressourcenverlauf fehler spans cpu speicher", + "5eaeacfa9f82051a": "bericht fehler problem t3 team senden feedback agenten tools automatisch wenn ich darum bitte", "f537f91e1ee41d47": "tastenkürzel hotkeys befehle tastenzuweisungen json", "1ba01e7ceed64b95": "fenster aufnahme bildschirmfoto", "279b1cceb779ff38": "App-Text einbeziehen", @@ -12322,7 +12386,6 @@ "0bd41ff995d36a66": "Cache-Lesen", "3f0dfe0cb15a3272": "Cache-Schreiben", "1c9d860be42b1c02": "Ausgabe", - "78344b60f407928e": "Sonstiges", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Schnell", "66796576034c18ea": "Ultraschnell", @@ -12338,6 +12401,262 @@ "2cddd6095abc734a": "7 Tage", "53493056306708cf": "30 Tage", "c719359d18d37ad3": "90 Tage", + "0bd950151ddc6407": "Ohne Speichern verlassen? Deine Änderungen an dieser Datei gehen verloren.", + "c0ba3f6756b09f30": "Ungespeicherte Änderungen", + "6914e22d357f0ad6": "Gespeichert und aktiv", + "aff389354a031d6f": "Die Datei auf der Festplatte lässt sich nicht laden. Die letzte funktionierende Version läuft weiter.", + "858effde748ab563": "Gespeichert, läuft aber noch nicht.", + "ddb37138df660942": "Nicht gespeichert. Auf dem Server hat sich nichts geändert.", + "6ef4db489e40e39e": "Speichern fehlgeschlagen", + "c89624a2e9af1793": "{name} ist nicht verbunden", + "b5a352a43adb4c17": "Ihre Workflows erscheinen wieder, sobald sie sich neu verbindet. Wähle eine andere Umgebung, um deren Läufe zu sehen.", + "3dcedb736d20aae5": "Die Workflow-Dateien konnten nicht gelesen werden", + "b09f4df8d76ae8ea": "{file} löschen? Die darin definierten Workflows können dann nicht mehr gestartet werden.", + "b4535f5a03689d27": "{name} ist nicht verbunden. Was du hier schreibst, bleibt erhalten und lässt sich speichern, sobald die Verbindung wieder da ist.", + "b54c78d85fd942ea": "Gelöscht, aber was läuft, ist noch nicht nachgezogen.", + "407c228d7da0b7df": "Nicht gelöscht. Auf dem Server hat sich nichts geändert.", + "1a6aa10f3cc14fff": "Diese Dateien passen nicht zusammen. Was bisher lief, läuft weiter.", + "259312516a1dbe6f": "Dateiname", + "2f48ab2aa0586853": "Definiert keine Workflows", + "ba5adfa37b55b8c5": [ + "Zeile ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Löschen", + "84c900d1ae72adc6": "Speichern", + "5912d817be03247a": "Die Datei wurde auf der Festplatte geändert, während du sie bearbeitet hast. Speichern ersetzt diese Änderung.", + "0b1e6f5608826387": "Datei laden und meine Änderungen verwerfen", + "f47b4c06aeb77c1c": "Workflow-Dateien werden geladen…", + "4353bfd401d58f87": [ + "Jede Datei in", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "definiert Workflows. Änderungen werden ohne Neustart übernommen." + ], + "0c165251a06f10f1": "Neue Datei", + "8e97cf734b4463e7": "Erstellen", + "2ec0d5108fd6cebe": "Noch keine Workflows. Erstelle hier die erste Datei oder bitte einen Agenten, eine in diesem Ordner zu schreiben.", + "5601350626e8cfe9": "Lässt sich nicht laden", + "21d778a1b9a0c234": "Neben der Ausführung geöffnet", + "62dc4d3a19ff7ca0": "Tab schließen", + "1e25265f2758fce3": "Als vollständigen Thread öffnen", + "672a3dae06b39402": "Auf eigener Seite öffnen", + "7755500a4cde5066": "Bereich schließen", + "b8dcbc93a2ca1861": "Diese Ausführung führt es nicht mehr auf.", + "115c69de3202f664": "Öffnen", + "644eafa9048b62df": "{count, plural, =1 {1. Versuch} =2 {2. Versuch} =3 {3. Versuch} other {{count}. Versuch}}", + "e39f89c909df4db0": "Die Ausführung konnte nicht fortgesetzt werden", + "865f034346b82f47": "{title} abbrechen? Die Agenten stoppen und die Ausführung kann nicht fortgesetzt werden.", + "6bc75632fd9c9136": "Die Ausführung konnte nicht abgebrochen werden", + "64e50329dcfdd5b0": "Abgeschlossen", + "350162e7cc1ebea4": "Gestoppt", + "0875cf506f4c6810": "Übersprungen", + "3cc43f1dbf3f8e0c": "Abgebrochen", + "ded70e75de6404ba": "Zurück zur Liste der Ausführungen", + "2f4ed7dbd22be30d": "Ausführung abbrechen", + "614e5ad58a795fb5": "Stoppen", + "04b050b0329f0ac8": "dauerte {duration}", + "aff78e1774818ff4": "bisher {duration}", + "38eddd466439afc9": "Was die Ausführung berührt hat", + "156ec271d49ddd70": "Was passiert ist", + "34f59bbbead0b97f": "{names} und {count} weitere", + "ac1556f6ce89a5ea": "{count} parallel", + "e197c4963bacc746": "{count} laufen", + "f5319ed9e18c0df1": "Fragt dich", + "882a25e9084ae1b2": "Pausiert", + "9a03d8a9afc60387": "Bisherige Schritte", + "2f2ae791afe01674": "wartet auf deine Freigabe", + "24f8060c4ccdf928": "startet", + "30a5be40eb956663": "arbeitet", + "dd7a1e58c2553933": "wacht in {duration} auf", + "95cc952724dd7310": "wacht gleich auf", + "3cc34921c0128593": "läuft", + "e777db2880f53a46": "niemand hat geantwortet", + "dc90739d391a5e67": "Du hast {choice} gesagt", + "389f2563b5b763fd": "Kurze Schritte", + "a41c8d758121ad81": "hat geschlafen", + "9db248b770096984": "hat gewartet", + "c76124517af28686": "läuft seit {duration}", + "89102905bf09b0e8": "Live ansehen", + "bdf338cdff4118f0": "Transkript", + "811e7e992f9ff820": "kann erst weitergehen, wenn ihre Workflow-Version wieder registriert ist", + "4d4cdf035e98dd57": "wartet darauf, dass du sie fortsetzt", + "eb5b21dd224a5941": "versucht es in {duration} von selbst erneut", + "6ab3dfa749fde477": "versucht es gleich von selbst erneut", + "44b6463aa70aa14c": "Grund der Pause", + "cf25e7169ab0eb7a": "Pausiert bei {step}", + "56c48c1f220f2754": "Die Frage konnte nicht beantwortet werden", + "a3c43735e1a81498": "Begründung für {title}", + "bfad234f016cfa3f": "Warum, in einem Satz. Gilt für die Antwort, die du wählst.", + "004c41aff9c97873": "Ausführungen", + "4dc0c244a2419f6c": [ + "Teil von ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "gestartet", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "ihre Version ist nicht mehr registriert", + "f92d9132f7b85d1a": "Schritte werden geladen…", + "6ebc59f64c761a49": "Noch nichts.", + "a759dccd157d7dae": [ + "Du hast", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " gesagt." + ], + "593b425188346781": [ + "Du hast", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " gesagt: ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Ausführung öffnen", + "c8eb9be36d4d51ad": [ + "Thread auf ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Fortsetzen", + "8cebd63fc4c967d5": "Nur der fehlgeschlagene Schritt läuft erneut; zuvor Abgeschlossenes bleibt erhalten.", + "bc1e0a2a0f1e9552": "Braucht dich", + "a812f51e970740f1": [ + "gefragt", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· die Ausführung wartet auf dich" + ], + "02dfe6c63fd0b8a1": "Begründung hinzufügen", + "19abd94828a3bdbc": "Erst den Agenten fragen", + "a18721fa8f328361": "Braucht dich", + "bbf24e7920c1e86b": "Läuft", + "8d6e18d2ad832db6": "Alle", + "f25af5332ffc3734": "Nichts wartet auf dich.", + "c3f0119b8d6231f8": "Es läuft nichts.", + "33028dfc1229eaa6": "Noch keine Ausführungen.", + "5459bf696a187c26": "Workflow-Ausführungen konnten nicht geladen werden", + "d57c35d43b0f163a": "Diesen Lauf gibt es hier nicht", + "b9aae2f7cdb1a379": "Noch keine Workflow-Ausführungen", + "8f15f66e545af7c0": "Welche Ausführungen", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Alle {count} Workflows", + "46d614fa7b4bf1e5": "Workflow-Ausführungen", + "1c635faa2fb45b8b": "Noch nie gelaufen.", + "156ff7b625287a1e": "Übersprungene ausblenden", + "69b985b97ab45e6b": "{count} übersprungene anzeigen", + "2400254d362de84d": "Workflow-Ausführungen werden geladen…", + "145e1f7503ba3b2c": [ + "Diese Umgebung hat keinen Lauf mit diesem Link.", + " ", + { + "t": "button", + "i": 1, + "c": "Zurück zu den Läufen" + } + ], + "783e616cb0476c17": [ + "Ein Workflow verbindet Agenten, Code, Zeitpläne und Fragen an dich zu einer Ausführung, die Neustarts übersteht. Schreib einen unter", + " ", + { + "t": "button", + "i": 1, + "c": "Definitionen" + }, + ", oder bitte einen Agenten darum.", + " ", + { + "t": "a", + "i": 2, + "c": "Anleitung lesen" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Eine Workflow-Datei hat ein Problem." + }, + " ", + "Die letzte funktionierende Version läuft weiter." + ], + "ed8ce6ebc73dc12d": "Datei öffnen", + "5d8d278ff828102d": "Alle Workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · Transkript", + "c512071143a5ba32": "Diesen Thread gibt es nicht mehr.", + "ed169d23683fb6ac": "Thread wird geladen…", + "290e0ab40b87dc17": "Workflows-Breadcrumb", + "683dd9831e54edc0": "Umgebung", + "34ad53646f06ed80": "Workflows sind aus", + "8f6589c9e0ac5d4e": "Keine Umgebung verbunden", + "744127f8dfad7d22": "Verbinde eine Umgebung, um ihre Workflow-Ausführungen zu sehen.", + "036182ec7e2ee4d4": "Neben der Ausführung", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definitionen", + "f0a212aadfe1257b": "Editor wird geladen…", + "20f194e003885e95": [ + "Aktiviere sie für diesen Server in den", + " ", + { + "t": "Link", + "i": 1, + "c": "Einstellungen → Labs" + }, + "." + ], "8367779e149f723b": "Anfrage an die primäre Umgebung während {operation} fehlgeschlagen (HTTP {status}).", "c5cd027743a2b5a6": "Ungültiges Kopplungstoken. Prüfe das Token und versuch es erneut.", "0e4b49c8203aae81": "Zeitüberschreitung beim Warten auf eine authentifizierte Sitzung nach dem Bootstrap.", @@ -12457,6 +12776,8 @@ "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", - "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", - "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben" + "99d51127f573296b": "Weiteres Konto", + "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", + "99963c0142e17f00": "Für das neue {tracker}-Konto.", + "6d8e4ebc889bace9": "Konto hinzufügen" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 252a92f3e7c23..3ee3c357e42b6 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Install {fj} 0.6 or later from {fjUrl} and run {fjLogin}, or install {tea} 0.16 or later from {teaUrl} and run {teaLogin} for each Forgejo or Gitea server.", "d026a85e2e50e675": "Install the GitCafe CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", "22d3c0c48a34b5b3": "Install the TanStack Source CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", + "756c80ad262ef315": "Waiting in the original thread", + "d8df14f9905f38eb": "Sent", + "e7c59185f8ab3987": "Not sent", + "b54ddec9084fa955": "Closed without sending", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confusing", + "0f53bc8f74dfe56a": "Missing capability", + "055560f307e15e30": "Wrong docs", + "78344b60f407928e": "Other", + "f653846a95cd6e8f": "Kind", + "f41ea186c275b56e": "About", + "2f6e4f7cd364da73": "Expected", + "9d11c93d4035de3e": "Happened", + "c87d0595693704f9": "Did instead", + "d7a4ea6ce5af44e0": "{speaker} · {count} characters", + "f5114fb9c40fd929": "You", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Turn {turn} · {what}", + "dfdaa6255a416140": "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + "afac52a5cc2dc801": "Could not send your answer. Try again.", "79d776428f4d0650": "The file could not be loaded. Reconnect and try again.", "3ea34cbb1ca5ba9b": "Preview cancelled.", "7c0af279ecb3da3a": "Streaming file previews are unavailable in this runtime.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} On", "77cc5f738cb7d459": "{label} Off", - "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", "aba3bb73ce212f0c": "Using {names} requires {providerName} {version} or newer, but the claude-code Homebrew cask only has {latestVersion}. Switch to the claude-code@latest cask: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", "d887bea446534de5": "No project in this environment can read {host}/{repository}.", "4e466d60e2f7736b": "Paste the full pull request URL; this thread has no repository to resolve the number against.", "302625058bacbe38": "Paste a full URL; this project's host has no known {changeRequest} URL.", @@ -376,6 +396,31 @@ "476ca970255eaea4": "Link this environment to T3 Connect for a public URL.", "6b80f5b38a8f9950": "Only this computer can call this address. Link T3 Connect for a public URL.", "c5a7b1d3891dd0b8": "Works wherever this environment's address is reachable, for example over Tailscale or your own proxy. Link T3 Connect for a public URL.", + "3669395daf36fd33": "No longer registered on this server", + "fe513cf316e796e3": "Runs as part of other workflows", + "ccf00b97925efab3": "Started by hand", + "421e585eb092b07b": "Starts on {triggers}", + "7bd7c58592671384": "Needs you", + "834ca879c14c167b": "Working", + "582d6df7dfab86fb": "Paused", + "ea6583ce92507ee3": "Sleeping", + "7ea8cb8af281ce93": "Waiting", + "1347868f2523140e": "Done", + "57d76c4614054271": "Stopped", + "5c7344bd51d0b966": "Skipped", + "b2074e9bd23049a6": "Cancelled", + "5bb7401807ee2fb5": "Asks: {question} and {more} more", + "9e4286183d5f9e34": "Asks: {question}", + "474c18d001bd6717": "A step failed", + "d3890f4eb1508781": "Running its own steps", + "3e7ced10c9482af0": "{step} is working", + "237e1bcb1cf1bdec": "Sleeping at {step}", + "3f7b17ac5a20c8d2": "Runs {run}", + "0306f5f324b8aaa5": "{count} runs under way", + "e8fd779b84a202a2": "Waiting", + "b6d55657e1a027b8": "Waiting for {step}", + "e942562a42aede34": "Finished", + "26b2b9727fe11289": "Ended early", "1bb995dcec481554": "Approve this device on {host}. It shows code {verificationCode}.", "8696a33219944832": "Could not create the websocket authorization proof.", "5678f133a8631f7d": "Your cloud sign-in changed. Sign in again to authorize the environment.", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -1720,6 +1768,8 @@ "2e995206e087c3fc": "Try replying after the connection or pending input is resolved.", "604ec3067171a0d7": "Conversation", "d6182a057ea12624": "Parent thread", + "f2d8537c33cc55a5": "Step of the workflow run", + "ba8337dca3232880": "Open run", "30fa4a764d11ae42": "Could not download {name}", "4952f87dc98191a7": "The attachment is unavailable.", "2fd6d178493fb407": "Failed to interrupt the current turn.", @@ -1805,6 +1855,7 @@ "04fd71efaa2c3b92": "Open pull requests", "57e875b79b98ab82": "Open issues", "f1db0a234c777a1d": "Use T3 Code in another app (MCP)", + "6050f22f63e2bcb5": "Open workflows", "a0cc19e60dd99851": "Open usage", "46694969044eee98": "Focus Next Workspace Area", "0a1011328ba42eef": "Focus Previous Workspace Area", @@ -2496,8 +2547,7 @@ "2d1c111e1b4ae0b0": "Delete thread \"{title}\"?", "c568ab8dad798ec5": "This permanently clears conversation history for this thread.", "0fd1c746a0e38003": "Failed to delete thread", - "0ecde875b0dd2f93": "Filter threads by project: {projects}", - "1ef65b647231ff0b": "Filter threads by project", + "1c8fc3c4a42949ab": "Projects: {projects}", "165511761be2855c": "Search projects", "a46a6467883575a4": "Search projects...", "fdc0e086438a3045": "Project settings for {project}", @@ -2559,10 +2609,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "On another machine, so this machine's agent can't read it. Remove it or switch back to send.", "5bbac0e5afeec779": "Current thread", "33c7e68fca089036": "Thread, {title}", - "b4b98a0287c282e2": "On another machine, so this machine's agent can't read it. Remove it or switch back to send.", - "c6196d99000642b4": "Open thread", "34cc63390ad793cc": "Choose a thread", "8f12309ead62e38a": "Search threads or projects...", "2f664754d005d9a7": "No active threads found.", @@ -2572,6 +2621,7 @@ "a3178769f8308cbc": "Thread failed", "89b5e8f3887812da": "Guest request", "62e626804919b294": "Input needed", + "c6196d99000642b4": "Open thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "You:", "a1fbf2422c588292": "Agent:", @@ -2595,8 +2645,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminal process running", "fc2c9a91f498ad6b": "{count, plural, one {{count} terminal process running. Open terminal} other {{count} terminal processes running. Open terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "stack", "6831e9a46cbd8939": "chain", "9aa9e74a3b7eee91": "Add to chat", @@ -3033,8 +3081,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "Voice input has no draft to record into.", "62450481c00d2ef3": "The draft's environment is unavailable for transcript cleanup.", - "c64cb58d9cecbcd2": "Transcript cleanup failed", "0674544195fcdc39": "The original transcript was added.", + "c64cb58d9cecbcd2": "Transcript cleanup failed", "296496693cdac0db": "The t3 command is unavailable.", "efbcef7bc9bbda01": "Failed to load the t3 command state.", "1bf6910332426e62": "Desktop network access is unavailable.", @@ -3277,6 +3325,7 @@ "4d493d0bda4d403d": "Attach the interrupted file again or remove it", "c9cad1d84d5f1a32": "Attach the interrupted files again or remove them", "536a820f2ff726da": "Select at least one model.", + "48d6389202ad6754": "Sending when ready", "fbafbe78b5e37966": "Resume thread", "bcd7eb979dd38dae": "Open composer to compact and send", "95ee62a0d6968b89": "Send message", @@ -3453,6 +3502,9 @@ "e778e4f446fdf873": "Your next message starts a fresh session", "0e2f2da4f2d94785": "The agent won't see earlier messages in this thread.", "e1189d2e582b008d": "Keep the current session", + "2bb448d605877a22": "Edit or press Esc to cancel", + "1a1f128d70c62304": "{count, plural, one {Sending once image is ready} other {Sending once {count} images are ready}}", + "5af3ab719a9725fb": "Sending message", "461c9f865f2e9b92": "{option} On", "f2aa17b5c620f2a4": "{option} Off", "f59314a884aae1ff": "Default", @@ -3576,6 +3628,14 @@ "c53bc5a4b0314342": "Next media", "2950b1424a3cddf5": "Reconnect to this environment and open the media again.", "ef638bf1479a5461": "The environment returned an invalid media URL.", + "3ccfbf7e86868c35": "Feedback for the T3 team", + "4e0710d19dfc2e7e": "Send this report to the T3 team?", + "87d0ae0723ba75d1": "This is everything that leaves your machine. Nothing is sent unless you press Send.", + "bf19826f81484328": "Include the conversation", + "260c6b45f52d2f27": "Adds the text of your messages and the agent's replies in the last {textTurns, plural, one {turn} other {{textTurns} turns}}.", + "ddb7e6f8ce99e657": "Only someone who can run agents on this machine can send or decline it.", + "03c1eb603c112f47": "Don't send", + "653405e4ed498d9f": "Send", "262955d6eb632f9b": "Clipboard API is unavailable while copying guest link.", "f1a4f2b04cdbb4ef": "Failed to copy guest link to the clipboard.", "cf3490a604e44d31": "Could not create a guest link.", @@ -3596,7 +3656,6 @@ "abd89e9eefedf11b": "Done", "18d166056c1ab6ff": "Stop sharing", "7a2d510eac9e4587": "Guest link expired", - "653405e4ed498d9f": "Send", "21888e302219891d": "Expanded {title} preview", "419719298a7acaea": "Zoom out", "ed8d5db95359cff4": "Reset zoom", @@ -3692,7 +3751,6 @@ "7c1923203049d602": "Copy code", "637817e4ff79c90e": "Code block actions", "ebf3a2b1e314aa5f": "Run in terminal", - "fe219642547fa0bf": "Run in terminal", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Full path", "f37e7d36b51c5b28": "Copy relative path", @@ -3704,10 +3762,6 @@ "4967584e8d0fb1c2": "Preview media", "67589dd912eacb7c": "Open in integrated browser", "a3c98d4c4b24cecb": "File options for {label}", - "b4fe8a076e9fd2f8": "Display equation", - "085d1407e8c92cce": "Inline equation", - "a2ef393fa7b48ae8": "Scroll display equation", - "e94685ea5642e088": "Scroll inline equation", "3a04583c8500e23d": "Show diagram", "16d64f650840fe06": "Show code", "6d329f7d3a50c7e7": "Copy table", @@ -3985,9 +4039,11 @@ "973e99fa86d7f531": "Queued message {position} of {total}, not sent", "0f6087c4f53c7f17": "Start a turn with this message ({shortcut})", "adab89933af02669": "Skip compaction and send this message ({shortcut})", + "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", "3de4016452e8d2bd": "Send into the current turn ({shortcut})", "259cc9568148e8ad": "Start a turn with this message", "bb7fddb812d5d29e": "Skip compaction and send this message", + "425ab15036aec8a4": "Move this command to the front of the queue", "a5fe1ee609b29a9f": "Send into the current turn", "2b7fd345e4f4fd6e": "Cancel editing queued message", "47f1726bf106d2c8": "Edit queued message", @@ -5600,7 +5656,6 @@ }, ". Check the link's path or locate the file in Files." ], - "b9b6bbd1e1ea189f": "Full file", "d715e9494fdbaaf6": "The font could not be loaded.", "ff17c777a72b4408": "Font previews are limited to 10 MB.", "6bd41ad699e22f10": "The font is unavailable.", @@ -5610,6 +5665,7 @@ "a9abaaa4220eae21": "{error} Save it to open in another app.", "c508c9000d9656f8": "Font preview", "1c416d621d250be8": "The quick brown fox jumps over the lazy dog.", + "d7d08260f16b7828": "The file is still loading. Try again in a moment.", "76ebb03de52c92d6": "The text viewer stopped.", "f48162e8e8c12af7": "Could not load the text viewer. Close the file and try again.", "bc4c5b13d38a5da7": "Preview closed.", @@ -5617,8 +5673,6 @@ "9450d1827ef336a1": "Another copy is in progress.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} line} other {{formatted} lines}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexing…", - "2d1f293ac12463fc": "Loading the rest of the file…", "b75105bef8f564a4": "Showing the first 1,024 columns. Source and Save retain every column.", "2a6e1b1f209c3888": "This file is empty.", "192fc79eb3b5b2cb": "This diagram contains resource URLs, markup, node metadata, or custom configuration. Show Mermaid source to inspect it safely.", @@ -5805,7 +5859,6 @@ "0061fff77e36bd4f": "Could not reach the server.", "04dfdd46e3dd4a2e": "Something went wrong. Try again.", "084bb2d8127a508d": "Sent", - "e7c59185f8ab3987": "Not sent", "77c01a15bd36d17c": "This link has ended or is not valid", "e0e736810f3cbef2": "Ask the owner for a new link. Each link works in one browser.", "c3c53aa46f7330e5": "This link has ended", @@ -8837,6 +8890,12 @@ "d3866ead082d14e5": "Add keybinding", "d4345c90894a3220": "Open keybindings.json", "e56a8d51219efaa0": "No keybindings match your search.", + "90a258fff61fd77e": "Off", + "4060244a7079a0d2": "When I ask", + "e88c9d8769544731": "Automatic", + "f29d1dade4dde8aa": "Agents send no feedback to the T3 team.", + "93c4c53562d30a98": "When you ask, agents show you a short report about T3 Code and send it to the T3 team if you approve.", + "cd9ee803e8727017": "Agents also report T3 Code problems they hit on their own, such as a T3 tool that failed.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Group sidebar threads into project folders. Pinned threads stay on top, and Snoozed and Settled stay below the folders.", "e4e91d155cb6a9b4": "Boring sidebar (group by project)", @@ -8845,11 +8904,16 @@ "9ae293971d93c819": "Share a thread with a guest who watches it live in a browser and sends messages you approve. Sign in to T3 Connect to use guest links.", "0aa5406ac4d7f7c7": "Guest links", "f0e853acd2006d53": "Linked environments", + "ef10c2dff987f3ea": "Run multi-step workflows from files in the workflows folder of this server's T3 home. Open them from the command palette. While off, nothing in that folder runs; runs wait until it is on again.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Show a predicted next message in the empty composer after a Claude or Codex turn. Tab uses it. Each is an extra cached request on your plan. Needs Codex 0.165+. Claude threads update on restart.", "d4b2a2ec812aafb0": "Suggest next prompt", "298c7150a7621c80": "Simlock device hosts", "67937aa49179285e": "On a Mac, clone new worktrees from a checkout cached in the T3 home folder instead of writing every file. Uses Git’s normal checkout when it can’t. Turning it off deletes the cache.", "f9904f78d3003f58": "Fast worktree checkout", + "9c2f647882522302": "The selected machines use different agent feedback modes.", + "31bbf7bf8c0a5279": "Agent feedback", + "d52b3d6bf9f2a013": "Mixed", "ec7623deed751c05": [ "Share a thread with a guest who watches it live in a browser and sends messages you approve. Needs T3 Connect: sign in and link this machine in", " ", @@ -8933,7 +8997,9 @@ "fb71127e5746a6bc": "From Sharing & access there, or t3 pair", "1e3fee7084791773": "Also link {target} back to {source}", "ea34a190b0bd804c": "Agents on {target} can then work on {source} too.", - "ad5ed0ce61b966eb": "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "974f8c65e8b5f492": "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", + "6cf9e3083b15614f": "{label} did not answer", + "34ccbdf619b83be3": "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", "81c9796bf61b306a": "Could not forget the link", "130e51beb6cf5aad": "Link an environment", "122c3e355699e69d": "Agents here can then launch, message and wait on threads there. It appears under Authorized clients in that environment's Sharing & access, where it can be revoked.", @@ -9162,7 +9228,6 @@ "0b4779a1825c85bc": "The shared name for this project group in the sidebar and thread lists.", "f68cbda4df83d739": "Reset project name to default", "56e37b85027e8431": "Project icon", - "e88c9d8769544731": "Automatic", "c99736317da5b1fa": "Reset project icon to default", "6afaa3e3739dc570": "Choose a project icon", "51651ce45d481a20": "Choose a project icon file", @@ -10137,7 +10202,6 @@ "a0eb0e4f76608833": "Open linked pull requests first. Otherwise, open Changes for edits to at least 3 files or 50 lines.", "16bdc70b858c223f": "Reset proactive panels to default", "3e99c5c14f4939c8": "Reset compact idle threads to default", - "d52b3d6bf9f2a013": "Mixed", "cd72fe451ba0d6aa": "New projects", "394c3bd0a1782c8e": "Leave empty to use \"~/\" when the Add Project browser opens.", "f9b912a818bd869d": "Reset add project base directory to default", @@ -11039,7 +11103,6 @@ "4a237f41ce592b7f": "Keep this project's worktrees until you delete them manually.", "00b8ffd8ea6e6a93": "Use these rules for this project.", "72c279824d15a999": "Use each machine's worktree cleanup settings.", - "90a258fff61fd77e": "Off", "b5702d0b64866b08": "Custom", "c009c901f3eefe78": "Delete worktrees with deleted threads", "431c7cd6d50102b7": "Remove unused worktrees when active or archived threads are deleted. Worktrees with local changes are kept.", @@ -11735,7 +11798,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "About", "af4b7734da1d5ce7": "Voice", "4ec62c39ca3192bf": "Source control & issues", "f2bf529f85e05494": "Sharing & access", @@ -11790,6 +11852,7 @@ "d443390c4d2dcfd4": "accessibility a11y screen reader nvda jaws voiceover orca narrator window title tab title alt tab taskbar thread status order working approval", "6826fa9579c22035": "beta share guest invite link teammate watch t3 connect tunnel", "f10c06cba0cdf7fe": "beta link another machine vps peer agents work there delegate", + "bc0b409d89ce086e": "beta workflow durable runs automation steps schedule webhook folder", "4a21cf825a2045b0": "beta tab autocomplete predict next message claude codex ghost text", "fea2dc36585c4a20": "Simlock device hosts (alpha)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lease gateway", @@ -11861,6 +11924,7 @@ "901a823214edc8c4": "telemetry analytics usage data tracking legal opt out", "82136480255a5106": "OTel OTLP telemetry export endpoints logs traces metrics Grafana", "659d081051faf7ff": "logs traces processes resource history failures spans cpu memory", + "5eaeacfa9f82051a": "report bug problem t3 team send feedback agents tools automatic when i ask", "f537f91e1ee41d47": "keyboard shortcuts hotkeys commands bindings json", "1ba01e7ceed64b95": "window capture screenshot", "279b1cceb779ff38": "Include app text", @@ -12330,7 +12394,6 @@ "0bd41ff995d36a66": "Cache read", "3f0dfe0cb15a3272": "Cache write", "1c9d860be42b1c02": "Output", - "78344b60f407928e": "Other", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Fast", "66796576034c18ea": "Ultrafast", @@ -12346,6 +12409,262 @@ "2cddd6095abc734a": "7 days", "53493056306708cf": "30 days", "c719359d18d37ad3": "90 days", + "0bd950151ddc6407": "Leave without saving? Your changes to this file are lost.", + "c0ba3f6756b09f30": "Unsaved changes", + "6914e22d357f0ad6": "Saved and running", + "aff389354a031d6f": "The file on disk does not load. The last version that did keeps running.", + "858effde748ab563": "Saved, but it does not run yet.", + "ddb37138df660942": "Not saved. Nothing changed on the server.", + "6ef4db489e40e39e": "Could not save", + "c89624a2e9af1793": "{name} is not connected", + "b5a352a43adb4c17": "Its workflows show again when it reconnects. Pick another environment to see its runs.", + "3dcedb736d20aae5": "Could not read the workflow files", + "b09f4df8d76ae8ea": "Delete {file}? The workflows it defines can no longer be started.", + "b4535f5a03689d27": "{name} is not connected. What you write here stays, and saves once it is back.", + "b54c78d85fd942ea": "Deleted, but what runs has not caught up yet.", + "407c228d7da0b7df": "Not deleted. Nothing changed on the server.", + "1a6aa10f3cc14fff": "These files do not fit together. What ran before keeps running.", + "259312516a1dbe6f": "File name", + "2f48ab2aa0586853": "Defines no workflows", + "ba5adfa37b55b8c5": [ + "Line ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Delete", + "84c900d1ae72adc6": "Save", + "5912d817be03247a": "The file changed on disk while you were editing. Saving replaces that change.", + "0b1e6f5608826387": "Load the file and drop my changes", + "f47b4c06aeb77c1c": "Loading the workflow files…", + "4353bfd401d58f87": [ + "Every file in", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "defines workflows. A change to one is picked up without a restart." + ], + "0c165251a06f10f1": "New file", + "8e97cf734b4463e7": "Create", + "2ec0d5108fd6cebe": "No workflows yet. Make the first file here, or ask an agent to write one in that folder.", + "5601350626e8cfe9": "Does not load", + "21d778a1b9a0c234": "Open beside the run", + "62dc4d3a19ff7ca0": "Close tab", + "1e25265f2758fce3": "Open as a full thread", + "672a3dae06b39402": "Open on its own page", + "7755500a4cde5066": "Close the pane", + "b8dcbc93a2ca1861": "This run no longer lists it.", + "115c69de3202f664": "Open", + "644eafa9048b62df": "{count, plural, =1 {1st try} =2 {2nd try} =3 {3rd try} other {{count}th try}}", + "e39f89c909df4db0": "Could not resume the run", + "865f034346b82f47": "Cancel {title}? Its agents stop and the run cannot be resumed.", + "6bc75632fd9c9136": "Could not cancel the run", + "64e50329dcfdd5b0": "Finished", + "350162e7cc1ebea4": "Stopped", + "0875cf506f4c6810": "Skipped", + "3cc43f1dbf3f8e0c": "Cancelled", + "ded70e75de6404ba": "Back to the list of runs", + "2f4ed7dbd22be30d": "Cancel run", + "614e5ad58a795fb5": "Stop", + "04b050b0329f0ac8": "took {duration}", + "aff78e1774818ff4": "{duration} so far", + "38eddd466439afc9": "What the run touched", + "156ec271d49ddd70": "What happened", + "34f59bbbead0b97f": "{names} and {count} more", + "ac1556f6ce89a5ea": "{count} in parallel", + "e197c4963bacc746": "{count} running", + "f5319ed9e18c0df1": "Asks you", + "882a25e9084ae1b2": "Paused", + "9a03d8a9afc60387": "Steps so far", + "2f2ae791afe01674": "waits for your approval", + "24f8060c4ccdf928": "starting", + "30a5be40eb956663": "working", + "dd7a1e58c2553933": "wakes in {duration}", + "95cc952724dd7310": "about to wake", + "3cc34921c0128593": "running", + "e777db2880f53a46": "nobody answered", + "dc90739d391a5e67": "You said {choice}", + "389f2563b5b763fd": "Quick steps", + "a41c8d758121ad81": "slept", + "9db248b770096984": "waited", + "c76124517af28686": "running for {duration}", + "89102905bf09b0e8": "Watch live", + "bdf338cdff4118f0": "Transcript", + "811e7e992f9ff820": "cannot go on until its workflow version is registered again", + "4d4cdf035e98dd57": "waits for you to resume it", + "eb5b21dd224a5941": "tries again by itself in {duration}", + "6ab3dfa749fde477": "about to try again by itself", + "44b6463aa70aa14c": "Why it paused", + "cf25e7169ab0eb7a": "Paused at {step}", + "56c48c1f220f2754": "Could not answer the question", + "a3c43735e1a81498": "Reason for {title}", + "bfad234f016cfa3f": "Why, in a sentence. It goes with whichever answer you pick.", + "004c41aff9c97873": "Runs", + "4dc0c244a2419f6c": [ + "Part of ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "started", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "its version is no longer registered", + "f92d9132f7b85d1a": "Loading steps…", + "6ebc59f64c761a49": "Nothing yet.", + "a759dccd157d7dae": [ + "You said", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "You said", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Open run", + "c8eb9be36d4d51ad": [ + "Thread on ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Resume", + "8cebd63fc4c967d5": "Only the failed step runs again; what finished before it is kept.", + "bc1e0a2a0f1e9552": "Needs you", + "a812f51e970740f1": [ + "asked", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· the run waits for you" + ], + "02dfe6c63fd0b8a1": "Add a reason", + "19abd94828a3bdbc": "Ask the agent first", + "a18721fa8f328361": "Needs you", + "bbf24e7920c1e86b": "Running", + "8d6e18d2ad832db6": "All", + "f25af5332ffc3734": "Nothing waits on you.", + "c3f0119b8d6231f8": "Nothing is running.", + "33028dfc1229eaa6": "No runs yet.", + "5459bf696a187c26": "Could not load workflow runs", + "d57c35d43b0f163a": "This run is not here", + "b9aae2f7cdb1a379": "No workflow runs yet", + "8f15f66e545af7c0": "Which runs", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "All {count} workflows", + "46d614fa7b4bf1e5": "Workflow runs", + "1c635faa2fb45b8b": "Has not run yet.", + "156ff7b625287a1e": "Hide skipped", + "69b985b97ab45e6b": "Show {count} skipped", + "2400254d362de84d": "Loading workflow runs…", + "145e1f7503ba3b2c": [ + "This environment has no run with that link.", + " ", + { + "t": "button", + "i": 1, + "c": "Back to the runs" + } + ], + "783e616cb0476c17": [ + "A workflow ties agents, code, schedules and questions to you into one run that survives restarts. Write one under", + " ", + { + "t": "button", + "i": 1, + "c": "Definitions" + }, + ", or ask an agent to.", + " ", + { + "t": "a", + "i": 2, + "c": "Read the guide" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "A workflow file has a problem." + }, + " ", + "The last version that did keeps running." + ], + "ed8ce6ebc73dc12d": "Open the file", + "5d8d278ff828102d": "All workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transcript", + "c512071143a5ba32": "This thread is no longer there.", + "ed169d23683fb6ac": "Loading the thread…", + "290e0ab40b87dc17": "Workflows breadcrumb", + "683dd9831e54edc0": "Environment", + "34ad53646f06ed80": "Workflows are off", + "8f6589c9e0ac5d4e": "No environment connected", + "744127f8dfad7d22": "Connect an environment to see its workflow runs.", + "036182ec7e2ee4d4": "Beside the run", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definitions", + "f0a212aadfe1257b": "Loading the editor…", + "20f194e003885e95": [ + "Turn them on for this server in", + " ", + { + "t": "Link", + "i": 1, + "c": "Settings → Labs" + }, + "." + ], "8367779e149f723b": "Primary environment request failed during {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Invalid pairing token. Check the token and try again.", "0e4b49c8203aae81": "Timed out waiting for authenticated session after bootstrap.", @@ -12466,6 +12785,8 @@ "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", "9e91e9a77b664e4e": "Could not start a review guide", - "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", - "425ab15036aec8a4": "Move this command to the front of the queue" + "99d51127f573296b": "Another account", + "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", + "99963c0142e17f00": "For the new {tracker} account.", + "6d8e4ebc889bace9": "Add account" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 14d4f8436c195..83fdd0553e4ea 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Instala {fj} 0.6 o posterior desde {fjUrl} y ejecuta {fjLogin}, o instala {tea} 0.16 o posterior desde {teaUrl} y ejecuta {teaLogin} para cada servidor de Forgejo o Gitea.", "d026a85e2e50e675": "Instala la CLI de GitCafe con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", "22d3c0c48a34b5b3": "Instala la CLI de TanStack Source con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", + "756c80ad262ef315": "En espera en el hilo original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "No enviado", + "b54ddec9084fa955": "Cerrado sin enviar", + "fbaa7ab5da716e50": "Error", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Función ausente", + "055560f307e15e30": "Documentación incorrecta", + "78344b60f407928e": "Otros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Acerca de", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "Lo que ocurrió", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Tú", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumen de {turns, plural, one {{turns} turno reciente} other {{turns} turnos recientes}}, {textTurns, plural, =0 {sin texto de mensajes} one {con el texto de los mensajes del último turno} other {con el texto de los mensajes de los últimos {textTurns} turnos}}{truncated, select, yes {, acortado para ajustarse} other {}}", + "afac52a5cc2dc801": "No se pudo enviar tu respuesta. Inténtalo de nuevo.", "79d776428f4d0650": "No se pudo cargar el archivo. Vuelve a conectarte e inténtalo de nuevo.", "3ea34cbb1ca5ba9b": "Vista previa cancelada.", "7c0af279ecb3da3a": "Las vistas previas de archivos en streaming no están disponibles en este entorno de ejecución.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activado", "77cc5f738cb7d459": "{label} desactivado", - "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", "aba3bb73ce212f0c": "Usar {names} requiere {providerName} {version} o posterior, pero el cask de Homebrew claude-code solo tiene {latestVersion}. Cambia al cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", "d887bea446534de5": "Ningún proyecto de este entorno puede leer {host}/{repository}.", "4e466d60e2f7736b": "Pega la URL completa de la pull request; este hilo no tiene ningún repositorio con el que resolver el número.", "302625058bacbe38": "Pega una URL completa; el host de este proyecto no tiene una URL de {changeRequest} conocida.", @@ -376,6 +396,31 @@ "476ca970255eaea4": "Vincula este entorno a T3 Connect para tener una URL pública.", "6b80f5b38a8f9950": "Solo este equipo puede llamar a esta dirección. Vincula T3 Connect para tener una URL pública.", "c5a7b1d3891dd0b8": "Funciona donde se pueda acceder a la dirección de este entorno, por ejemplo a través de Tailscale o de tu propio proxy. Vincula T3 Connect para tener una URL pública.", + "3669395daf36fd33": "Ya no está registrado en este servidor", + "fe513cf316e796e3": "Se ejecuta como parte de otros flujos de trabajo", + "ccf00b97925efab3": "Se inicia a mano", + "421e585eb092b07b": "Se inicia con {triggers}", + "7bd7c58592671384": "Te necesitan", + "834ca879c14c167b": "Trabajando", + "582d6df7dfab86fb": "En pausa", + "ea6583ce92507ee3": "Durmiendo", + "7ea8cb8af281ce93": "Esperando", + "1347868f2523140e": "Terminada", + "57d76c4614054271": "Detenida", + "5c7344bd51d0b966": "Omitida", + "b2074e9bd23049a6": "Cancelada", + "5bb7401807ee2fb5": "Pregunta: {question} y {more} más", + "9e4286183d5f9e34": "Pregunta: {question}", + "474c18d001bd6717": "Falló un paso", + "d3890f4eb1508781": "Ejecuta sus propios pasos", + "3e7ced10c9482af0": "{step} está trabajando", + "237e1bcb1cf1bdec": "Durmiendo en {step}", + "3f7b17ac5a20c8d2": "Ejecuta {run}", + "0306f5f324b8aaa5": "{count} ejecuciones en curso", + "e8fd779b84a202a2": "Esperando", + "b6d55657e1a027b8": "Esperando a {step}", + "e942562a42aede34": "Finalizada", + "26b2b9727fe11289": "Terminó antes de tiempo", "1bb995dcec481554": "Aprueba este dispositivo en {host}. Muestra el código {verificationCode}.", "8696a33219944832": "No se pudo crear la prueba de autorización del websocket.", "5678f133a8631f7d": "Tu inicio de sesión en la nube cambió. Vuelve a iniciar sesión para autorizar el entorno.", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexión WebSocket.", "d9ce6c142a485959": "{host} dejó de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectó.", + "8450a95e5214d199": "{host} envió una actualización de la configuración del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -1720,6 +1768,8 @@ "2e995206e087c3fc": "Prueba a responder cuando se resuelva la conexión o la entrada pendiente.", "604ec3067171a0d7": "Conversación", "d6182a057ea12624": "Hilo principal", + "f2d8537c33cc55a5": "Paso de la ejecución del flujo de trabajo", + "ba8337dca3232880": "Abrir ejecución", "30fa4a764d11ae42": "No se pudo descargar {name}", "4952f87dc98191a7": "El adjunto no está disponible.", "2fd6d178493fb407": "No se pudo interrumpir el turno actual.", @@ -1805,6 +1855,7 @@ "04fd71efaa2c3b92": "Abrir pull requests", "57e875b79b98ab82": "Abrir issues", "f1db0a234c777a1d": "Usar T3 Code en otra app (MCP)", + "6050f22f63e2bcb5": "Abrir flujos de trabajo", "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Enfocar la siguiente área de trabajo", "0a1011328ba42eef": "Enfocar el área de trabajo anterior", @@ -2496,8 +2547,7 @@ "2d1c111e1b4ae0b0": "¿Eliminar el hilo \"{title}\"?", "c568ab8dad798ec5": "Esto borra de forma permanente el historial de conversación de este hilo.", "0fd1c746a0e38003": "No se pudo eliminar el hilo", - "0ecde875b0dd2f93": "Filtrar hilos por proyecto: {projects}", - "1ef65b647231ff0b": "Filtrar hilos por proyecto", + "1c8fc3c4a42949ab": "Proyectos: {projects}", "165511761be2855c": "Buscar proyectos", "a46a6467883575a4": "Buscar proyectos...", "fdc0e086438a3045": "Ajustes del proyecto {project}", @@ -2559,10 +2609,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Está en otra máquina, así que el agente de esta máquina no puede leerlo. Quítalo o vuelve a cambiar para enviar.", "5bbac0e5afeec779": "Hilo actual", "33c7e68fca089036": "Hilo, {title}", - "b4b98a0287c282e2": "Está en otra máquina, así que el agente de esta máquina no puede leerlo. Quítalo o vuelve a cambiar para enviar.", - "c6196d99000642b4": "Abrir hilo", "34cc63390ad793cc": "Elige un hilo", "8f12309ead62e38a": "Buscar hilos o proyectos...", "2f664754d005d9a7": "No se encontraron hilos activos.", @@ -2572,6 +2621,7 @@ "a3178769f8308cbc": "El hilo falló", "89b5e8f3887812da": "Solicitud de invitado", "62e626804919b294": "Se necesita una respuesta", + "c6196d99000642b4": "Abrir hilo", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Tú:", "a1fbf2422c588292": "Agente:", @@ -2595,8 +2645,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Proceso de terminal en ejecución", "fc2c9a91f498ad6b": "{count, plural, one {{count} proceso de terminal en ejecución. Abrir terminal} other {{count} procesos de terminal en ejecución. Abrir terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "pila", "6831e9a46cbd8939": "cadena", "9aa9e74a3b7eee91": "Añadir al chat", @@ -3033,8 +3081,8 @@ "6f85f14f35b3f547": "{provider} a través de {environment}", "7c59a888a062a8bd": "La entrada de voz no tiene ningún borrador en el que grabar.", "62450481c00d2ef3": "El entorno del borrador no está disponible para limpiar la transcripción.", - "c64cb58d9cecbcd2": "Falló la limpieza de la transcripción", "0674544195fcdc39": "Se añadió la transcripción original.", + "c64cb58d9cecbcd2": "Falló la limpieza de la transcripción", "296496693cdac0db": "El comando t3 no está disponible.", "efbcef7bc9bbda01": "No se pudo cargar el estado del comando t3.", "1bf6910332426e62": "El acceso a la red del escritorio no está disponible.", @@ -3277,6 +3325,7 @@ "4d493d0bda4d403d": "Vuelve a adjuntar el archivo interrumpido o quítalo", "c9cad1d84d5f1a32": "Vuelve a adjuntar los archivos interrumpidos o quítalos", "536a820f2ff726da": "Selecciona al menos un modelo.", + "48d6389202ad6754": "Se enviará cuando esté listo", "fbafbe78b5e37966": "Reanudar hilo", "bcd7eb979dd38dae": "Abrir el cuadro de mensaje para compactar y enviar", "95ee62a0d6968b89": "Enviar mensaje", @@ -3453,6 +3502,9 @@ "e778e4f446fdf873": "Tu próximo mensaje inicia una sesión nueva", "0e2f2da4f2d94785": "El agente no verá los mensajes anteriores de este hilo.", "e1189d2e582b008d": "Mantener la sesión actual", + "2bb448d605877a22": "Edita o pulsa Esc para cancelar", + "1a1f128d70c62304": "{count, plural, one {Se enviará cuando la imagen esté lista} other {Se enviará cuando {count} imágenes estén listas}}", + "5af3ab719a9725fb": "Enviando mensaje", "461c9f865f2e9b92": "{option} activado", "f2aa17b5c620f2a4": "{option} desactivado", "f59314a884aae1ff": "Predeterminado", @@ -3576,6 +3628,14 @@ "c53bc5a4b0314342": "Elemento siguiente", "2950b1424a3cddf5": "Vuelve a conectarte a este entorno y abre de nuevo el contenido.", "ef638bf1479a5461": "El entorno devolvió una URL de contenido no válida.", + "3ccfbf7e86868c35": "Comentarios para el equipo de T3", + "4e0710d19dfc2e7e": "¿Enviar este informe al equipo de T3?", + "87d0ae0723ba75d1": "Esto es todo lo que sale de tu máquina. No se envía nada hasta que pulses Enviar.", + "bf19826f81484328": "Incluir la conversación", + "260c6b45f52d2f27": "Añade el texto de tus mensajes y de las respuestas del agente en {textTurns, plural, one {el último turno} other {los últimos {textTurns} turnos}}.", + "ddb7e6f8ce99e657": "Solo quien pueda ejecutar agentes en esta máquina puede enviarlo o rechazarlo.", + "03c1eb603c112f47": "No enviar", + "653405e4ed498d9f": "Enviar", "262955d6eb632f9b": "La API del portapapeles no está disponible al copiar el enlace de invitado.", "f1a4f2b04cdbb4ef": "No se pudo copiar el enlace de invitado al portapapeles.", "cf3490a604e44d31": "No se pudo crear un enlace de invitado.", @@ -3596,7 +3656,6 @@ "abd89e9eefedf11b": "Listo", "18d166056c1ab6ff": "Dejar de compartir", "7a2d510eac9e4587": "El enlace de invitado caducó", - "653405e4ed498d9f": "Enviar", "21888e302219891d": "Vista previa ampliada de {title}", "419719298a7acaea": "Alejar", "ed8d5db95359cff4": "Restablecer zoom", @@ -3692,7 +3751,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Acciones del bloque de código", "ebf3a2b1e314aa5f": "Ejecutar en la terminal", - "fe219642547fa0bf": "Ejecutar en la terminal", "122a8512abc51180": "Detalles", "58c38c65c2783c5d": "Ruta completa", "f37e7d36b51c5b28": "Copiar ruta relativa", @@ -3704,10 +3762,6 @@ "4967584e8d0fb1c2": "Vista previa del contenido", "67589dd912eacb7c": "Abrir en el navegador integrado", "a3c98d4c4b24cecb": "Opciones de archivo de {label}", - "b4fe8a076e9fd2f8": "Ecuación en bloque", - "085d1407e8c92cce": "Ecuación en línea", - "a2ef393fa7b48ae8": "Desplazar la ecuación en bloque", - "e94685ea5642e088": "Desplazar la ecuación en línea", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabla", @@ -3983,9 +4037,11 @@ "973e99fa86d7f531": "Mensaje en cola {position} de {total}, sin enviar", "0f6087c4f53c7f17": "Iniciar un turno con este mensaje ({shortcut})", "adab89933af02669": "Omitir la compactación y enviar este mensaje ({shortcut})", + "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", "3de4016452e8d2bd": "Enviar al turno actual ({shortcut})", "259cc9568148e8ad": "Iniciar un turno con este mensaje", "bb7fddb812d5d29e": "Omitir la compactación y enviar este mensaje", + "425ab15036aec8a4": "Mover este comando al principio de la cola", "a5fe1ee609b29a9f": "Enviar al turno actual", "2b7fd345e4f4fd6e": "Cancelar la edición del mensaje en cola", "47f1726bf106d2c8": "Editar mensaje en cola", @@ -5598,7 +5654,6 @@ }, ". Revisa la ruta del enlace o busca el archivo en Archivos." ], - "b9b6bbd1e1ea189f": "Archivo completo", "d715e9494fdbaaf6": "No se pudo cargar la fuente.", "ff17c777a72b4408": "Las vistas previas de fuentes están limitadas a 10 MB.", "6bd41ad699e22f10": "La fuente no está disponible.", @@ -5608,6 +5663,7 @@ "a9abaaa4220eae21": "{error} Guárdala para abrirla en otra app.", "c508c9000d9656f8": "Vista previa de la fuente", "1c416d621d250be8": "El veloz murciélago hindú comía feliz cardillo y kiwi.", + "d7d08260f16b7828": "El archivo aún se está cargando. Inténtalo de nuevo en un momento.", "76ebb03de52c92d6": "El visor de texto se detuvo.", "f48162e8e8c12af7": "No se pudo cargar el visor de texto. Cierra el archivo y vuelve a intentarlo.", "bc4c5b13d38a5da7": "Vista previa cerrada.", @@ -5615,8 +5671,6 @@ "9450d1827ef336a1": "Ya hay otra copia en curso.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} línea} other {{formatted} líneas}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexando…", - "2d1f293ac12463fc": "Cargando el resto del archivo…", "b75105bef8f564a4": "Se muestran las primeras 1024 columnas. El código fuente y Guardar conservan todas las columnas.", "2a6e1b1f209c3888": "Este archivo está vacío.", "192fc79eb3b5b2cb": "Este diagrama contiene URL de recursos, marcado, metadatos de nodos o configuración personalizada. Muestra el código fuente de Mermaid para inspeccionarlo de forma segura.", @@ -5803,7 +5857,6 @@ "0061fff77e36bd4f": "No se pudo acceder al servidor.", "04dfdd46e3dd4a2e": "Algo salió mal. Vuelve a intentarlo.", "084bb2d8127a508d": "Enviado", - "e7c59185f8ab3987": "No enviado", "77c01a15bd36d17c": "Este enlace terminó o no es válido", "e0e736810f3cbef2": "Pide un enlace nuevo al propietario. Cada enlace funciona en un navegador.", "c3c53aa46f7330e5": "Este enlace terminó", @@ -8827,6 +8880,12 @@ "d3866ead082d14e5": "Añadir atajo de teclado", "d4345c90894a3220": "Abrir keybindings.json", "e56a8d51219efaa0": "Ningún atajo de teclado coincide con tu búsqueda.", + "90a258fff61fd77e": "Desactivado", + "4060244a7079a0d2": "Cuando lo pida", + "e88c9d8769544731": "Automático", + "f29d1dade4dde8aa": "Los agentes no envían comentarios al equipo de T3.", + "93c4c53562d30a98": "Cuando lo pides, los agentes te muestran un breve informe sobre T3 Code y lo envían al equipo de T3 si lo apruebas.", + "cd9ee803e8727017": "Los agentes también informan por su cuenta de los problemas que encuentran en T3 Code, como una herramienta de T3 que falla.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Agrupa los hilos de la barra lateral en carpetas de proyecto. Los hilos fijados quedan arriba, y Pospuestos y Resueltos quedan debajo de las carpetas.", "e4e91d155cb6a9b4": "Barra lateral simple (agrupar por proyecto)", @@ -8835,11 +8894,16 @@ "9ae293971d93c819": "Comparte un hilo con un invitado que lo ve en directo en un navegador y envía mensajes que tú apruebas. Inicia sesión en T3 Connect para usar enlaces de invitado.", "0aa5406ac4d7f7c7": "Enlaces de invitado", "f0e853acd2006d53": "Entornos vinculados", + "ef10c2dff987f3ea": "Ejecuta flujos de trabajo de varios pasos a partir de archivos en la carpeta workflows del directorio T3 de este servidor. Ábrelos desde la paleta de comandos. Mientras está desactivado, no se ejecuta nada de esa carpeta; las ejecuciones esperan hasta que se vuelva a activar.", + "2dadb2359422121c": "Flujos de trabajo", "13e86eb5d8287a71": "Muestra un mensaje siguiente previsto en el cuadro de mensaje vacío tras un turno de Claude o Codex. Tab lo usa. Cada uno es una solicitud extra en caché de tu plan. Requiere Codex 0.165+. Los hilos de Claude se actualizan al reiniciar.", "d4b2a2ec812aafb0": "Sugerir el siguiente prompt", "298c7150a7621c80": "Hosts de dispositivos Simlock", "67937aa49179285e": "En un Mac, clona los nuevos worktrees desde un checkout en caché en la carpeta de inicio de T3 en lugar de escribir cada archivo. Usa el checkout normal de Git cuando no puede. Al desactivarlo se elimina la caché.", "f9904f78d3003f58": "Checkout rápido de worktrees", + "9c2f647882522302": "Las máquinas seleccionadas usan distintos modos de comentarios de agentes.", + "31bbf7bf8c0a5279": "Comentarios de agentes", + "d52b3d6bf9f2a013": "Mixto", "ec7623deed751c05": [ "Comparte un hilo con un invitado que lo ve en directo en un navegador y envía mensajes que tú apruebas. Requiere T3 Connect: inicia sesión y vincula esta máquina en", " ", @@ -8923,7 +8987,9 @@ "fb71127e5746a6bc": "Desde Compartir y acceso allí, o t3 pair", "1e3fee7084791773": "Vincular también {target} de vuelta a {source}", "ea34a190b0bd804c": "Los agentes de {target} podrán trabajar también en {source}.", - "ad5ed0ce61b966eb": "¿Olvidar {label}? Los agentes de aquí dejarán de trabajar allí. Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", + "974f8c65e8b5f492": "¿Olvidar {label}? Los agentes de aquí dejan de trabajar allí, y su sesión en {label} también termina si responde.", + "6cf9e3083b15614f": "{label} no respondió", + "34ccbdf619b83be3": "Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", "81c9796bf61b306a": "No se pudo olvidar el vínculo", "130e51beb6cf5aad": "Vincular un entorno", "122c3e355699e69d": "Así los agentes de aquí podrán iniciar hilos allí, enviarles mensajes y esperarlos. Aparece en Clientes autorizados, en Compartir y acceso de ese entorno, donde se puede revocar.", @@ -9152,7 +9218,6 @@ "0b4779a1825c85bc": "El nombre compartido de este grupo de proyectos en la barra lateral y en las listas de hilos.", "f68cbda4df83d739": "Restablecer el nombre del proyecto al valor predeterminado", "56e37b85027e8431": "Icono del proyecto", - "e88c9d8769544731": "Automático", "c99736317da5b1fa": "Restablecer el icono del proyecto al valor predeterminado", "6afaa3e3739dc570": "Elige un icono para el proyecto", "51651ce45d481a20": "Elige un archivo de icono para el proyecto", @@ -10125,7 +10190,6 @@ "a0eb0e4f76608833": "Abre primero las pull requests vinculadas. Si no hay, abre Cambios cuando se editan al menos 3 archivos o 50 líneas.", "16bdc70b858c223f": "Restablecer los paneles proactivos al valor predeterminado", "3e99c5c14f4939c8": "Restablecer la compactación de hilos inactivos al valor predeterminado", - "d52b3d6bf9f2a013": "Mixto", "cd72fe451ba0d6aa": "Proyectos nuevos", "394c3bd0a1782c8e": "Déjalo vacío para usar \"~/\" cuando se abra el explorador de Añadir proyecto.", "f9b912a818bd869d": "Restablecer el directorio base para añadir proyectos al valor predeterminado", @@ -11024,7 +11088,6 @@ "4a237f41ce592b7f": "Conserva los worktrees de este proyecto hasta que los elimines manualmente.", "00b8ffd8ea6e6a93": "Usa estas reglas para este proyecto.", "72c279824d15a999": "Usa los ajustes de limpieza de worktrees de cada máquina.", - "90a258fff61fd77e": "Desactivado", "b5702d0b64866b08": "Personalizado", "c009c901f3eefe78": "Eliminar los worktrees de hilos eliminados", "431c7cd6d50102b7": "Quita los worktrees sin uso cuando se eliminan hilos activos o archivados. Se conservan los worktrees con cambios locales.", @@ -11720,7 +11783,6 @@ "4c70e3e7b3e6c493": "Secretos", "79b768229c9ef672": "Mantenimiento", "54b188d65247e42f": "Experimentos", - "f41ea186c275b56e": "Acerca de", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versiones e issues", "f2bf529f85e05494": "Compartir y acceso", @@ -11775,6 +11837,7 @@ "d443390c4d2dcfd4": "accesibilidad a11y lector de pantalla nvda jaws voiceover orca narrador título de ventana título de pestaña alt tab barra de tareas estado del hilo orden en curso aprobación", "6826fa9579c22035": "beta compartir invitado invitar enlace compañero ver t3 connect túnel", "f10c06cba0cdf7fe": "beta vincular otra máquina vps agentes pares trabajar allí delegar", + "bc0b409d89ce086e": "beta flujo de trabajo workflow ejecuciones duraderas automatización pasos programación webhook carpeta", "4a21cf825a2045b0": "beta tab autocompletar predecir siguiente mensaje claude codex texto fantasma", "fea2dc36585c4a20": "Hosts de dispositivos Simlock (alfa)", "9d834d178130180e": "beta alfa simlock callstack simulador emulador ios android grupo préstamo gateway", @@ -11846,6 +11909,7 @@ "901a823214edc8c4": "telemetría analítica datos de uso seguimiento legal desactivar", "82136480255a5106": "OTel OTLP telemetría exportar endpoints registros trazas métricas Grafana", "659d081051faf7ff": "registros trazas procesos historial de recursos fallos spans cpu memoria", + "5eaeacfa9f82051a": "informe error problema t3 equipo enviar comentarios agentes herramientas automático cuando lo pida", "f537f91e1ee41d47": "atajos de teclado teclas rápidas comandos combinaciones json", "1ba01e7ceed64b95": "ventana captura captura de pantalla", "279b1cceb779ff38": "Incluir el texto de la app", @@ -12315,7 +12379,6 @@ "0bd41ff995d36a66": "Lectura de caché", "3f0dfe0cb15a3272": "Escritura de caché", "1c9d860be42b1c02": "Salida", - "78344b60f407928e": "Otros", "684e516076de81fe": "Estándar", "3bbcc1b826fef537": "Rápida", "66796576034c18ea": "Ultrarrápida", @@ -12331,6 +12394,262 @@ "2cddd6095abc734a": "7 días", "53493056306708cf": "30 días", "c719359d18d37ad3": "90 días", + "0bd950151ddc6407": "¿Salir sin guardar? Se perderán tus cambios en este archivo.", + "c0ba3f6756b09f30": "Cambios sin guardar", + "6914e22d357f0ad6": "Guardado y en ejecución", + "aff389354a031d6f": "El archivo en disco no se carga. Sigue en ejecución la última versión que sí cargó.", + "858effde748ab563": "Guardado, pero todavía no se ejecuta.", + "ddb37138df660942": "No se guardó. No cambió nada en el servidor.", + "6ef4db489e40e39e": "No se pudo guardar", + "c89624a2e9af1793": "{name} no está conectado", + "b5a352a43adb4c17": "Sus flujos de trabajo vuelven a mostrarse cuando se reconecta. Elige otro entorno para ver sus ejecuciones.", + "3dcedb736d20aae5": "No se pudieron leer los archivos de flujos de trabajo", + "b09f4df8d76ae8ea": "¿Eliminar {file}? Los flujos de trabajo que define ya no se podrán iniciar.", + "b4535f5a03689d27": "{name} no está conectado. Lo que escribas aquí se conserva y se puede guardar en cuanto vuelva.", + "b54c78d85fd942ea": "Eliminado, pero lo que se ejecuta aún no se ha actualizado.", + "407c228d7da0b7df": "No se eliminó. No cambió nada en el servidor.", + "1a6aa10f3cc14fff": "Estos archivos no encajan entre sí. Lo que se ejecutaba antes sigue en ejecución.", + "259312516a1dbe6f": "Nombre del archivo", + "2f48ab2aa0586853": "No define ningún flujo de trabajo", + "ba5adfa37b55b8c5": [ + "Línea ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Eliminar", + "84c900d1ae72adc6": "Guardar", + "5912d817be03247a": "El archivo cambió en disco mientras lo editabas. Al guardar se reemplaza ese cambio.", + "0b1e6f5608826387": "Cargar el archivo y descartar mis cambios", + "f47b4c06aeb77c1c": "Cargando los archivos de flujos de trabajo…", + "4353bfd401d58f87": [ + "Cada archivo de", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "define flujos de trabajo. Los cambios se aplican sin reiniciar." + ], + "0c165251a06f10f1": "Nuevo archivo", + "8e97cf734b4463e7": "Crear", + "2ec0d5108fd6cebe": "Aún no hay flujos de trabajo. Crea aquí el primer archivo o pide a un agente que escriba uno en esa carpeta.", + "5601350626e8cfe9": "No se carga", + "21d778a1b9a0c234": "Abierto junto a la ejecución", + "62dc4d3a19ff7ca0": "Cerrar pestaña", + "1e25265f2758fce3": "Abrir como hilo completo", + "672a3dae06b39402": "Abrir en su propia página", + "7755500a4cde5066": "Cerrar el panel", + "b8dcbc93a2ca1861": "Esta ejecución ya no lo incluye.", + "115c69de3202f664": "Abrir", + "644eafa9048b62df": "{count, plural, =1 {1.er intento} =2 {2.º intento} =3 {3.er intento} other {{count}.º intento}}", + "e39f89c909df4db0": "No se pudo reanudar la ejecución", + "865f034346b82f47": "¿Cancelar {title}? Sus agentes se detienen y la ejecución no se podrá reanudar.", + "6bc75632fd9c9136": "No se pudo cancelar la ejecución", + "64e50329dcfdd5b0": "Finalizada", + "350162e7cc1ebea4": "Detenida", + "0875cf506f4c6810": "Omitida", + "3cc43f1dbf3f8e0c": "Cancelada", + "ded70e75de6404ba": "Volver a la lista de ejecuciones", + "2f4ed7dbd22be30d": "Cancelar ejecución", + "614e5ad58a795fb5": "Detener", + "04b050b0329f0ac8": "tardó {duration}", + "aff78e1774818ff4": "{duration} hasta ahora", + "38eddd466439afc9": "Lo que tocó la ejecución", + "156ec271d49ddd70": "Qué ocurrió", + "34f59bbbead0b97f": "{names} y {count} más", + "ac1556f6ce89a5ea": "{count} en paralelo", + "e197c4963bacc746": "{count} en curso", + "f5319ed9e18c0df1": "Te pregunta", + "882a25e9084ae1b2": "En pausa", + "9a03d8a9afc60387": "Pasos hasta ahora", + "2f2ae791afe01674": "espera tu aprobación", + "24f8060c4ccdf928": "empezando", + "30a5be40eb956663": "trabajando", + "dd7a1e58c2553933": "despierta en {duration}", + "95cc952724dd7310": "a punto de despertar", + "3cc34921c0128593": "en curso", + "e777db2880f53a46": "nadie respondió", + "dc90739d391a5e67": "Dijiste {choice}", + "389f2563b5b763fd": "Pasos rápidos", + "a41c8d758121ad81": "en espera", + "9db248b770096984": "esperó", + "c76124517af28686": "en ejecución desde hace {duration}", + "89102905bf09b0e8": "Ver en directo", + "bdf338cdff4118f0": "Transcripción", + "811e7e992f9ff820": "no puede continuar hasta que su versión del flujo de trabajo vuelva a registrarse", + "4d4cdf035e98dd57": "espera a que la reanudes", + "eb5b21dd224a5941": "lo reintenta sola en {duration}", + "6ab3dfa749fde477": "a punto de reintentarlo sola", + "44b6463aa70aa14c": "Por qué se pausó", + "cf25e7169ab0eb7a": "En pausa en {step}", + "56c48c1f220f2754": "No se pudo responder a la pregunta", + "a3c43735e1a81498": "Motivo de {title}", + "bfad234f016cfa3f": "El porqué, en una frase. Acompaña a la respuesta que elijas.", + "004c41aff9c97873": "Ejecuciones", + "4dc0c244a2419f6c": [ + "Parte de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "iniciada", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "su versión ya no está registrada", + "f92d9132f7b85d1a": "Cargando pasos…", + "6ebc59f64c761a49": "Nada todavía.", + "a759dccd157d7dae": [ + "Dijiste", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Dijiste", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Abrir ejecución", + "c8eb9be36d4d51ad": [ + "Hilo en ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Reanudar", + "8cebd63fc4c967d5": "Solo se vuelve a ejecutar el paso que falló; lo que terminó antes se conserva.", + "bc1e0a2a0f1e9552": "Te necesitan", + "a812f51e970740f1": [ + "preguntó", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· la ejecución te espera" + ], + "02dfe6c63fd0b8a1": "Añadir un motivo", + "19abd94828a3bdbc": "Preguntar antes al agente", + "a18721fa8f328361": "Te necesitan", + "bbf24e7920c1e86b": "En ejecución", + "8d6e18d2ad832db6": "Todas", + "f25af5332ffc3734": "Nada espera tu respuesta.", + "c3f0119b8d6231f8": "No hay nada en ejecución.", + "33028dfc1229eaa6": "Aún no hay ejecuciones.", + "5459bf696a187c26": "No se pudieron cargar las ejecuciones de flujos de trabajo", + "d57c35d43b0f163a": "Esta ejecución no está aquí", + "b9aae2f7cdb1a379": "Aún no hay ejecuciones de flujos de trabajo", + "8f15f66e545af7c0": "Qué ejecuciones", + "b6409289e0c9a4dd": "Flujo de trabajo", + "035cb02ca1ae4952": "Los {count} flujos de trabajo", + "46d614fa7b4bf1e5": "Ejecuciones de flujos de trabajo", + "1c635faa2fb45b8b": "Aún no se ha ejecutado.", + "156ff7b625287a1e": "Ocultar omitidos", + "69b985b97ab45e6b": "Mostrar {count} omitidos", + "2400254d362de84d": "Cargando ejecuciones de flujos de trabajo…", + "145e1f7503ba3b2c": [ + "Este entorno no tiene ninguna ejecución con ese enlace.", + " ", + { + "t": "button", + "i": 1, + "c": "Volver a las ejecuciones" + } + ], + "783e616cb0476c17": [ + "Un flujo de trabajo une agentes, código, programaciones y preguntas para ti en una sola ejecución que sobrevive a los reinicios. Escribe uno en", + " ", + { + "t": "button", + "i": 1, + "c": "Definiciones" + }, + ", o pídeselo a un agente.", + " ", + { + "t": "a", + "i": 2, + "c": "Leer la guía" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Un archivo de flujo de trabajo tiene un problema." + }, + " ", + "Sigue en ejecución la última versión que sí cargó." + ], + "ed8ce6ebc73dc12d": "Abrir el archivo", + "5d8d278ff828102d": "Todos los flujos de trabajo", + "39459da07479f482": "Agente", + "7741243632056b81": "{step} · transcripción", + "c512071143a5ba32": "Este hilo ya no existe.", + "ed169d23683fb6ac": "Cargando el hilo…", + "290e0ab40b87dc17": "Ruta de navegación de flujos de trabajo", + "683dd9831e54edc0": "Entorno", + "34ad53646f06ed80": "Los flujos de trabajo están desactivados", + "8f6589c9e0ac5d4e": "Ningún entorno conectado", + "744127f8dfad7d22": "Conecta un entorno para ver sus ejecuciones de flujos de trabajo.", + "036182ec7e2ee4d4": "Junto a la ejecución", + "2d6107cb78382d08": "Flujos de trabajo", + "16f7df687349b399": "Definiciones", + "f0a212aadfe1257b": "Cargando el editor…", + "20f194e003885e95": [ + "Actívalos para este servidor en", + " ", + { + "t": "Link", + "i": 1, + "c": "Ajustes → Labs" + }, + "." + ], "8367779e149f723b": "Falló una solicitud al entorno principal durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "El token de emparejamiento no es válido. Revísalo e inténtalo de nuevo.", "0e4b49c8203aae81": "Se agotó el tiempo de espera de la sesión autenticada tras el arranque.", @@ -12452,6 +12771,8 @@ "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", - "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", - "425ab15036aec8a4": "Mover este comando al principio de la cola" + "99d51127f573296b": "Otra cuenta", + "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", + "99963c0142e17f00": "Para la nueva cuenta de {tracker}.", + "6d8e4ebc889bace9": "Añadir cuenta" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e386e8b587b69..462e67d2053d3 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installez {fj} 0.6 ou version ultérieure depuis {fjUrl} et exécutez {fjLogin}, ou installez {tea} 0.16 ou version ultérieure depuis {teaUrl} et exécutez {teaLogin} pour chaque serveur Forgejo ou Gitea.", "d026a85e2e50e675": "Installez la CLI GitCafe avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", "22d3c0c48a34b5b3": "Installez la CLI TanStack Source avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", + "756c80ad262ef315": "En attente dans le fil d'origine", + "d8df14f9905f38eb": "Envoyé", + "e7c59185f8ab3987": "Non envoyé", + "b54ddec9084fa955": "Fermé sans envoi", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Peu clair", + "0f53bc8f74dfe56a": "Fonctionnalité manquante", + "055560f307e15e30": "Documentation incorrecte", + "78344b60f407928e": "Autre", + "f653846a95cd6e8f": "Type", + "f41ea186c275b56e": "À propos", + "2f6e4f7cd364da73": "Résultat attendu", + "9d11c93d4035de3e": "Résultat obtenu", + "c87d0595693704f9": "Solution de repli", + "d7a4ea6ce5af44e0": "{speaker} · {count} caractères", + "f5114fb9c40fd929": "Vous", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Tour {turn} · {what}", + "dfdaa6255a416140": "Résumé de {turns, plural, one {{turns} tour récent} other {{turns} tours récents}}, {textTurns, plural, =0 {sans texte des messages} one {avec le texte des messages du dernier tour} other {avec le texte des messages des {textTurns} derniers tours}}{truncated, select, yes {, raccourci pour tenir dans la limite} other {}}", + "afac52a5cc2dc801": "Impossible d'envoyer votre réponse. Réessayez.", "79d776428f4d0650": "Le fichier n’a pas pu être chargé. Reconnectez-vous et réessayez.", "3ea34cbb1ca5ba9b": "Aperçu annulé.", "7c0af279ecb3da3a": "Les aperçus de fichiers en streaming ne sont pas disponibles dans cet environnement d’exécution.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activé", "77cc5f738cb7d459": "{label} désactivé", - "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", "aba3bb73ce212f0c": "{names} nécessite {providerName} {version} ou une version plus récente, mais le cask Homebrew claude-code ne propose que {latestVersion}. Passe au cask claude-code@latest : {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", "d887bea446534de5": "Aucun projet de cet environnement ne peut lire {host}/{repository}.", "4e466d60e2f7736b": "Collez l’URL complète de la pull request ; ce fil n’a pas de dépôt auquel rattacher le numéro.", "302625058bacbe38": "Collez une URL complète ; l’hôte de ce projet n’a pas de format d’URL connu pour {changeRequest}.", @@ -376,6 +396,31 @@ "476ca970255eaea4": "Associez cet environnement à T3 Connect pour obtenir une URL publique.", "6b80f5b38a8f9950": "Seul cet ordinateur peut appeler cette adresse. Associez T3 Connect pour obtenir une URL publique.", "c5a7b1d3891dd0b8": "Fonctionne partout où l’adresse de cet environnement est joignable, par exemple via Tailscale ou votre propre proxy. Associez T3 Connect pour obtenir une URL publique.", + "3669395daf36fd33": "N’est plus enregistré sur ce serveur", + "fe513cf316e796e3": "S’exécute dans le cadre d’autres workflows", + "ccf00b97925efab3": "Démarré à la main", + "421e585eb092b07b": "Démarre sur {triggers}", + "7bd7c58592671384": "Vous attendent", + "834ca879c14c167b": "En cours", + "582d6df7dfab86fb": "En pause", + "ea6583ce92507ee3": "En veille", + "7ea8cb8af281ce93": "En attente", + "1347868f2523140e": "Terminée", + "57d76c4614054271": "Arrêtée", + "5c7344bd51d0b966": "Ignorée", + "b2074e9bd23049a6": "Annulée", + "5bb7401807ee2fb5": "Demande : {question} et {more} de plus", + "9e4286183d5f9e34": "Demande : {question}", + "474c18d001bd6717": "Une étape a échoué", + "d3890f4eb1508781": "Exécute ses propres étapes", + "3e7ced10c9482af0": "{step} est en cours", + "237e1bcb1cf1bdec": "En veille à {step}", + "3f7b17ac5a20c8d2": "Exécute {run}", + "0306f5f324b8aaa5": "{count} exécutions en cours", + "e8fd779b84a202a2": "En attente", + "b6d55657e1a027b8": "En attente de {step}", + "e942562a42aede34": "Terminée", + "26b2b9727fe11289": "Terminée prématurément", "1bb995dcec481554": "Approuvez cet appareil sur {host}. Il affiche le code {verificationCode}.", "8696a33219944832": "Impossible de créer la preuve d’autorisation WebSocket.", "5678f133a8631f7d": "Votre connexion cloud a changé. Reconnectez-vous pour autoriser l’environnement.", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host} n’a pas pu établir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne répond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est déconnecté.", + "8450a95e5214d199": "{host} a envoyé une mise à jour de la configuration du serveur que ce client n’a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", @@ -1720,6 +1768,8 @@ "2e995206e087c3fc": "Réessayez de répondre une fois la connexion ou la saisie en attente résolue.", "604ec3067171a0d7": "Conversation", "d6182a057ea12624": "Fil parent", + "f2d8537c33cc55a5": "Étape de l’exécution du workflow", + "ba8337dca3232880": "Ouvrir l’exécution", "30fa4a764d11ae42": "Impossible de télécharger {name}", "4952f87dc98191a7": "La pièce jointe est indisponible.", "2fd6d178493fb407": "Échec de l’interruption du tour en cours.", @@ -1805,6 +1855,7 @@ "04fd71efaa2c3b92": "Ouvrir les pull requests", "57e875b79b98ab82": "Ouvrir les tickets", "f1db0a234c777a1d": "Utiliser T3 Code dans une autre app (MCP)", + "6050f22f63e2bcb5": "Ouvrir les workflows", "a0cc19e60dd99851": "Ouvrir l’utilisation", "46694969044eee98": "Activer la zone de travail suivante", "0a1011328ba42eef": "Activer la zone de travail précédente", @@ -2496,8 +2547,7 @@ "2d1c111e1b4ae0b0": "Supprimer le fil « {title} » ?", "c568ab8dad798ec5": "Cela efface définitivement l’historique de conversation de ce fil.", "0fd1c746a0e38003": "Échec de la suppression du fil", - "0ecde875b0dd2f93": "Filtrer les fils par projet : {projects}", - "1ef65b647231ff0b": "Filtrer les fils par projet", + "1c8fc3c4a42949ab": "Projets : {projects}", "165511761be2855c": "Rechercher des projets", "a46a6467883575a4": "Rechercher des projets...", "fdc0e086438a3045": "Paramètres du projet {project}", @@ -2559,10 +2609,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Sur une autre machine, l’agent de cette machine ne peut donc pas le lire. Retirez-le ou revenez en arrière pour envoyer.", "5bbac0e5afeec779": "Fil actuel", "33c7e68fca089036": "Fil, {title}", - "b4b98a0287c282e2": "Sur une autre machine, l’agent de cette machine ne peut donc pas le lire. Retirez-le ou revenez en arrière pour envoyer.", - "c6196d99000642b4": "Ouvrir le fil", "34cc63390ad793cc": "Choisir un fil", "8f12309ead62e38a": "Rechercher des fils ou des projets...", "2f664754d005d9a7": "Aucun fil actif trouvé.", @@ -2572,6 +2621,7 @@ "a3178769f8308cbc": "Échec du fil", "89b5e8f3887812da": "Demande d’invité", "62e626804919b294": "Réponse requise", + "c6196d99000642b4": "Ouvrir le fil", "826cb862b4a11fb3": "{label} :", "3e597ec938e7551b": "Vous :", "a1fbf2422c588292": "Agent :", @@ -2595,8 +2645,6 @@ "3260b22f72f7effb": "{tooltipLead} : {title}", "feac8e54b30c5a03": "Processus du terminal en cours", "fc2c9a91f498ad6b": "{count, plural, one {{count} processus de terminal en cours. Ouvrir le terminal} other {{count} processus de terminal en cours. Ouvrir le terminal}}", - "643c4b50feadc874": "Worktree : {path} ({branch})", - "fb7c44da0f0825ea": "Worktree : {path}", "56f37ff8ca568059": "pile", "6831e9a46cbd8939": "chaîne", "9aa9e74a3b7eee91": "Ajouter à la discussion", @@ -3033,8 +3081,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "La saisie vocale n’a aucun brouillon dans lequel enregistrer.", "62450481c00d2ef3": "L’environnement du brouillon n’est pas disponible pour nettoyer la transcription.", - "c64cb58d9cecbcd2": "Échec du nettoyage de la transcription", "0674544195fcdc39": "La transcription d’origine a été ajoutée.", + "c64cb58d9cecbcd2": "Échec du nettoyage de la transcription", "296496693cdac0db": "La commande t3 n’est pas disponible.", "efbcef7bc9bbda01": "Échec du chargement de l’état de la commande t3.", "1bf6910332426e62": "L’accès réseau de l’app desktop n’est pas disponible.", @@ -3277,6 +3325,7 @@ "4d493d0bda4d403d": "Joignez à nouveau le fichier interrompu ou retirez-le", "c9cad1d84d5f1a32": "Joignez à nouveau les fichiers interrompus ou retirez-les", "536a820f2ff726da": "Sélectionnez au moins un modèle.", + "48d6389202ad6754": "Envoi dès que prêt", "fbafbe78b5e37966": "Reprendre le fil", "bcd7eb979dd38dae": "Ouvrir la zone de saisie pour compacter et envoyer", "95ee62a0d6968b89": "Envoyer le message", @@ -3453,6 +3502,9 @@ "e778e4f446fdf873": "Votre prochain message démarre une nouvelle session", "0e2f2da4f2d94785": "L’agent ne verra pas les messages précédents de ce fil.", "e1189d2e582b008d": "Garder la session actuelle", + "2bb448d605877a22": "Modifiez ou appuyez sur Échap pour annuler", + "1a1f128d70c62304": "{count, plural, one {Envoi dès que l’image est prête} other {Envoi dès que les {count} images sont prêtes}}", + "5af3ab719a9725fb": "Envoi du message", "461c9f865f2e9b92": "{option} activé", "f2aa17b5c620f2a4": "{option} désactivé", "f59314a884aae1ff": "Par défaut", @@ -3576,6 +3628,14 @@ "c53bc5a4b0314342": "Média suivant", "2950b1424a3cddf5": "Reconnectez-vous à cet environnement et ouvrez à nouveau le média.", "ef638bf1479a5461": "L’environnement a renvoyé une URL de média non valide.", + "3ccfbf7e86868c35": "Retour pour l'équipe T3", + "4e0710d19dfc2e7e": "Envoyer ce rapport à l'équipe T3 ?", + "87d0ae0723ba75d1": "Voici tout ce qui quitte votre machine. Rien n'est envoyé tant que vous ne cliquez pas sur Envoyer.", + "bf19826f81484328": "Inclure la conversation", + "260c6b45f52d2f27": "Ajoute le texte de vos messages et des réponses de l'agent dans {textTurns, plural, one {le dernier tour} other {les {textTurns} derniers tours}}.", + "ddb7e6f8ce99e657": "Seule une personne autorisée à exécuter des agents sur cette machine peut l'envoyer ou le refuser.", + "03c1eb603c112f47": "Ne pas envoyer", + "653405e4ed498d9f": "Envoyer", "262955d6eb632f9b": "L’API Presse-papiers n’est pas disponible pour copier le lien invité.", "f1a4f2b04cdbb4ef": "Impossible de copier le lien invité dans le presse-papiers.", "cf3490a604e44d31": "Impossible de créer un lien invité.", @@ -3596,7 +3656,6 @@ "abd89e9eefedf11b": "Terminé", "18d166056c1ab6ff": "Arrêter le partage", "7a2d510eac9e4587": "Lien invité expiré", - "653405e4ed498d9f": "Envoyer", "21888e302219891d": "Aperçu agrandi de {title}", "419719298a7acaea": "Zoom arrière", "ed8d5db95359cff4": "Réinitialiser le zoom", @@ -3692,7 +3751,6 @@ "7c1923203049d602": "Copier le code", "637817e4ff79c90e": "Actions du bloc de code", "ebf3a2b1e314aa5f": "Exécuter dans le terminal", - "fe219642547fa0bf": "Exécuter dans le terminal", "122a8512abc51180": "Détails", "58c38c65c2783c5d": "Chemin complet", "f37e7d36b51c5b28": "Copier le chemin relatif", @@ -3704,10 +3762,6 @@ "4967584e8d0fb1c2": "Aperçu du média", "67589dd912eacb7c": "Ouvrir dans le navigateur intégré", "a3c98d4c4b24cecb": "Options du fichier {label}", - "b4fe8a076e9fd2f8": "Équation en bloc", - "085d1407e8c92cce": "Équation en ligne", - "a2ef393fa7b48ae8": "Faire défiler l’équation en bloc", - "e94685ea5642e088": "Faire défiler l’équation en ligne", "3a04583c8500e23d": "Afficher le diagramme", "16d64f650840fe06": "Afficher le code", "6d329f7d3a50c7e7": "Copier le tableau", @@ -3984,9 +4038,11 @@ "973e99fa86d7f531": "Message en file d’attente {position} sur {total}, non envoyé", "0f6087c4f53c7f17": "Démarrer un tour avec ce message ({shortcut})", "adab89933af02669": "Passer le compactage et envoyer ce message ({shortcut})", + "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", "3de4016452e8d2bd": "Envoyer dans le tour en cours ({shortcut})", "259cc9568148e8ad": "Démarrer un tour avec ce message", "bb7fddb812d5d29e": "Passer le compactage et envoyer ce message", + "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente", "a5fe1ee609b29a9f": "Envoyer dans le tour en cours", "2b7fd345e4f4fd6e": "Annuler la modification du message en file d’attente", "47f1726bf106d2c8": "Modifier le message en file d’attente", @@ -5599,7 +5655,6 @@ }, ". Vérifiez le chemin du lien ou retrouvez le fichier dans Fichiers." ], - "b9b6bbd1e1ea189f": "Fichier complet", "d715e9494fdbaaf6": "Impossible de charger la police.", "ff17c777a72b4408": "Les aperçus de polices sont limités à 10 Mo.", "6bd41ad699e22f10": "La police est indisponible.", @@ -5609,6 +5664,7 @@ "a9abaaa4220eae21": "{error} Enregistrez-la pour l’ouvrir dans une autre app.", "c508c9000d9656f8": "Aperçu de la police", "1c416d621d250be8": "Portez ce vieux whisky au juge blond qui fume.", + "d7d08260f16b7828": "Le fichier est encore en cours de chargement. Réessaie dans un instant.", "76ebb03de52c92d6": "La visionneuse de texte s’est arrêtée.", "f48162e8e8c12af7": "Impossible de charger la visionneuse de texte. Fermez le fichier et réessayez.", "bc4c5b13d38a5da7": "Aperçu fermé.", @@ -5616,8 +5672,6 @@ "9450d1827ef336a1": "Une autre copie est en cours.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} ligne} other {{formatted} lignes}}", "13b14784f8707ddd": "0 octet", - "f6e9581cba3467fa": "Indexation…", - "2d1f293ac12463fc": "Chargement du reste du fichier…", "b75105bef8f564a4": "Affichage des 1 024 premières colonnes. Source et Enregistrer conservent toutes les colonnes.", "2a6e1b1f209c3888": "Ce fichier est vide.", "192fc79eb3b5b2cb": "Ce diagramme contient des URL de ressources, du balisage, des métadonnées de nœuds ou une configuration personnalisée. Affichez la source Mermaid pour l’examiner en toute sécurité.", @@ -5804,7 +5858,6 @@ "0061fff77e36bd4f": "Impossible de joindre le serveur.", "04dfdd46e3dd4a2e": "Une erreur s’est produite. Réessayez.", "084bb2d8127a508d": "Envoyé", - "e7c59185f8ab3987": "Non envoyé", "77c01a15bd36d17c": "Ce lien a expiré ou n’est pas valide", "e0e736810f3cbef2": "Demandez un nouveau lien au propriétaire. Chaque lien fonctionne dans un seul navigateur.", "c3c53aa46f7330e5": "Ce lien a expiré", @@ -8828,6 +8881,12 @@ "d3866ead082d14e5": "Ajouter un raccourci clavier", "d4345c90894a3220": "Ouvrir keybindings.json", "e56a8d51219efaa0": "Aucun raccourci clavier ne correspond à votre recherche.", + "90a258fff61fd77e": "Désactivé", + "4060244a7079a0d2": "À ma demande", + "e88c9d8769544731": "Automatique", + "f29d1dade4dde8aa": "Les agents n'envoient aucun retour à l'équipe T3.", + "93c4c53562d30a98": "À votre demande, les agents vous présentent un court rapport sur T3 Code et l'envoient à l'équipe T3 si vous l'approuvez.", + "cd9ee803e8727017": "Les agents signalent aussi spontanément les problèmes qu'ils rencontrent dans T3 Code, comme un outil T3 qui échoue.", "45fa271ea0e1ac8e": "Bêta", "3a678332fc7142f7": "Regroupe les fils de la barre latérale dans des dossiers de projet. Les fils épinglés restent en haut, les fils reportés et clos restent sous les dossiers.", "e4e91d155cb6a9b4": "Barre latérale classique (regrouper par projet)", @@ -8836,11 +8895,16 @@ "9ae293971d93c819": "Partagez un fil avec un invité qui le suit en direct dans un navigateur et envoie des messages que vous approuvez. Connectez-vous à T3 Connect pour utiliser les liens invités.", "0aa5406ac4d7f7c7": "Liens invités", "f0e853acd2006d53": "Environnements associés", + "ef10c2dff987f3ea": "Exécutez des workflows en plusieurs étapes à partir des fichiers du dossier workflows du répertoire T3 de ce serveur. Ouvrez-les depuis la palette de commandes. Tant que c'est désactivé, rien dans ce dossier ne s'exécute ; les exécutions attendent sa réactivation.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Affiche un prochain message suggéré dans la zone de saisie vide après un tour Claude ou Codex. Tab l’utilise. Chaque suggestion est une requête en cache supplémentaire sur votre forfait. Nécessite Codex 0.165+. Les fils Claude se mettent à jour au redémarrage.", "d4b2a2ec812aafb0": "Suggérer le prochain prompt", "298c7150a7621c80": "Hôtes d’appareils Simlock", "67937aa49179285e": "Sur Mac, clone les nouveaux worktrees depuis une copie en cache dans le dossier T3 home au lieu d’écrire chaque fichier. Utilise le checkout Git normal quand ce n’est pas possible. La désactivation supprime le cache.", "f9904f78d3003f58": "Checkout rapide des worktrees", + "9c2f647882522302": "Les machines sélectionnées utilisent des modes de retour des agents différents.", + "31bbf7bf8c0a5279": "Retours des agents", + "d52b3d6bf9f2a013": "Mixte", "ec7623deed751c05": [ "Partagez un fil avec un invité qui le suit en direct dans un navigateur et envoie des messages que vous approuvez. Nécessite T3 Connect : connectez-vous et associez cette machine dans", " ", @@ -8925,7 +8989,9 @@ "fb71127e5746a6bc": "Depuis Partage et accès sur cette machine, ou t3 pair", "1e3fee7084791773": "Associer aussi {target} en retour à {source}", "ea34a190b0bd804c": "Les agents de {target} pourront alors aussi travailler sur {source}.", - "ad5ed0ce61b966eb": "Oublier {label} ? Les agents d’ici cessent d’y travailler. Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", + "974f8c65e8b5f492": "Oublier {label} ? Les agents d’ici cessent d’y travailler, et leur session sur {label} prend fin aussi s’il répond.", + "6cf9e3083b15614f": "{label} n’a pas répondu", + "34ccbdf619b83be3": "Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", "81c9796bf61b306a": "Impossible d’oublier l’association", "130e51beb6cf5aad": "Associer un environnement", "122c3e355699e69d": "Les agents d’ici pourront alors lancer des fils là-bas, leur envoyer des messages et les attendre. L’association apparaît sous Clients autorisés dans Partage et accès de cet environnement, où elle peut être révoquée.", @@ -9154,7 +9220,6 @@ "0b4779a1825c85bc": "Le nom commun de ce groupe de projets dans la barre latérale et les listes de fils.", "f68cbda4df83d739": "Réinitialiser le nom du projet à la valeur par défaut", "56e37b85027e8431": "Icône du projet", - "e88c9d8769544731": "Automatique", "c99736317da5b1fa": "Réinitialiser l’icône du projet à la valeur par défaut", "6afaa3e3739dc570": "Choisir une icône de projet", "51651ce45d481a20": "Choisir un fichier d’icône de projet", @@ -10127,7 +10192,6 @@ "a0eb0e4f76608833": "Ouvre d’abord les pull requests associées. Sinon, ouvre Modifications pour des changements touchant au moins 3 fichiers ou 50 lignes.", "16bdc70b858c223f": "Réinitialiser les panneaux proactifs à la valeur par défaut", "3e99c5c14f4939c8": "Réinitialiser le compactage des fils inactifs à la valeur par défaut", - "d52b3d6bf9f2a013": "Mixte", "cd72fe451ba0d6aa": "Nouveaux projets", "394c3bd0a1782c8e": "Laissez vide pour utiliser « ~/ » à l’ouverture du navigateur Ajouter un projet.", "f9b912a818bd869d": "Réinitialiser le répertoire de base pour l’ajout de projets à la valeur par défaut", @@ -11029,7 +11093,6 @@ "4a237f41ce592b7f": "Conserve les worktrees de ce projet jusqu’à ce que vous les supprimiez manuellement.", "00b8ffd8ea6e6a93": "Utilise ces règles pour ce projet.", "72c279824d15a999": "Utilise les paramètres de nettoyage des worktrees de chaque machine.", - "90a258fff61fd77e": "Désactivé", "b5702d0b64866b08": "Personnalisé", "c009c901f3eefe78": "Supprimer les worktrees des fils supprimés", "431c7cd6d50102b7": "Supprime les worktrees inutilisés quand des fils actifs ou archivés sont supprimés. Les worktrees avec des modifications locales sont conservés.", @@ -11725,7 +11788,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "À propos", "af4b7734da1d5ce7": "Voix", "4ec62c39ca3192bf": "Versions et tickets", "f2bf529f85e05494": "Partage et accès", @@ -11780,6 +11842,7 @@ "d443390c4d2dcfd4": "accessibilité a11y lecteur d’écran nvda jaws voiceover orca narrateur titre de fenêtre titre d’onglet alt tab barre des tâches statut du fil ordre en cours approbation", "6826fa9579c22035": "bêta partager invité invitation lien coéquipier regarder t3 connect tunnel", "f10c06cba0cdf7fe": "bêta associer une autre machine vps pair agents y travaillent déléguer", + "bc0b409d89ce086e": "bêta workflow exécutions durables automatisation étapes planification webhook dossier", "4a21cf825a2045b0": "bêta tab autocomplétion prédire prochain message claude codex texte fantôme", "fea2dc36585c4a20": "Hôtes d’appareils Simlock (alpha)", "9d834d178130180e": "bêta alpha simlock callstack simulateur émulateur ios android pool bail passerelle", @@ -11851,6 +11914,7 @@ "901a823214edc8c4": "télémétrie analytique données d’utilisation suivi mentions légales refuser", "82136480255a5106": "OTel OTLP télémétrie export points de terminaison journaux traces métriques Grafana", "659d081051faf7ff": "journaux traces processus historique des ressources échecs spans cpu mémoire", + "5eaeacfa9f82051a": "rapport bug problème t3 équipe envoyer retour agents outils automatique à ma demande", "f537f91e1ee41d47": "raccourcis clavier touches commandes associations json", "1ba01e7ceed64b95": "fenêtre capture capture d’écran", "279b1cceb779ff38": "Inclure le texte de l’app", @@ -12320,7 +12384,6 @@ "0bd41ff995d36a66": "Lecture du cache", "3f0dfe0cb15a3272": "Écriture du cache", "1c9d860be42b1c02": "Sortie", - "78344b60f407928e": "Autre", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Rapide", "66796576034c18ea": "Ultrarapide", @@ -12336,6 +12399,262 @@ "2cddd6095abc734a": "7 jours", "53493056306708cf": "30 jours", "c719359d18d37ad3": "90 jours", + "0bd950151ddc6407": "Quitter sans enregistrer ? Vos modifications de ce fichier seront perdues.", + "c0ba3f6756b09f30": "Modifications non enregistrées", + "6914e22d357f0ad6": "Enregistré et en service", + "aff389354a031d6f": "Le fichier sur le disque ne se charge pas. La dernière version valide continue de s’exécuter.", + "858effde748ab563": "Enregistré, mais il ne s’exécute pas encore.", + "ddb37138df660942": "Non enregistré. Rien n’a changé sur le serveur.", + "6ef4db489e40e39e": "Impossible d’enregistrer", + "c89624a2e9af1793": "{name} n’est pas connecté", + "b5a352a43adb4c17": "Ses workflows réapparaissent quand il se reconnecte. Choisis un autre environnement pour voir ses exécutions.", + "3dcedb736d20aae5": "Impossible de lire les fichiers de workflow", + "b09f4df8d76ae8ea": "Supprimer {file} ? Les workflows qu’il définit ne pourront plus être démarrés.", + "b4535f5a03689d27": "{name} n’est pas connecté. Ce que vous écrivez ici est conservé et pourra être enregistré dès son retour.", + "b54c78d85fd942ea": "Supprimé, mais ce qui s’exécute n’a pas encore suivi.", + "407c228d7da0b7df": "Non supprimé. Rien n’a changé sur le serveur.", + "1a6aa10f3cc14fff": "Ces fichiers ne sont pas cohérents entre eux. Ce qui s’exécutait avant continue de s’exécuter.", + "259312516a1dbe6f": "Nom du fichier", + "2f48ab2aa0586853": "Ne définit aucun workflow", + "ba5adfa37b55b8c5": [ + "Ligne ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " :" + ], + "d94eb9ab3201b641": "Supprimer", + "84c900d1ae72adc6": "Enregistrer", + "5912d817be03247a": "Le fichier a changé sur le disque pendant votre modification. L’enregistrement remplace ce changement.", + "0b1e6f5608826387": "Charger le fichier et abandonner mes modifications", + "f47b4c06aeb77c1c": "Chargement des fichiers de workflow…", + "4353bfd401d58f87": [ + "Chaque fichier de", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "définit des workflows. Toute modification est prise en compte sans redémarrage." + ], + "0c165251a06f10f1": "Nouveau fichier", + "8e97cf734b4463e7": "Créer", + "2ec0d5108fd6cebe": "Aucun workflow pour l’instant. Créez le premier fichier ici ou demandez à un agent d’en écrire un dans ce dossier.", + "5601350626e8cfe9": "Ne se charge pas", + "21d778a1b9a0c234": "Ouvert à côté de l’exécution", + "62dc4d3a19ff7ca0": "Fermer l’onglet", + "1e25265f2758fce3": "Ouvrir comme fil complet", + "672a3dae06b39402": "Ouvrir sur sa propre page", + "7755500a4cde5066": "Fermer le panneau", + "b8dcbc93a2ca1861": "Cette exécution ne le mentionne plus.", + "115c69de3202f664": "Ouvrir", + "644eafa9048b62df": "{count, plural, =1 {1er essai} =2 {2e essai} =3 {3e essai} other {{count}e essai}}", + "e39f89c909df4db0": "Impossible de reprendre l’exécution", + "865f034346b82f47": "Annuler {title} ? Ses agents s’arrêtent et l’exécution ne pourra pas être reprise.", + "6bc75632fd9c9136": "Impossible d’annuler l’exécution", + "64e50329dcfdd5b0": "Terminée", + "350162e7cc1ebea4": "Arrêtée", + "0875cf506f4c6810": "Ignorée", + "3cc43f1dbf3f8e0c": "Annulée", + "ded70e75de6404ba": "Retour à la liste des exécutions", + "2f4ed7dbd22be30d": "Annuler l’exécution", + "614e5ad58a795fb5": "Arrêter", + "04b050b0329f0ac8": "a duré {duration}", + "aff78e1774818ff4": "{duration} jusqu’ici", + "38eddd466439afc9": "Ce que l’exécution a touché", + "156ec271d49ddd70": "Ce qui s’est passé", + "34f59bbbead0b97f": "{names} et {count} de plus", + "ac1556f6ce89a5ea": "{count} en parallèle", + "e197c4963bacc746": "{count} en cours", + "f5319ed9e18c0df1": "Vous pose une question", + "882a25e9084ae1b2": "En pause", + "9a03d8a9afc60387": "Étapes jusqu’ici", + "2f2ae791afe01674": "attend ton approbation", + "24f8060c4ccdf928": "démarre", + "30a5be40eb956663": "en cours", + "dd7a1e58c2553933": "réveil dans {duration}", + "95cc952724dd7310": "réveil imminent", + "3cc34921c0128593": "en cours", + "e777db2880f53a46": "personne n’a répondu", + "dc90739d391a5e67": "Vous avez répondu {choice}", + "389f2563b5b763fd": "Étapes rapides", + "a41c8d758121ad81": "en veille", + "9db248b770096984": "a attendu", + "c76124517af28686": "en cours depuis {duration}", + "89102905bf09b0e8": "Suivre en direct", + "bdf338cdff4118f0": "Transcription", + "811e7e992f9ff820": "ne peut pas continuer tant que sa version du workflow n’est pas de nouveau enregistrée", + "4d4cdf035e98dd57": "attend que vous la repreniez", + "eb5b21dd224a5941": "réessaie d’elle-même dans {duration}", + "6ab3dfa749fde477": "va réessayer d’elle-même", + "44b6463aa70aa14c": "Raison de la pause", + "cf25e7169ab0eb7a": "En pause à {step}", + "56c48c1f220f2754": "Impossible de répondre à la question", + "a3c43735e1a81498": "Raison pour {title}", + "bfad234f016cfa3f": "Pourquoi, en une phrase. Elle accompagne la réponse que vous choisissez.", + "004c41aff9c97873": "Exécutions", + "4dc0c244a2419f6c": [ + "Fait partie de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "démarrée", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "sa version n’est plus enregistrée", + "f92d9132f7b85d1a": "Chargement des étapes…", + "6ebc59f64c761a49": "Rien pour l’instant.", + "a759dccd157d7dae": [ + "Vous avez répondu", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Vous avez répondu", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " : ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Ouvrir l’exécution", + "c8eb9be36d4d51ad": [ + "Fil sur ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Reprendre", + "8cebd63fc4c967d5": "Seule l’étape en échec est relancée ; ce qui s’est terminé avant est conservé.", + "bc1e0a2a0f1e9552": "Vous attendent", + "a812f51e970740f1": [ + "question posée", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· l’exécution vous attend" + ], + "02dfe6c63fd0b8a1": "Ajouter une raison", + "19abd94828a3bdbc": "Demander d’abord à l’agent", + "a18721fa8f328361": "Vous attendent", + "bbf24e7920c1e86b": "En cours", + "8d6e18d2ad832db6": "Toutes", + "f25af5332ffc3734": "Rien n’attend votre réponse.", + "c3f0119b8d6231f8": "Rien n’est en cours.", + "33028dfc1229eaa6": "Aucune exécution pour l’instant.", + "5459bf696a187c26": "Impossible de charger les exécutions de workflow", + "d57c35d43b0f163a": "Cette exécution n’est pas ici", + "b9aae2f7cdb1a379": "Aucune exécution de workflow pour l’instant", + "8f15f66e545af7c0": "Quelles exécutions", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Les {count} workflows", + "46d614fa7b4bf1e5": "Exécutions de workflow", + "1c635faa2fb45b8b": "Pas encore exécuté.", + "156ff7b625287a1e": "Masquer les éléments ignorés", + "69b985b97ab45e6b": "Afficher {count} ignorés", + "2400254d362de84d": "Chargement des exécutions de workflow…", + "145e1f7503ba3b2c": [ + "Cet environnement n’a aucune exécution avec ce lien.", + " ", + { + "t": "button", + "i": 1, + "c": "Retour aux exécutions" + } + ], + "783e616cb0476c17": [ + "Un workflow réunit agents, code, planifications et questions qui vous sont posées en une seule exécution qui survit aux redémarrages. Écrivez-en un dans", + " ", + { + "t": "button", + "i": 1, + "c": "Définitions" + }, + ", ou demandez-le à un agent.", + " ", + { + "t": "a", + "i": 2, + "c": "Lire le guide" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Un fichier de workflow présente un problème." + }, + " ", + "La dernière version valide continue de s’exécuter." + ], + "ed8ce6ebc73dc12d": "Ouvrir le fichier", + "5d8d278ff828102d": "Tous les workflows", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transcription", + "c512071143a5ba32": "Ce fil n’existe plus.", + "ed169d23683fb6ac": "Chargement du fil…", + "290e0ab40b87dc17": "Fil d’Ariane des workflows", + "683dd9831e54edc0": "Environnement", + "34ad53646f06ed80": "Les workflows sont désactivés", + "8f6589c9e0ac5d4e": "Aucun environnement connecté", + "744127f8dfad7d22": "Connectez un environnement pour voir ses exécutions de workflow.", + "036182ec7e2ee4d4": "À côté de l’exécution", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Définitions", + "f0a212aadfe1257b": "Chargement de l’éditeur…", + "20f194e003885e95": [ + "Activez-les pour ce serveur dans", + " ", + { + "t": "Link", + "i": 1, + "c": "Paramètres → Labs" + }, + "." + ], "8367779e149f723b": "La requête vers l’environnement principal a échoué pendant {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Jeton d’appairage non valide. Vérifiez le jeton et réessayez.", "0e4b49c8203aae81": "Délai dépassé en attendant la session authentifiée après l’amorçage.", @@ -12457,6 +12776,8 @@ "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", - "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", - "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente" + "99d51127f573296b": "Autre compte", + "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", + "99963c0142e17f00": "Pour le nouveau compte {tracker}.", + "6d8e4ebc889bace9": "Ajouter un compte" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index b257432a36c05..0e6d237df1668 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Forgejo または Gitea のサーバーごとに、{fjUrl} から {fj} 0.6 以降をインストールして {fjLogin} を実行するか、{teaUrl} から {tea} 0.16 以降をインストールして {teaLogin} を実行してください。", "d026a85e2e50e675": "{install} で GitCafe CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", "22d3c0c48a34b5b3": "{install} で TanStack Source CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", + "756c80ad262ef315": "元のスレッドで待機中", + "d8df14f9905f38eb": "送信済み", + "e7c59185f8ab3987": "未送信", + "b54ddec9084fa955": "送信せずに閉じました", + "fbaa7ab5da716e50": "不具合", + "01bac997ea55272e": "分かりにくい", + "0f53bc8f74dfe56a": "機能の不足", + "055560f307e15e30": "ドキュメントの誤り", + "78344b60f407928e": "その他", + "f653846a95cd6e8f": "種類", + "f41ea186c275b56e": "情報", + "2f6e4f7cd364da73": "期待した動作", + "9d11c93d4035de3e": "実際の動作", + "c87d0595693704f9": "代わりに行ったこと", + "d7a4ea6ce5af44e0": "{speaker} · {count} 文字", + "f5114fb9c40fd929": "あなた", + "cd03eb1b84271c02": "エージェント", + "bfe1a60f3f9c60fb": "ターン {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {直近 {turns} ターン} other {直近 {turns} ターン}}の概要、{textTurns, plural, =0 {メッセージ本文なし} one {最後のターンのメッセージ本文} other {直近 {textTurns} ターンのメッセージ本文}}{truncated, select, yes {、収まる長さに短縮済み} other {}}", + "afac52a5cc2dc801": "回答を送信できませんでした。もう一度お試しください。", "79d776428f4d0650": "ファイルを読み込めませんでした。再接続してもう一度お試しください。", "3ea34cbb1ca5ba9b": "プレビューをキャンセルしました。", "7c0af279ecb3da3a": "このランタイムではファイルのストリーミングプレビューを利用できません。", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "標準", "f42c2a36b3507308": "{label} オン", "77cc5f738cb7d459": "{label} オフ", - "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", "aba3bb73ce212f0c": "{names} を使うには {providerName} {version} 以降が必要ですが、Homebrew の claude-code cask には {latestVersion} までしかありません。claude-code@latest cask に切り替えてください: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", "d887bea446534de5": "この環境には {host}/{repository} を読み取れるプロジェクトがありません。", "4e466d60e2f7736b": "プルリクエストの完全な URL を貼り付けてください。このスレッドには番号を解決するためのリポジトリがありません。", "302625058bacbe38": "完全な URL を貼り付けてください。このプロジェクトのホストには既知の {changeRequest} URL がありません。", @@ -376,6 +396,31 @@ "476ca970255eaea4": "公開 URL を使うには、この環境を T3 Connect にリンクしてください。", "6b80f5b38a8f9950": "このアドレスを呼び出せるのはこのコンピューターだけです。公開 URL を使うには T3 Connect をリンクしてください。", "c5a7b1d3891dd0b8": "この環境のアドレスに到達できる場所ならどこでも動作します (Tailscale や独自のプロキシ経由など)。公開 URL を使うには T3 Connect をリンクしてください。", + "3669395daf36fd33": "このサーバーにはもう登録されていません", + "fe513cf316e796e3": "他のワークフローの一部として実行", + "ccf00b97925efab3": "手動で開始", + "421e585eb092b07b": "{triggers} で開始", + "7bd7c58592671384": "要対応", + "834ca879c14c167b": "作業中", + "582d6df7dfab86fb": "一時停止中", + "ea6583ce92507ee3": "スリープ中", + "7ea8cb8af281ce93": "待機中", + "1347868f2523140e": "完了", + "57d76c4614054271": "停止", + "5c7344bd51d0b966": "スキップ", + "b2074e9bd23049a6": "キャンセル済み", + "5bb7401807ee2fb5": "質問: {question} ほか {more} 件", + "9e4286183d5f9e34": "質問: {question}", + "474c18d001bd6717": "ステップが失敗しました", + "d3890f4eb1508781": "自身のステップを実行中", + "3e7ced10c9482af0": "{step} が作業中", + "237e1bcb1cf1bdec": "{step} でスリープ中", + "3f7b17ac5a20c8d2": "{run} を実行", + "0306f5f324b8aaa5": "{count} 件の実行が進行中", + "e8fd779b84a202a2": "待機中", + "b6d55657e1a027b8": "{step} を待機中", + "e942562a42aede34": "完了", + "26b2b9727fe11289": "早期終了", "1bb995dcec481554": "{host} でこのデバイスを承認してください。コード {verificationCode} が表示されています。", "8696a33219944832": "WebSocket の認可証明を作成できませんでした。", "5678f133a8631f7d": "クラウドのサインインが変更されました。環境を認可するには、もう一度サインインしてください。", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -1719,6 +1767,8 @@ "2e995206e087c3fc": "接続または保留中の入力が解決してから、返信してください。", "604ec3067171a0d7": "会話", "d6182a057ea12624": "親スレッド", + "f2d8537c33cc55a5": "ワークフロー実行のステップ", + "ba8337dca3232880": "実行を開く", "30fa4a764d11ae42": "{name} をダウンロードできませんでした", "4952f87dc98191a7": "添付ファイルを利用できません。", "2fd6d178493fb407": "現在のターンを中断できませんでした。", @@ -1804,6 +1854,7 @@ "04fd71efaa2c3b92": "プルリクエストを開く", "57e875b79b98ab82": "Issue を開く", "f1db0a234c777a1d": "他のアプリで T3 Code を使用 (MCP)", + "6050f22f63e2bcb5": "ワークフローを開く", "a0cc19e60dd99851": "使用量を開く", "46694969044eee98": "次のワークスペース領域にフォーカス", "0a1011328ba42eef": "前のワークスペース領域にフォーカス", @@ -2494,8 +2545,7 @@ "2d1c111e1b4ae0b0": "スレッド「{title}」を削除しますか?", "c568ab8dad798ec5": "このスレッドの会話履歴が完全に消去されます。", "0fd1c746a0e38003": "スレッドを削除できませんでした", - "0ecde875b0dd2f93": "プロジェクトでスレッドを絞り込み: {projects}", - "1ef65b647231ff0b": "プロジェクトでスレッドを絞り込み", + "1c8fc3c4a42949ab": "プロジェクト: {projects}", "165511761be2855c": "プロジェクトを検索", "a46a6467883575a4": "プロジェクトを検索...", "fdc0e086438a3045": "{project} のプロジェクト設定", @@ -2557,10 +2607,9 @@ }, " にインストール" ], + "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", "5bbac0e5afeec779": "現在のスレッド", "33c7e68fca089036": "スレッド、{title}", - "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", - "c6196d99000642b4": "スレッドを開く", "34cc63390ad793cc": "スレッドを選択", "8f12309ead62e38a": "スレッドまたはプロジェクトを検索...", "2f664754d005d9a7": "アクティブなスレッドが見つかりません。", @@ -2570,6 +2619,7 @@ "a3178769f8308cbc": "スレッドが失敗しました", "89b5e8f3887812da": "ゲストのリクエスト", "62e626804919b294": "入力が必要です", + "c6196d99000642b4": "スレッドを開く", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "あなた:", "a1fbf2422c588292": "エージェント:", @@ -2593,8 +2643,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "ターミナルのプロセスが実行中", "fc2c9a91f498ad6b": "{count, plural, other {{count} 個のターミナルプロセスが実行中。ターミナルを開く}}", - "643c4b50feadc874": "ワークツリー: {path} ({branch})", - "fb7c44da0f0825ea": "ワークツリー: {path}", "56f37ff8ca568059": "スタック", "6831e9a46cbd8939": "チェーン", "9aa9e74a3b7eee91": "チャットに追加", @@ -3031,8 +3079,8 @@ "6f85f14f35b3f547": "{provider} ({environment} 経由)", "7c59a888a062a8bd": "音声入力を記録する下書きがありません。", "62450481c00d2ef3": "下書きの環境を利用できないため、文字起こしを整形できません。", - "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "0674544195fcdc39": "元の文字起こしを追加しました。", + "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "296496693cdac0db": "t3 コマンドを利用できません。", "efbcef7bc9bbda01": "t3 コマンドの状態を読み込めませんでした。", "1bf6910332426e62": "デスクトップのネットワークアクセスを利用できません。", @@ -3275,6 +3323,7 @@ "4d493d0bda4d403d": "中断されたファイルをもう一度添付するか、削除してください", "c9cad1d84d5f1a32": "中断されたファイルをもう一度添付するか、削除してください", "536a820f2ff726da": "モデルを少なくとも 1 つ選択してください。", + "48d6389202ad6754": "準備ができたら送信", "fbafbe78b5e37966": "スレッドを再開", "bcd7eb979dd38dae": "入力欄を開いて圧縮して送信", "95ee62a0d6968b89": "メッセージを送信", @@ -3449,6 +3498,9 @@ "e778e4f446fdf873": "次のメッセージで新しいセッションが始まります", "0e2f2da4f2d94785": "エージェントはこのスレッドの以前のメッセージを参照できません。", "e1189d2e582b008d": "現在のセッションを維持", + "2bb448d605877a22": "編集または Esc でキャンセル", + "1a1f128d70c62304": "{count, plural, other {画像の準備ができたら送信}}", + "5af3ab719a9725fb": "メッセージを送信中", "461c9f865f2e9b92": "{option} オン", "f2aa17b5c620f2a4": "{option} オフ", "f59314a884aae1ff": "デフォルト", @@ -3572,6 +3624,14 @@ "c53bc5a4b0314342": "次のメディア", "2950b1424a3cddf5": "この環境に再接続してから、もう一度メディアを開いてください。", "ef638bf1479a5461": "環境から無効なメディア URL が返されました。", + "3ccfbf7e86868c35": "T3 チームへのフィードバック", + "4e0710d19dfc2e7e": "このレポートを T3 チームに送信しますか?", + "87d0ae0723ba75d1": "この内容だけがこのマシンから送信されます。「送信」を押すまで何も送信されません。", + "bf19826f81484328": "会話を含める", + "260c6b45f52d2f27": "直近 {textTurns} ターンでのあなたのメッセージとエージェントの返信の本文を追加します。", + "ddb7e6f8ce99e657": "このマシンでエージェントを実行できる人だけが、送信または拒否できます。", + "03c1eb603c112f47": "送信しない", + "653405e4ed498d9f": "送信", "262955d6eb632f9b": "ゲストリンクをコピーする際にクリップボード API を利用できませんでした。", "f1a4f2b04cdbb4ef": "ゲストリンクをクリップボードにコピーできませんでした。", "cf3490a604e44d31": "ゲストリンクを作成できませんでした。", @@ -3592,7 +3652,6 @@ "abd89e9eefedf11b": "完了", "18d166056c1ab6ff": "共有を停止", "7a2d510eac9e4587": "ゲストリンクの期限が切れました", - "653405e4ed498d9f": "送信", "21888e302219891d": "拡大した {title} のプレビュー", "419719298a7acaea": "縮小", "ed8d5db95359cff4": "ズームをリセット", @@ -3687,7 +3746,6 @@ "7c1923203049d602": "コードをコピー", "637817e4ff79c90e": "コードブロックの操作", "ebf3a2b1e314aa5f": "ターミナルで実行", - "fe219642547fa0bf": "ターミナルで実行", "122a8512abc51180": "詳細", "58c38c65c2783c5d": "フルパス", "f37e7d36b51c5b28": "相対パスをコピー", @@ -3699,10 +3757,6 @@ "4967584e8d0fb1c2": "メディアをプレビュー", "67589dd912eacb7c": "統合ブラウザーで開く", "a3c98d4c4b24cecb": "{label} のファイルオプション", - "b4fe8a076e9fd2f8": "ディスプレイ数式", - "085d1407e8c92cce": "インライン数式", - "a2ef393fa7b48ae8": "ディスプレイ数式をスクロール", - "e94685ea5642e088": "インライン数式をスクロール", "3a04583c8500e23d": "図を表示", "16d64f650840fe06": "コードを表示", "6d329f7d3a50c7e7": "表をコピー", @@ -3974,9 +4028,11 @@ "973e99fa86d7f531": "キュー内のメッセージ {position}/{total}、未送信", "0f6087c4f53c7f17": "このメッセージでターンを開始 ({shortcut})", "adab89933af02669": "圧縮をスキップしてこのメッセージを送信 ({shortcut})", + "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", "3de4016452e8d2bd": "現在のターンに送信 ({shortcut})", "259cc9568148e8ad": "このメッセージでターンを開始", "bb7fddb812d5d29e": "圧縮をスキップしてこのメッセージを送信", + "425ab15036aec8a4": "このコマンドをキューの先頭に移動", "a5fe1ee609b29a9f": "現在のターンに送信", "2b7fd345e4f4fd6e": "キュー内のメッセージの編集をキャンセル", "47f1726bf106d2c8": "キュー内のメッセージを編集", @@ -5581,7 +5637,6 @@ }, "。リンクのパスを確認するか、[ファイル] でファイルを探してください。" ], - "b9b6bbd1e1ea189f": "ファイル全体", "d715e9494fdbaaf6": "フォントを読み込めませんでした。", "ff17c777a72b4408": "フォントのプレビューは 10 MB までです。", "6bd41ad699e22f10": "フォントを利用できません。", @@ -5591,6 +5646,7 @@ "a9abaaa4220eae21": "{error} 別のアプリで開くには保存してください。", "c508c9000d9656f8": "フォントのプレビュー", "1c416d621d250be8": "いろはにほへと ちりぬるを わかよたれそ つねならむ", + "d7d08260f16b7828": "ファイルはまだ読み込み中です。少し待ってからもう一度お試しください。", "76ebb03de52c92d6": "テキストビューアーが停止しました。", "f48162e8e8c12af7": "テキストビューアーを読み込めませんでした。ファイルを閉じて、もう一度お試しください。", "bc4c5b13d38a5da7": "プレビューを閉じました。", @@ -5598,8 +5654,6 @@ "9450d1827ef336a1": "別のコピーが進行中です。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 バイト", - "f6e9581cba3467fa": "インデックスを作成しています…", - "2d1f293ac12463fc": "ファイルの残りを読み込んでいます…", "b75105bef8f564a4": "最初の 1,024 列を表示しています。ソースと保存ではすべての列が保持されます。", "2a6e1b1f209c3888": "このファイルは空です。", "192fc79eb3b5b2cb": "この図にはリソース URL、マークアップ、ノードのメタデータ、またはカスタム構成が含まれています。安全に確認するには Mermaid のソースを表示してください。", @@ -5786,7 +5840,6 @@ "0061fff77e36bd4f": "サーバーに接続できませんでした。", "04dfdd46e3dd4a2e": "問題が発生しました。もう一度お試しください。", "084bb2d8127a508d": "送信済み", - "e7c59185f8ab3987": "未送信", "77c01a15bd36d17c": "このリンクは終了したか、無効です", "e0e736810f3cbef2": "所有者に新しいリンクを依頼してください。各リンクは 1 つのブラウザーでのみ使用できます。", "c3c53aa46f7330e5": "このリンクは終了しました", @@ -8785,6 +8838,12 @@ "d3866ead082d14e5": "キーボードショートカットを追加", "d4345c90894a3220": "keybindings.json を開く", "e56a8d51219efaa0": "検索に一致するキーボードショートカットはありません。", + "90a258fff61fd77e": "オフ", + "4060244a7079a0d2": "依頼したとき", + "e88c9d8769544731": "自動", + "f29d1dade4dde8aa": "エージェントは T3 チームにフィードバックを送信しません。", + "93c4c53562d30a98": "依頼すると、エージェントが T3 Code についての短いレポートを表示し、承認した場合に T3 チームへ送信します。", + "cd9ee803e8727017": "エージェントが自ら遭遇した T3 Code の問題も報告します。たとえば、T3 ツールの失敗などです。", "45fa271ea0e1ac8e": "ベータ", "3a678332fc7142f7": "サイドバーのスレッドをプロジェクトフォルダーにまとめます。ピン留めしたスレッドは上部に残り、スヌーズ中と対応済みはフォルダーの下に表示されます。", "e4e91d155cb6a9b4": "シンプルなサイドバー(プロジェクトでグループ化)", @@ -8793,11 +8852,16 @@ "9ae293971d93c819": "スレッドをゲストと共有します。ゲストはブラウザーでライブで閲覧し、あなたが承認したメッセージを送信できます。ゲストリンクを使うには T3 Connect にサインインしてください。", "0aa5406ac4d7f7c7": "ゲストリンク", "f0e853acd2006d53": "リンクされた環境", + "ef10c2dff987f3ea": "このサーバーの T3 ホームにある workflows フォルダーのファイルから、複数ステップのワークフローを実行します。コマンドパレットから開けます。オフの間はそのフォルダーの内容は実行されず、実行はオンに戻るまで待機します。", + "2dadb2359422121c": "ワークフロー", "13e86eb5d8287a71": "Claude または Codex のターンの後、空の入力欄に次のメッセージの予測を表示します。Tab で使用します。毎回、プランでキャッシュされたリクエストが 1 つ追加されます。Codex 0.165 以降が必要です。Claude のスレッドは再起動時に更新されます。", "d4b2a2ec812aafb0": "次のプロンプトを提案", "298c7150a7621c80": "Simlock デバイスホスト", "67937aa49179285e": "Mac では、すべてのファイルを書き込む代わりに、T3 ホームフォルダーにキャッシュしたチェックアウトから新しいワークツリーを複製します。できない場合は Git の通常のチェックアウトを使います。オフにするとキャッシュは削除されます。", "f9904f78d3003f58": "高速ワークツリーチェックアウト", + "9c2f647882522302": "選択したマシンでは、エージェントのフィードバックモードが異なります。", + "31bbf7bf8c0a5279": "エージェントのフィードバック", + "d52b3d6bf9f2a013": "混在", "ec7623deed751c05": [ "スレッドをゲストと共有します。ゲストはブラウザーでライブで閲覧し、あなたが承認したメッセージを送信できます。T3 Connect が必要です。サインインして、", " ", @@ -8881,7 +8945,9 @@ "fb71127e5746a6bc": "リンク先の「共有とアクセス」、または t3 pair から", "1e3fee7084791773": "{target} から {source} へも逆方向にリンクする", "ea34a190b0bd804c": "{target} のエージェントも {source} で作業できるようになります。", - "ad5ed0ce61b966eb": "{label} を削除しますか?ここのエージェントはそこで作業できなくなります。そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", + "974f8c65e8b5f492": "{label} を削除しますか?ここのエージェントはそこで作業できなくなり、{label} が応答すればそこでのセッションも終了します。", + "6cf9e3083b15614f": "{label} が応答しませんでした", + "34ccbdf619b83be3": "そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", "81c9796bf61b306a": "リンクを削除できませんでした", "130e51beb6cf5aad": "環境をリンク", "122c3e355699e69d": "これで、ここのエージェントがそこでスレッドを起動し、メッセージを送り、完了を待てるようになります。リンクはその環境の「共有とアクセス」の「承認済みクライアント」に表示され、そこで取り消せます。", @@ -9111,7 +9177,6 @@ "0b4779a1825c85bc": "サイドバーとスレッド一覧に表示される、このプロジェクトグループの共通の名前です。", "f68cbda4df83d739": "プロジェクト名をデフォルトにリセット", "56e37b85027e8431": "プロジェクトのアイコン", - "e88c9d8769544731": "自動", "c99736317da5b1fa": "プロジェクトのアイコンをデフォルトにリセット", "6afaa3e3739dc570": "プロジェクトのアイコンを選択", "51651ce45d481a20": "プロジェクトのアイコンファイルを選択", @@ -10080,7 +10145,6 @@ "a0eb0e4f76608833": "リンクされたプルリクエストがあれば最初に開きます。ない場合は、3 ファイル以上または 50 行以上の編集で変更パネルを開きます。", "16bdc70b858c223f": "自動で開くパネルをデフォルトにリセット", "3e99c5c14f4939c8": "「アイドル状態のスレッドを圧縮」をデフォルトにリセット", - "d52b3d6bf9f2a013": "混在", "cd72fe451ba0d6aa": "新しいプロジェクト", "394c3bd0a1782c8e": "空のままにすると、「プロジェクトを追加」のブラウザーを開いたときに \"~/\" を使用します。", "f9b912a818bd869d": "プロジェクト追加のベースディレクトリをデフォルトにリセット", @@ -10980,7 +11044,6 @@ "4a237f41ce592b7f": "このプロジェクトのワークツリーは、手動で削除するまで保持します。", "00b8ffd8ea6e6a93": "このプロジェクトでこれらのルールを使用します。", "72c279824d15a999": "各マシンのワークツリーのクリーンアップ設定を使用します。", - "90a258fff61fd77e": "オフ", "b5702d0b64866b08": "カスタム", "c009c901f3eefe78": "削除したスレッドのワークツリーを削除", "431c7cd6d50102b7": "アクティブまたはアーカイブ済みのスレッドを削除したときに、使われていないワークツリーを削除します。ローカルの変更があるワークツリーは保持されます。", @@ -11676,7 +11739,6 @@ "4c70e3e7b3e6c493": "シークレット", "79b768229c9ef672": "メンテナンス", "54b188d65247e42f": "試験的機能", - "f41ea186c275b56e": "情報", "af4b7734da1d5ce7": "音声", "4ec62c39ca3192bf": "ソース管理と Issue", "f2bf529f85e05494": "共有とアクセス", @@ -11731,6 +11793,7 @@ "d443390c4d2dcfd4": "アクセシビリティ a11y スクリーンリーダー NVDA JAWS VoiceOver Orca ナレーター ウィンドウタイトル タブタイトル Alt+Tab タスクバー スレッド ステータス 順序 作業中 承認 accessibility", "6826fa9579c22035": "ベータ 共有 ゲスト 招待 リンク チームメイト 閲覧 T3 Connect トンネル beta share guest", "f10c06cba0cdf7fe": "ベータ リンク 別のマシン VPS ピア エージェント そこで作業 委任 beta link machine", + "bc0b409d89ce086e": "ベータ ワークフロー 永続 実行 自動化 ステップ スケジュール webhook フォルダー beta workflow", "4a21cf825a2045b0": "ベータ Tab 補完 次のメッセージを予測 Claude Codex ゴーストテキスト autocomplete", "fea2dc36585c4a20": "Simlock デバイスホスト (アルファ版)", "9d834d178130180e": "ベータ アルファ simlock callstack シミュレーター エミュレーター iOS Android プール リース ゲートウェイ simulator", @@ -11802,6 +11865,7 @@ "901a823214edc8c4": "テレメトリー 分析 使用状況データ トラッキング 法的事項 オプトアウト telemetry", "82136480255a5106": "OTel OTLP テレメトリー エクスポート エンドポイント ログ トレース メトリクス Grafana", "659d081051faf7ff": "ログ トレース プロセス リソース履歴 失敗 スパン CPU メモリ diagnostics", + "5eaeacfa9f82051a": "報告 不具合 問題 t3 チーム 送信 フィードバック エージェント ツール 自動 依頼したとき", "f537f91e1ee41d47": "キーボードショートカット ホットキー コマンド キーバインド JSON keybindings", "1ba01e7ceed64b95": "ウィンドウ キャプチャ スクリーンショット window capture", "279b1cceb779ff38": "アプリのテキストを含める", @@ -12271,7 +12335,6 @@ "0bd41ff995d36a66": "キャッシュの読み取り", "3f0dfe0cb15a3272": "キャッシュの書き込み", "1c9d860be42b1c02": "出力", - "78344b60f407928e": "その他", "684e516076de81fe": "標準", "3bbcc1b826fef537": "高速", "66796576034c18ea": "超高速", @@ -12287,6 +12350,254 @@ "2cddd6095abc734a": "7 日間", "53493056306708cf": "30 日間", "c719359d18d37ad3": "90 日間", + "0bd950151ddc6407": "保存せずに移動しますか?このファイルへの変更は失われます。", + "c0ba3f6756b09f30": "未保存の変更", + "6914e22d357f0ad6": "保存済み、実行中", + "aff389354a031d6f": "ディスク上のファイルを読み込めません。正常に読み込めた最後のバージョンが引き続き実行されます。", + "858effde748ab563": "保存しましたが、まだ実行されていません。", + "ddb37138df660942": "保存されませんでした。サーバー上では何も変更されていません。", + "6ef4db489e40e39e": "保存できませんでした", + "c89624a2e9af1793": "{name} は接続されていません", + "b5a352a43adb4c17": "再接続するとワークフローがまた表示されます。別の環境を選ぶと、その実行を確認できます。", + "3dcedb736d20aae5": "ワークフローファイルを読み取れませんでした", + "b09f4df8d76ae8ea": "{file} を削除しますか?このファイルで定義されたワークフローは開始できなくなります。", + "b4535f5a03689d27": "{name} は接続されていません。ここに書いた内容は残り、再接続後に保存できます。", + "b54c78d85fd942ea": "削除しましたが、実行中の内容はまだ反映されていません。", + "407c228d7da0b7df": "削除されませんでした。サーバー上では何も変更されていません。", + "1a6aa10f3cc14fff": "これらのファイルは互いに整合しません。以前のものが引き続き実行されます。", + "259312516a1dbe6f": "ファイル名", + "2f48ab2aa0586853": "ワークフローの定義なし", + "ba5adfa37b55b8c5": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 行目:" + ], + "d94eb9ab3201b641": "削除", + "84c900d1ae72adc6": "保存", + "5912d817be03247a": "編集中にディスク上のファイルが変更されました。保存するとその変更が上書きされます。", + "0b1e6f5608826387": "ファイルを読み込んで自分の変更を破棄", + "f47b4c06aeb77c1c": "ワークフローファイルを読み込んでいます…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "内のすべてのファイルがワークフローを定義します。変更は再起動なしで反映されます。" + ], + "0c165251a06f10f1": "新しいファイル", + "8e97cf734b4463e7": "作成", + "2ec0d5108fd6cebe": "ワークフローはまだありません。ここで最初のファイルを作成するか、エージェントにそのフォルダーへ作成するよう依頼してください。", + "5601350626e8cfe9": "読み込めません", + "21d778a1b9a0c234": "実行の横で開いているもの", + "62dc4d3a19ff7ca0": "タブを閉じる", + "1e25265f2758fce3": "通常のスレッドとして開く", + "672a3dae06b39402": "専用のページで開く", + "7755500a4cde5066": "ペインを閉じる", + "b8dcbc93a2ca1861": "この実行には含まれなくなりました。", + "115c69de3202f664": "開く", + "644eafa9048b62df": "{count, plural, =1 {1 回目の試行} =2 {2 回目の試行} =3 {3 回目の試行} other {{count} 回目の試行}}", + "e39f89c909df4db0": "実行を再開できませんでした", + "865f034346b82f47": "{title} をキャンセルしますか?エージェントは停止し、この実行は再開できなくなります。", + "6bc75632fd9c9136": "実行をキャンセルできませんでした", + "64e50329dcfdd5b0": "完了", + "350162e7cc1ebea4": "停止", + "0875cf506f4c6810": "スキップ", + "3cc43f1dbf3f8e0c": "キャンセル済み", + "ded70e75de6404ba": "実行一覧に戻る", + "2f4ed7dbd22be30d": "実行をキャンセル", + "614e5ad58a795fb5": "停止", + "04b050b0329f0ac8": "所要時間 {duration}", + "aff78e1774818ff4": "{duration} 経過", + "38eddd466439afc9": "この実行が扱ったもの", + "156ec271d49ddd70": "経過", + "34f59bbbead0b97f": "{names} ほか {count} 件", + "ac1556f6ce89a5ea": "{count} 件を並行", + "e197c4963bacc746": "{count} 件実行中", + "f5319ed9e18c0df1": "あなたへの質問", + "882a25e9084ae1b2": "一時停止中", + "9a03d8a9afc60387": "これまでのステップ", + "2f2ae791afe01674": "承認待ち", + "24f8060c4ccdf928": "開始中", + "30a5be40eb956663": "作業中", + "dd7a1e58c2553933": "{duration} 後にスリープ解除", + "95cc952724dd7310": "まもなくスリープ解除", + "3cc34921c0128593": "実行中", + "e777db2880f53a46": "回答なし", + "dc90739d391a5e67": "あなたの回答: {choice}", + "389f2563b5b763fd": "短いステップ", + "a41c8d758121ad81": "スリープ", + "9db248b770096984": "待機", + "c76124517af28686": "{duration} 実行中", + "89102905bf09b0e8": "ライブで見る", + "bdf338cdff4118f0": "トランスクリプト", + "811e7e992f9ff820": "ワークフローのバージョンが再登録されるまで続行できません", + "4d4cdf035e98dd57": "手動での再開待ち", + "eb5b21dd224a5941": "{duration} 後に自動で再試行", + "6ab3dfa749fde477": "まもなく自動で再試行", + "44b6463aa70aa14c": "一時停止の理由", + "cf25e7169ab0eb7a": "{step} で一時停止中", + "56c48c1f220f2754": "質問に回答できませんでした", + "a3c43735e1a81498": "{title} の理由", + "bfad234f016cfa3f": "理由を一文で。どの回答を選んでも一緒に送信されます。", + "004c41aff9c97873": "実行", + "4dc0c244a2419f6c": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " の一部" + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "に開始" + ], + "8bffb377e2a6a7de": "そのバージョンはもう登録されていません", + "f92d9132f7b85d1a": "ステップを読み込んでいます…", + "6ebc59f64c761a49": "まだ何もありません。", + "a759dccd157d7dae": [ + "あなたの回答: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "あなたの回答: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "実行を開く", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 上のスレッド" + ], + "3d9761e81798fcd8": "再開", + "8cebd63fc4c967d5": "失敗したステップだけが再実行されます。それより前に完了したものは保持されます。", + "bc1e0a2a0f1e9552": "要対応", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "に質問", + " ", + "· 実行はあなたの回答を待っています" + ], + "02dfe6c63fd0b8a1": "理由を追加", + "19abd94828a3bdbc": "先にエージェントに質問", + "a18721fa8f328361": "要対応", + "bbf24e7920c1e86b": "実行中", + "8d6e18d2ad832db6": "すべて", + "f25af5332ffc3734": "対応待ちのものはありません。", + "c3f0119b8d6231f8": "実行中のものはありません。", + "33028dfc1229eaa6": "実行はまだありません。", + "5459bf696a187c26": "ワークフローの実行を読み込めませんでした", + "d57c35d43b0f163a": "この実行はここにありません", + "b9aae2f7cdb1a379": "ワークフローの実行はまだありません", + "8f15f66e545af7c0": "表示する実行", + "b6409289e0c9a4dd": "ワークフロー", + "035cb02ca1ae4952": "すべてのワークフロー ({count} 件)", + "46d614fa7b4bf1e5": "ワークフローの実行", + "1c635faa2fb45b8b": "まだ実行されていません。", + "156ff7b625287a1e": "スキップ済みを非表示", + "69b985b97ab45e6b": "スキップ済み {count} 件を表示", + "2400254d362de84d": "ワークフローの実行を読み込んでいます…", + "145e1f7503ba3b2c": [ + "この環境には、そのリンクの実行はありません。", + " ", + { + "t": "button", + "i": 1, + "c": "実行一覧に戻る" + } + ], + "783e616cb0476c17": [ + "ワークフローは、エージェント、コード、スケジュール、あなたへの質問を、再起動後も継続する 1 つの実行にまとめます。", + { + "t": "button", + "i": 1, + "c": "定義" + }, + " ", + "で作成するか、エージェントに依頼してください。", + " ", + { + "t": "a", + "i": 2, + "c": "ガイドを読む" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "ワークフローファイルに問題があります。" + }, + " ", + "正常に読み込めた最後のバージョンが引き続き実行されます。" + ], + "ed8ce6ebc73dc12d": "ファイルを開く", + "5d8d278ff828102d": "すべてのワークフロー", + "39459da07479f482": "エージェント", + "7741243632056b81": "{step} · トランスクリプト", + "c512071143a5ba32": "このスレッドはもう存在しません。", + "ed169d23683fb6ac": "スレッドを読み込んでいます…", + "290e0ab40b87dc17": "ワークフローのパンくずリスト", + "683dd9831e54edc0": "環境", + "34ad53646f06ed80": "ワークフローはオフです", + "8f6589c9e0ac5d4e": "接続されている環境がありません", + "744127f8dfad7d22": "環境を接続すると、そのワークフローの実行が表示されます。", + "036182ec7e2ee4d4": "実行の横", + "2d6107cb78382d08": "ワークフロー", + "16f7df687349b399": "定義", + "f0a212aadfe1257b": "エディターを読み込んでいます…", + "20f194e003885e95": [ + "このサーバーの", + " ", + { + "t": "Link", + "i": 1, + "c": "設定 → Labs" + }, + " でオンにしてください。" + ], "8367779e149f723b": "プライマリ環境へのリクエストが {operation} 中に失敗しました (HTTP {status})。", "c5cd027743a2b5a6": "ペアリングトークンが無効です。トークンを確認して、もう一度お試しください。", "0e4b49c8203aae81": "ブートストラップ後、認証済みセッションの待機がタイムアウトしました。", @@ -12406,6 +12717,8 @@ "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", - "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", - "425ab15036aec8a4": "このコマンドをキューの先頭に移動" + "99d51127f573296b": "別のアカウント", + "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", + "99963c0142e17f00": "新しい {tracker} アカウント用です。", + "6d8e4ebc889bace9": "アカウントを追加" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 0bc3940cf927f..2e98c679624c3 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "{fjUrl}에서 {fj} 0.6 이상을 설치하고 {fjLogin}을(를) 실행하거나, {teaUrl}에서 {tea} 0.16 이상을 설치하고 Forgejo 또는 Gitea 서버마다 {teaLogin}을(를) 실행하세요.", "d026a85e2e50e675": "{install}로 GitCafe CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", "22d3c0c48a34b5b3": "{install}로 TanStack Source CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", + "756c80ad262ef315": "원래 스레드에서 대기 중", + "d8df14f9905f38eb": "보냄", + "e7c59185f8ab3987": "보내지 않음", + "b54ddec9084fa955": "보내지 않고 닫음", + "fbaa7ab5da716e50": "버그", + "01bac997ea55272e": "이해하기 어려움", + "0f53bc8f74dfe56a": "기능 부족", + "055560f307e15e30": "잘못된 문서", + "78344b60f407928e": "기타", + "f653846a95cd6e8f": "유형", + "f41ea186c275b56e": "정보", + "2f6e4f7cd364da73": "기대한 동작", + "9d11c93d4035de3e": "실제 동작", + "c87d0595693704f9": "대신 한 일", + "d7a4ea6ce5af44e0": "{speaker} · {count}자", + "f5114fb9c40fd929": "나", + "cd03eb1b84271c02": "에이전트", + "bfe1a60f3f9c60fb": "턴 {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {최근 {turns}개 턴} other {최근 {turns}개 턴}}의 개요, {textTurns, plural, =0 {메시지 본문 없음} one {마지막 턴의 메시지 본문} other {최근 {textTurns}개 턴의 메시지 본문}}{truncated, select, yes {, 길이에 맞게 줄임} other {}}", + "afac52a5cc2dc801": "답변을 보내지 못했습니다. 다시 시도하세요.", "79d776428f4d0650": "파일을 불러올 수 없습니다. 다시 연결한 뒤 시도하세요.", "3ea34cbb1ca5ba9b": "미리 보기가 취소되었습니다.", "7c0af279ecb3da3a": "이 런타임에서는 스트리밍 파일 미리 보기를 사용할 수 없습니다.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "보통", "f42c2a36b3507308": "{label} 켜짐", "77cc5f738cb7d459": "{label} 꺼짐", - "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", "aba3bb73ce212f0c": "{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만 Homebrew claude-code cask에는 {latestVersion}까지만 있습니다. claude-code@latest cask로 전환하세요: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", "d887bea446534de5": "이 환경에는 {host}/{repository}을(를) 읽을 수 있는 프로젝트가 없습니다.", "4e466d60e2f7736b": "전체 풀 리퀘스트 URL을 붙여 넣으세요. 이 스레드에는 번호를 확인할 저장소가 없습니다.", "302625058bacbe38": "전체 URL을 붙여 넣으세요. 이 프로젝트의 호스트에는 알려진 {changeRequest} URL이 없습니다.", @@ -376,6 +396,31 @@ "476ca970255eaea4": "공개 URL을 사용하려면 이 환경을 T3 Connect에 연결하세요.", "6b80f5b38a8f9950": "이 컴퓨터에서만 이 주소를 호출할 수 있습니다. 공개 URL을 사용하려면 T3 Connect를 연결하세요.", "c5a7b1d3891dd0b8": "Tailscale이나 자체 프록시처럼 이 환경의 주소에 접근할 수 있는 곳이면 어디서든 작동합니다. 공개 URL을 사용하려면 T3 Connect를 연결하세요.", + "3669395daf36fd33": "이 서버에 더 이상 등록되어 있지 않음", + "fe513cf316e796e3": "다른 워크플로의 일부로 실행", + "ccf00b97925efab3": "수동으로 시작", + "421e585eb092b07b": "{triggers}에서 시작", + "7bd7c58592671384": "확인 필요", + "834ca879c14c167b": "작업 중", + "582d6df7dfab86fb": "일시 중지됨", + "ea6583ce92507ee3": "슬립 중", + "7ea8cb8af281ce93": "대기 중", + "1347868f2523140e": "완료", + "57d76c4614054271": "중지됨", + "5c7344bd51d0b966": "건너뜀", + "b2074e9bd23049a6": "취소됨", + "5bb7401807ee2fb5": "질문: {question} 외 {more}개", + "9e4286183d5f9e34": "질문: {question}", + "474c18d001bd6717": "단계 실패", + "d3890f4eb1508781": "자체 단계 실행 중", + "3e7ced10c9482af0": "{step} 작업 중", + "237e1bcb1cf1bdec": "{step}에서 슬립 중", + "3f7b17ac5a20c8d2": "{run} 실행", + "0306f5f324b8aaa5": "실행 {count}개 진행 중", + "e8fd779b84a202a2": "대기 중", + "b6d55657e1a027b8": "{step} 대기 중", + "e942562a42aede34": "완료", + "26b2b9727fe11289": "조기 종료", "1bb995dcec481554": "{host}에서 이 기기를 승인하세요. 코드 {verificationCode}이(가) 표시됩니다.", "8696a33219944832": "WebSocket 인증 증명을 만들 수 없습니다.", "5678f133a8631f7d": "클라우드 로그인이 변경되었습니다. 환경을 인증하려면 다시 로그인하세요.", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", @@ -1719,6 +1767,8 @@ "2e995206e087c3fc": "연결 또는 대기 중인 입력이 해결된 후 답장해 보세요.", "604ec3067171a0d7": "대화", "d6182a057ea12624": "상위 스레드", + "f2d8537c33cc55a5": "워크플로 실행의 단계", + "ba8337dca3232880": "실행 열기", "30fa4a764d11ae42": "{name}을(를) 다운로드할 수 없습니다", "4952f87dc98191a7": "첨부 파일을 사용할 수 없습니다.", "2fd6d178493fb407": "현재 턴을 중단하지 못했습니다.", @@ -1804,6 +1854,7 @@ "04fd71efaa2c3b92": "풀 리퀘스트 열기", "57e875b79b98ab82": "이슈 열기", "f1db0a234c777a1d": "다른 앱에서 T3 Code 사용(MCP)", + "6050f22f63e2bcb5": "워크플로 열기", "a0cc19e60dd99851": "사용량 열기", "46694969044eee98": "다음 작업 영역으로 포커스 이동", "0a1011328ba42eef": "이전 작업 영역으로 포커스 이동", @@ -2495,8 +2546,7 @@ "2d1c111e1b4ae0b0": "스레드 \"{title}\"을(를) 삭제할까요?", "c568ab8dad798ec5": "이 스레드의 대화 기록이 영구적으로 삭제됩니다.", "0fd1c746a0e38003": "스레드를 삭제하지 못했습니다", - "0ecde875b0dd2f93": "프로젝트별 스레드 필터: {projects}", - "1ef65b647231ff0b": "프로젝트별 스레드 필터", + "1c8fc3c4a42949ab": "프로젝트: {projects}", "165511761be2855c": "프로젝트 검색", "a46a6467883575a4": "프로젝트 검색...", "fdc0e086438a3045": "{project} 프로젝트 설정", @@ -2558,10 +2608,9 @@ }, "에 설치" ], + "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", "5bbac0e5afeec779": "현재 스레드", "33c7e68fca089036": "스레드, {title}", - "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", - "c6196d99000642b4": "스레드 열기", "34cc63390ad793cc": "스레드 선택", "8f12309ead62e38a": "스레드 또는 프로젝트 검색...", "2f664754d005d9a7": "활성 스레드를 찾을 수 없습니다.", @@ -2571,6 +2620,7 @@ "a3178769f8308cbc": "스레드 실패", "89b5e8f3887812da": "게스트 요청", "62e626804919b294": "입력 필요", + "c6196d99000642b4": "스레드 열기", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "나:", "a1fbf2422c588292": "에이전트:", @@ -2594,8 +2644,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "터미널 프로세스 실행 중", "fc2c9a91f498ad6b": "{count, plural, other {터미널 프로세스 {count}개 실행 중. 터미널 열기}}", - "643c4b50feadc874": "워크트리: {path}({branch})", - "fb7c44da0f0825ea": "워크트리: {path}", "56f37ff8ca568059": "스택", "6831e9a46cbd8939": "체인", "9aa9e74a3b7eee91": "채팅에 추가", @@ -3032,8 +3080,8 @@ "6f85f14f35b3f547": "{environment}을(를) 통한 {provider}", "7c59a888a062a8bd": "음성 입력을 기록할 초안이 없습니다.", "62450481c00d2ef3": "초안의 환경을 사용할 수 없어 받아쓴 내용을 정리할 수 없습니다.", - "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "0674544195fcdc39": "원본 받아쓰기 내용이 추가되었습니다.", + "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "296496693cdac0db": "t3 명령을 사용할 수 없습니다.", "efbcef7bc9bbda01": "t3 명령 상태를 불러오지 못했습니다.", "1bf6910332426e62": "데스크톱 네트워크 액세스를 사용할 수 없습니다.", @@ -3276,6 +3324,7 @@ "4d493d0bda4d403d": "중단된 파일을 다시 첨부하거나 제거하세요", "c9cad1d84d5f1a32": "중단된 파일을 다시 첨부하거나 제거하세요", "536a820f2ff726da": "모델을 하나 이상 선택하세요.", + "48d6389202ad6754": "준비되면 전송", "fbafbe78b5e37966": "스레드 재개", "bcd7eb979dd38dae": "압축하고 보내려면 입력창을 여세요", "95ee62a0d6968b89": "메시지 보내기", @@ -3449,6 +3498,9 @@ "e778e4f446fdf873": "다음 메시지부터 새 세션이 시작됩니다", "0e2f2da4f2d94785": "에이전트는 이 스레드의 이전 메시지를 볼 수 없습니다.", "e1189d2e582b008d": "현재 세션 유지", + "2bb448d605877a22": "편집하거나 Esc를 눌러 취소", + "1a1f128d70c62304": "{count, plural, other {이미지가 준비되면 전송}}", + "5af3ab719a9725fb": "메시지 전송 중", "461c9f865f2e9b92": "{option} 켜짐", "f2aa17b5c620f2a4": "{option} 꺼짐", "f59314a884aae1ff": "기본값", @@ -3572,6 +3624,14 @@ "c53bc5a4b0314342": "다음 미디어", "2950b1424a3cddf5": "이 환경에 다시 연결한 후 미디어를 다시 여세요.", "ef638bf1479a5461": "환경에서 잘못된 미디어 URL을 반환했습니다.", + "3ccfbf7e86868c35": "T3 팀에 보내는 피드백", + "4e0710d19dfc2e7e": "이 보고서를 T3 팀에 보낼까요?", + "87d0ae0723ba75d1": "이 내용만 이 컴퓨터에서 전송됩니다. 보내기를 누르기 전에는 아무것도 전송되지 않습니다.", + "bf19826f81484328": "대화 포함", + "260c6b45f52d2f27": "최근 {textTurns}개 턴에서 내 메시지와 에이전트 답변의 본문을 추가합니다.", + "ddb7e6f8ce99e657": "이 컴퓨터에서 에이전트를 실행할 수 있는 사람만 보고서를 보내거나 거절할 수 있습니다.", + "03c1eb603c112f47": "보내지 않기", + "653405e4ed498d9f": "보내기", "262955d6eb632f9b": "게스트 링크를 복사하는 중 클립보드 API를 사용할 수 없습니다.", "f1a4f2b04cdbb4ef": "게스트 링크를 클립보드에 복사하지 못했습니다.", "cf3490a604e44d31": "게스트 링크를 만들 수 없습니다.", @@ -3592,7 +3652,6 @@ "abd89e9eefedf11b": "완료", "18d166056c1ab6ff": "공유 중지", "7a2d510eac9e4587": "게스트 링크 만료됨", - "653405e4ed498d9f": "보내기", "21888e302219891d": "확대된 {title} 미리 보기", "419719298a7acaea": "축소", "ed8d5db95359cff4": "확대/축소 초기화", @@ -3687,7 +3746,6 @@ "7c1923203049d602": "코드 복사", "637817e4ff79c90e": "코드 블록 작업", "ebf3a2b1e314aa5f": "터미널에서 실행", - "fe219642547fa0bf": "터미널에서 실행", "122a8512abc51180": "세부 정보", "58c38c65c2783c5d": "전체 경로", "f37e7d36b51c5b28": "상대 경로 복사", @@ -3699,10 +3757,6 @@ "4967584e8d0fb1c2": "미디어 미리 보기", "67589dd912eacb7c": "통합 브라우저에서 열기", "a3c98d4c4b24cecb": "{label} 파일 옵션", - "b4fe8a076e9fd2f8": "블록 수식", - "085d1407e8c92cce": "인라인 수식", - "a2ef393fa7b48ae8": "블록 수식 스크롤", - "e94685ea5642e088": "인라인 수식 스크롤", "3a04583c8500e23d": "다이어그램 표시", "16d64f650840fe06": "코드 표시", "6d329f7d3a50c7e7": "표 복사", @@ -3972,9 +4026,11 @@ "973e99fa86d7f531": "대기열 메시지 {total}개 중 {position}번째, 보내지 않음", "0f6087c4f53c7f17": "이 메시지로 턴 시작({shortcut})", "adab89933af02669": "압축을 건너뛰고 이 메시지 보내기({shortcut})", + "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", "3de4016452e8d2bd": "현재 턴에 보내기({shortcut})", "259cc9568148e8ad": "이 메시지로 턴 시작", "bb7fddb812d5d29e": "압축을 건너뛰고 이 메시지 보내기", + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동", "a5fe1ee609b29a9f": "현재 턴에 보내기", "2b7fd345e4f4fd6e": "대기열 메시지 편집 취소", "47f1726bf106d2c8": "대기열 메시지 편집", @@ -5579,7 +5635,6 @@ }, ". 링크의 경로를 확인하거나 파일에서 해당 파일을 찾으세요." ], - "b9b6bbd1e1ea189f": "전체 파일", "d715e9494fdbaaf6": "글꼴을 불러올 수 없습니다.", "ff17c777a72b4408": "글꼴 미리 보기는 10MB로 제한됩니다.", "6bd41ad699e22f10": "글꼴을 사용할 수 없습니다.", @@ -5589,6 +5644,7 @@ "a9abaaa4220eae21": "{error} 저장한 후 다른 앱에서 여세요.", "c508c9000d9656f8": "글꼴 미리 보기", "1c416d621d250be8": "다람쥐 헌 쳇바퀴에 타고파.", + "d7d08260f16b7828": "파일을 아직 불러오는 중입니다. 잠시 후 다시 시도하세요.", "76ebb03de52c92d6": "텍스트 뷰어가 중지되었습니다.", "f48162e8e8c12af7": "텍스트 뷰어를 불러올 수 없습니다. 파일을 닫고 다시 시도하세요.", "bc4c5b13d38a5da7": "미리 보기가 닫혔습니다.", @@ -5596,8 +5652,6 @@ "9450d1827ef336a1": "다른 복사가 진행 중입니다.", "8f48999eb6d9e2e3": "{count, plural, other {{formatted}줄}}", "13b14784f8707ddd": "0바이트", - "f6e9581cba3467fa": "색인하는 중…", - "2d1f293ac12463fc": "파일의 나머지를 불러오는 중…", "b75105bef8f564a4": "처음 1,024열을 표시합니다. 소스와 저장에는 모든 열이 유지됩니다.", "2a6e1b1f209c3888": "이 파일은 비어 있습니다.", "192fc79eb3b5b2cb": "이 다이어그램에는 리소스 URL, 마크업, 노드 메타데이터 또는 사용자 지정 구성이 포함되어 있습니다. 안전하게 확인하려면 Mermaid 소스를 표시하세요.", @@ -5784,7 +5838,6 @@ "0061fff77e36bd4f": "서버에 연결할 수 없습니다.", "04dfdd46e3dd4a2e": "문제가 발생했습니다. 다시 시도하세요.", "084bb2d8127a508d": "보냄", - "e7c59185f8ab3987": "보내지 않음", "77c01a15bd36d17c": "이 링크는 종료되었거나 유효하지 않습니다", "e0e736810f3cbef2": "소유자에게 새 링크를 요청하세요. 각 링크는 한 브라우저에서만 작동합니다.", "c3c53aa46f7330e5": "이 링크는 종료되었습니다", @@ -8788,6 +8841,12 @@ "d3866ead082d14e5": "단축키 추가", "d4345c90894a3220": "keybindings.json 열기", "e56a8d51219efaa0": "검색과 일치하는 단축키가 없습니다.", + "90a258fff61fd77e": "끔", + "4060244a7079a0d2": "내가 요청할 때", + "e88c9d8769544731": "자동", + "f29d1dade4dde8aa": "에이전트가 T3 팀에 피드백을 보내지 않습니다.", + "93c4c53562d30a98": "요청하면 에이전트가 T3 Code에 관한 짧은 보고서를 보여주고, 승인하면 T3 팀에 보냅니다.", + "cd9ee803e8727017": "에이전트가 직접 겪은 T3 Code 문제도 보고합니다. 예를 들어 T3 도구가 실패한 경우입니다.", "45fa271ea0e1ac8e": "베타", "3a678332fc7142f7": "사이드바 스레드를 프로젝트 폴더로 묶습니다. 고정된 스레드는 맨 위에, 다시 알림과 정리됨은 폴더 아래에 유지됩니다.", "e4e91d155cb6a9b4": "단순 사이드바(프로젝트별 그룹화)", @@ -8796,11 +8855,16 @@ "9ae293971d93c819": "브라우저에서 실시간으로 지켜보고 승인한 메시지를 보낼 수 있는 게스트와 스레드를 공유합니다. 게스트 링크를 사용하려면 T3 Connect에 로그인하세요.", "0aa5406ac4d7f7c7": "게스트 링크", "f0e853acd2006d53": "연결된 환경", + "ef10c2dff987f3ea": "이 서버 T3 홈의 workflows 폴더에 있는 파일로 여러 단계의 워크플로를 실행합니다. 명령 팔레트에서 엽니다. 꺼져 있는 동안에는 그 폴더의 어떤 것도 실행되지 않으며, 실행은 다시 켤 때까지 기다립니다.", + "2dadb2359422121c": "워크플로", "13e86eb5d8287a71": "Claude 또는 Codex 턴이 끝난 뒤 빈 입력창에 예상되는 다음 메시지를 표시합니다. Tab을 누르면 사용합니다. 제안마다 요금제에서 캐시된 요청이 하나 더 발생합니다. Codex 0.165 이상이 필요합니다. Claude 스레드는 다시 시작하면 업데이트됩니다.", "d4b2a2ec812aafb0": "다음 프롬프트 제안", "298c7150a7621c80": "Simlock 기기 호스트", "67937aa49179285e": "Mac에서 모든 파일을 쓰는 대신 T3 홈 폴더에 캐시된 체크아웃에서 새 워크트리를 복제합니다. 불가능하면 Git의 일반 체크아웃을 사용합니다. 끄면 캐시가 삭제됩니다.", "f9904f78d3003f58": "빠른 워크트리 체크아웃", + "9c2f647882522302": "선택한 컴퓨터의 에이전트 피드백 모드가 서로 다릅니다.", + "31bbf7bf8c0a5279": "에이전트 피드백", + "d52b3d6bf9f2a013": "혼합", "ec7623deed751c05": [ "브라우저에서 실시간으로 지켜보고 승인한 메시지를 보낼 수 있는 게스트와 스레드를 공유합니다. T3 Connect가 필요합니다. 로그인한 뒤", " ", @@ -8884,7 +8948,9 @@ "fb71127e5746a6bc": "그곳의 공유 및 액세스 또는 t3 pair에서", "1e3fee7084791773": "{target}에서 {source}(으)로도 반대 방향 연결", "ea34a190b0bd804c": "그러면 {target}의 에이전트도 {source}에서 작업할 수 있습니다.", - "ad5ed0ce61b966eb": "{label}을(를) 삭제할까요? 이곳의 에이전트가 그곳에서 더 이상 작업하지 않습니다. 그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", + "974f8c65e8b5f492": "{label}을(를) 잊을까요? 여기의 에이전트는 그곳에서 더 이상 작업하지 않으며, {label}이(가) 응답하면 그곳의 세션도 종료됩니다.", + "6cf9e3083b15614f": "{label}이(가) 응답하지 않았습니다", + "34ccbdf619b83be3": "그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", "81c9796bf61b306a": "링크를 삭제할 수 없습니다", "130e51beb6cf5aad": "환경 연결", "122c3e355699e69d": "그러면 이곳의 에이전트가 그곳에서 스레드를 시작하고, 메시지를 보내고, 기다릴 수 있습니다. 해당 환경의 공유 및 액세스에서 승인된 클라이언트에 표시되며 그곳에서 취소할 수 있습니다.", @@ -9113,7 +9179,6 @@ "0b4779a1825c85bc": "사이드바와 스레드 목록에 표시되는 이 프로젝트 그룹의 공유 이름입니다.", "f68cbda4df83d739": "프로젝트 이름 기본값으로 재설정", "56e37b85027e8431": "프로젝트 아이콘", - "e88c9d8769544731": "자동", "c99736317da5b1fa": "프로젝트 아이콘 기본값으로 재설정", "6afaa3e3739dc570": "프로젝트 아이콘 선택", "51651ce45d481a20": "프로젝트 아이콘 파일 선택", @@ -10082,7 +10147,6 @@ "a0eb0e4f76608833": "연결된 풀 리퀘스트를 먼저 엽니다. 없으면 3개 이상의 파일 또는 50줄 이상이 편집되었을 때 변경 사항을 엽니다.", "16bdc70b858c223f": "패널 미리 열기 기본값으로 재설정", "3e99c5c14f4939c8": "유휴 스레드 압축 기본값으로 재설정", - "d52b3d6bf9f2a013": "혼합", "cd72fe451ba0d6aa": "새 프로젝트", "394c3bd0a1782c8e": "프로젝트 추가 탐색기가 열릴 때 \"~/\"를 사용하려면 비워 두세요.", "f9b912a818bd869d": "프로젝트 추가 기본 디렉터리 기본값으로 재설정", @@ -10980,7 +11044,6 @@ "4a237f41ce592b7f": "직접 삭제할 때까지 이 프로젝트의 워크트리를 유지합니다.", "00b8ffd8ea6e6a93": "이 프로젝트에 이 규칙을 사용합니다.", "72c279824d15a999": "각 머신의 워크트리 정리 설정을 사용합니다.", - "90a258fff61fd77e": "끔", "b5702d0b64866b08": "사용자 지정", "c009c901f3eefe78": "삭제된 스레드의 워크트리 삭제", "431c7cd6d50102b7": "활성 또는 보관된 스레드가 삭제되면 사용하지 않는 워크트리를 제거합니다. 로컬 변경 사항이 있는 워크트리는 유지됩니다.", @@ -11672,7 +11735,6 @@ "4c70e3e7b3e6c493": "시크릿", "79b768229c9ef672": "유지 관리", "54b188d65247e42f": "실험 기능", - "f41ea186c275b56e": "정보", "af4b7734da1d5ce7": "음성", "4ec62c39ca3192bf": "소스 제어 및 이슈", "f2bf529f85e05494": "공유 및 액세스", @@ -11727,6 +11789,7 @@ "d443390c4d2dcfd4": "접근성 a11y 화면 낭독기 nvda jaws voiceover orca 내레이터 창 제목 탭 제목 alt tab 작업 표시줄 스레드 상태 순서 작업 중 승인", "6826fa9579c22035": "베타 공유 게스트 초대 링크 팀원 지켜보기 T3 Connect 터널", "f10c06cba0cdf7fe": "베타 다른 머신 연결 vps 피어 에이전트 원격 작업 위임", + "bc0b409d89ce086e": "베타 워크플로 workflow 지속 실행 자동화 단계 일정 webhook 폴더", "4a21cf825a2045b0": "베타 탭 자동 완성 다음 메시지 예측 Claude Codex 고스트 텍스트", "fea2dc36585c4a20": "Simlock 기기 호스트(알파)", "9d834d178130180e": "베타 알파 simlock callstack 시뮬레이터 에뮬레이터 iOS Android 풀 임대 게이트웨이", @@ -11798,6 +11861,7 @@ "901a823214edc8c4": "원격 분석 분석 사용 데이터 추적 법적 옵트아웃", "82136480255a5106": "OTel OTLP 원격 분석 내보내기 엔드포인트 로그 추적 메트릭 Grafana", "659d081051faf7ff": "로그 추적 프로세스 리소스 기록 실패 스팬 cpu 메모리", + "5eaeacfa9f82051a": "보고 버그 문제 t3 팀 보내기 피드백 에이전트 도구 자동 내가 요청할 때", "f537f91e1ee41d47": "키보드 단축키 핫키 명령 바인딩 json", "1ba01e7ceed64b95": "창 캡처 스크린샷", "279b1cceb779ff38": "앱 텍스트 포함", @@ -12267,7 +12331,6 @@ "0bd41ff995d36a66": "캐시 읽기", "3f0dfe0cb15a3272": "캐시 쓰기", "1c9d860be42b1c02": "출력", - "78344b60f407928e": "기타", "684e516076de81fe": "표준", "3bbcc1b826fef537": "빠름", "66796576034c18ea": "초고속", @@ -12283,6 +12346,255 @@ "2cddd6095abc734a": "7일", "53493056306708cf": "30일", "c719359d18d37ad3": "90일", + "0bd950151ddc6407": "저장하지 않고 나갈까요? 이 파일의 변경 사항이 사라집니다.", + "c0ba3f6756b09f30": "저장되지 않은 변경 사항", + "6914e22d357f0ad6": "저장되어 실행 중", + "aff389354a031d6f": "디스크의 파일을 불러올 수 없습니다. 마지막으로 불러온 버전이 계속 실행됩니다.", + "858effde748ab563": "저장했지만 아직 실행되지 않습니다.", + "ddb37138df660942": "저장되지 않았습니다. 서버에서 변경된 것은 없습니다.", + "6ef4db489e40e39e": "저장할 수 없습니다", + "c89624a2e9af1793": "{name}이(가) 연결되어 있지 않습니다", + "b5a352a43adb4c17": "다시 연결되면 워크플로가 다시 표시됩니다. 다른 환경을 선택하면 그 환경의 실행을 볼 수 있습니다.", + "3dcedb736d20aae5": "워크플로 파일을 읽을 수 없습니다", + "b09f4df8d76ae8ea": "{file}을(를) 삭제할까요? 이 파일에 정의된 워크플로는 더 이상 시작할 수 없습니다.", + "b4535f5a03689d27": "{name}이(가) 연결되어 있지 않습니다. 여기에 작성한 내용은 유지되며, 다시 연결되면 저장할 수 있습니다.", + "b54c78d85fd942ea": "삭제했지만 실행 중인 내용에 아직 반영되지 않았습니다.", + "407c228d7da0b7df": "삭제되지 않았습니다. 서버에서 변경된 것은 없습니다.", + "1a6aa10f3cc14fff": "이 파일들은 서로 맞지 않습니다. 이전에 실행되던 것이 계속 실행됩니다.", + "259312516a1dbe6f": "파일 이름", + "2f48ab2aa0586853": "정의된 워크플로 없음", + "ba5adfa37b55b8c5": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "번째 줄:" + ], + "d94eb9ab3201b641": "삭제", + "84c900d1ae72adc6": "저장", + "5912d817be03247a": "편집하는 동안 디스크의 파일이 변경되었습니다. 저장하면 해당 변경 사항을 덮어씁니다.", + "0b1e6f5608826387": "파일을 불러오고 내 변경 사항 버리기", + "f47b4c06aeb77c1c": "워크플로 파일을 불러오는 중…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "의 모든 파일이 워크플로를 정의합니다. 파일을 변경하면 다시 시작하지 않아도 반영됩니다." + ], + "0c165251a06f10f1": "새 파일", + "8e97cf734b4463e7": "만들기", + "2ec0d5108fd6cebe": "아직 워크플로가 없습니다. 여기에서 첫 파일을 만들거나 에이전트에게 해당 폴더에 작성해 달라고 요청하세요.", + "5601350626e8cfe9": "불러올 수 없음", + "21d778a1b9a0c234": "실행 옆에 열린 항목", + "62dc4d3a19ff7ca0": "탭 닫기", + "1e25265f2758fce3": "전체 스레드로 열기", + "672a3dae06b39402": "전용 페이지에서 열기", + "7755500a4cde5066": "창 닫기", + "b8dcbc93a2ca1861": "이 실행에 더 이상 포함되지 않습니다.", + "115c69de3202f664": "열기", + "644eafa9048b62df": "{count, plural, =1 {1번째 시도} =2 {2번째 시도} =3 {3번째 시도} other {{count}번째 시도}}", + "e39f89c909df4db0": "실행을 재개할 수 없습니다", + "865f034346b82f47": "{title}을(를) 취소할까요? 에이전트가 중지되며 이 실행은 재개할 수 없습니다.", + "6bc75632fd9c9136": "실행을 취소할 수 없습니다", + "64e50329dcfdd5b0": "완료", + "350162e7cc1ebea4": "중지됨", + "0875cf506f4c6810": "건너뜀", + "3cc43f1dbf3f8e0c": "취소됨", + "ded70e75de6404ba": "실행 목록으로 돌아가기", + "2f4ed7dbd22be30d": "실행 취소", + "614e5ad58a795fb5": "중지", + "04b050b0329f0ac8": "{duration} 소요", + "aff78e1774818ff4": "현재까지 {duration}", + "38eddd466439afc9": "이 실행이 다룬 항목", + "156ec271d49ddd70": "진행 내역", + "34f59bbbead0b97f": "{names} 외 {count}개", + "ac1556f6ce89a5ea": "{count}개 병렬", + "e197c4963bacc746": "{count}개 실행 중", + "f5319ed9e18c0df1": "사용자에게 질문", + "882a25e9084ae1b2": "일시 중지됨", + "9a03d8a9afc60387": "지금까지의 단계", + "2f2ae791afe01674": "승인을 기다리는 중", + "24f8060c4ccdf928": "시작하는 중", + "30a5be40eb956663": "작업 중", + "dd7a1e58c2553933": "{duration} 후 깨어남", + "95cc952724dd7310": "곧 깨어남", + "3cc34921c0128593": "실행 중", + "e777db2880f53a46": "응답 없음", + "dc90739d391a5e67": "내 답변: {choice}", + "389f2563b5b763fd": "빠른 단계", + "a41c8d758121ad81": "슬립", + "9db248b770096984": "대기", + "c76124517af28686": "{duration}째 실행 중", + "89102905bf09b0e8": "실시간 보기", + "bdf338cdff4118f0": "대화 기록", + "811e7e992f9ff820": "워크플로 버전이 다시 등록될 때까지 계속할 수 없음", + "4d4cdf035e98dd57": "사용자가 재개하기를 기다리는 중", + "eb5b21dd224a5941": "{duration} 후 자동으로 다시 시도", + "6ab3dfa749fde477": "곧 자동으로 다시 시도", + "44b6463aa70aa14c": "일시 중지된 이유", + "cf25e7169ab0eb7a": "{step}에서 일시 중지됨", + "56c48c1f220f2754": "질문에 답변할 수 없습니다", + "a3c43735e1a81498": "{title}의 이유", + "bfad234f016cfa3f": "이유를 한 문장으로 적어 주세요. 어떤 답변을 고르든 함께 전달됩니다.", + "004c41aff9c97873": "실행", + "4dc0c244a2419f6c": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "의 일부" + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "시작" + ], + "8bffb377e2a6a7de": "해당 버전이 더 이상 등록되어 있지 않음", + "f92d9132f7b85d1a": "단계를 불러오는 중…", + "6ebc59f64c761a49": "아직 아무것도 없습니다.", + "a759dccd157d7dae": [ + "내 답변: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "내 답변: ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "실행 열기", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "의 스레드" + ], + "3d9761e81798fcd8": "재개", + "8cebd63fc4c967d5": "실패한 단계만 다시 실행되며, 그 전에 완료된 내용은 유지됩니다.", + "bc1e0a2a0f1e9552": "확인 필요", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "질문", + " ", + "· 실행이 답변을 기다리는 중" + ], + "02dfe6c63fd0b8a1": "이유 추가", + "19abd94828a3bdbc": "먼저 에이전트에게 묻기", + "a18721fa8f328361": "확인 필요", + "bbf24e7920c1e86b": "실행 중", + "8d6e18d2ad832db6": "전체", + "f25af5332ffc3734": "확인이 필요한 항목이 없습니다.", + "c3f0119b8d6231f8": "실행 중인 항목이 없습니다.", + "33028dfc1229eaa6": "아직 실행이 없습니다.", + "5459bf696a187c26": "워크플로 실행을 불러올 수 없습니다", + "d57c35d43b0f163a": "이 실행은 여기에 없습니다", + "b9aae2f7cdb1a379": "아직 워크플로 실행이 없습니다", + "8f15f66e545af7c0": "표시할 실행", + "b6409289e0c9a4dd": "워크플로", + "035cb02ca1ae4952": "워크플로 {count}개 전체", + "46d614fa7b4bf1e5": "워크플로 실행", + "1c635faa2fb45b8b": "아직 실행된 적이 없습니다.", + "156ff7b625287a1e": "건너뛴 항목 숨기기", + "69b985b97ab45e6b": "건너뛴 항목 {count}개 표시", + "2400254d362de84d": "워크플로 실행을 불러오는 중…", + "145e1f7503ba3b2c": [ + "이 환경에는 해당 링크의 실행이 없습니다.", + " ", + { + "t": "button", + "i": 1, + "c": "실행 목록으로 돌아가기" + } + ], + "783e616cb0476c17": [ + "워크플로는 에이전트, 코드, 일정, 사용자에게 묻는 질문을 다시 시작해도 유지되는 하나의 실행으로 묶습니다.", + " ", + { + "t": "button", + "i": 1, + "c": "정의" + }, + "에서 직접 작성하거나 에이전트에게 요청하세요.", + " ", + { + "t": "a", + "i": 2, + "c": "가이드 읽기" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "워크플로 파일에 문제가 있습니다." + }, + " ", + "마지막으로 불러온 버전이 계속 실행됩니다." + ], + "ed8ce6ebc73dc12d": "파일 열기", + "5d8d278ff828102d": "모든 워크플로", + "39459da07479f482": "에이전트", + "7741243632056b81": "{step} · 기록", + "c512071143a5ba32": "이 스레드는 더 이상 존재하지 않습니다.", + "ed169d23683fb6ac": "스레드를 불러오는 중…", + "290e0ab40b87dc17": "워크플로 탐색 경로", + "683dd9831e54edc0": "환경", + "34ad53646f06ed80": "워크플로가 꺼져 있습니다", + "8f6589c9e0ac5d4e": "연결된 환경 없음", + "744127f8dfad7d22": "환경을 연결하면 해당 환경의 워크플로 실행을 볼 수 있습니다.", + "036182ec7e2ee4d4": "실행 옆", + "2d6107cb78382d08": "워크플로", + "16f7df687349b399": "정의", + "f0a212aadfe1257b": "편집기를 불러오는 중…", + "20f194e003885e95": [ + "이 서버의", + " ", + { + "t": "Link", + "i": 1, + "c": "설정 → Labs" + }, + "에서 켜세요." + ], "8367779e149f723b": "{operation} 중 기본 환경 요청에 실패했습니다(HTTP {status}).", "c5cd027743a2b5a6": "잘못된 페어링 토큰입니다. 토큰을 확인하고 다시 시도하세요.", "0e4b49c8203aae81": "부트스트랩 후 인증된 세션을 기다리다 시간이 초과되었습니다.", @@ -12401,6 +12713,8 @@ "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", - "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", - "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동" + "99d51127f573296b": "다른 계정", + "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", + "99963c0142e17f00": "새 {tracker} 계정용입니다.", + "6d8e4ebc889bace9": "계정 추가" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 729564df06fe9..ebcd6d8586978 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Instale o {fj} 0.6 ou posterior em {fjUrl} e execute {fjLogin}, ou instale o {tea} 0.16 ou posterior em {teaUrl} e execute {teaLogin} para cada servidor Forgejo ou Gitea.", "d026a85e2e50e675": "Instale a CLI do GitCafe com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", "22d3c0c48a34b5b3": "Instale a CLI do TanStack Source com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", + "756c80ad262ef315": "Aguardando na thread original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "Não enviada", + "b54ddec9084fa955": "Fechado sem enviar", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Funcionalidade ausente", + "055560f307e15e30": "Documentação incorreta", + "78344b60f407928e": "Outros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Sobre", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "O que aconteceu", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Você", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumo de {turns, plural, one {{turns} turno recente} other {{turns} turnos recentes}}, {textTurns, plural, =0 {sem texto das mensagens} one {com o texto das mensagens do último turno} other {com o texto das mensagens dos últimos {textTurns} turnos}}{truncated, select, yes {, encurtado para caber} other {}}", + "afac52a5cc2dc801": "Não foi possível enviar sua resposta. Tente novamente.", "79d776428f4d0650": "Não foi possível carregar o arquivo. Reconecte e tente novamente.", "3ea34cbb1ca5ba9b": "Pré-visualização cancelada.", "7c0af279ecb3da3a": "As pré-visualizações de arquivos por streaming não estão disponíveis neste runtime.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} ativado", "77cc5f738cb7d459": "{label} desativado", - "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", "aba3bb73ce212f0c": "Usar {names} requer {providerName} {version} ou mais recente, mas o cask claude-code do Homebrew só tem {latestVersion}. Mude para o cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", "d887bea446534de5": "Nenhum projeto neste ambiente consegue ler {host}/{repository}.", "4e466d60e2f7736b": "Cole a URL completa do pull request; esta thread não tem repositório para resolver o número.", "302625058bacbe38": "Cole uma URL completa; o host deste projeto não tem uma URL de {changeRequest} conhecida.", @@ -376,6 +396,31 @@ "476ca970255eaea4": "Vincule este ambiente ao T3 Connect para ter uma URL pública.", "6b80f5b38a8f9950": "Só este computador pode acessar este endereço. Vincule o T3 Connect para ter uma URL pública.", "c5a7b1d3891dd0b8": "Funciona onde o endereço deste ambiente for acessível, por exemplo pelo Tailscale ou pelo seu próprio proxy. Vincule o T3 Connect para ter uma URL pública.", + "3669395daf36fd33": "Não está mais registrado neste servidor", + "fe513cf316e796e3": "Executa como parte de outros workflows", + "ccf00b97925efab3": "Iniciado manualmente", + "421e585eb092b07b": "Inicia com {triggers}", + "7bd7c58592671384": "Precisam de você", + "834ca879c14c167b": "Trabalhando", + "582d6df7dfab86fb": "Pausada", + "ea6583ce92507ee3": "Dormindo", + "7ea8cb8af281ce93": "Aguardando", + "1347868f2523140e": "Concluída", + "57d76c4614054271": "Parada", + "5c7344bd51d0b966": "Pulada", + "b2074e9bd23049a6": "Cancelada", + "5bb7401807ee2fb5": "Pergunta: {question} e mais {more}", + "9e4286183d5f9e34": "Pergunta: {question}", + "474c18d001bd6717": "Uma etapa falhou", + "d3890f4eb1508781": "Executando as próprias etapas", + "3e7ced10c9482af0": "{step} está trabalhando", + "237e1bcb1cf1bdec": "Dormindo em {step}", + "3f7b17ac5a20c8d2": "Executa {run}", + "0306f5f324b8aaa5": "{count} execuções em andamento", + "e8fd779b84a202a2": "Aguardando", + "b6d55657e1a027b8": "Aguardando {step}", + "e942562a42aede34": "Concluída", + "26b2b9727fe11289": "Encerrada antes do fim", "1bb995dcec481554": "Aprove este dispositivo em {host}. Ele mostra o código {verificationCode}.", "8696a33219944832": "Não foi possível criar a prova de autorização do websocket.", "5678f133a8631f7d": "Seu login na nuvem mudou. Entre novamente para autorizar o ambiente.", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host} não conseguiu estabelecer uma conexão WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualização da configuração do servidor que este cliente não conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -1720,6 +1768,8 @@ "2e995206e087c3fc": "Tente responder depois que a conexão ou a resposta pendente for resolvida.", "604ec3067171a0d7": "Conversa", "d6182a057ea12624": "Thread principal", + "f2d8537c33cc55a5": "Etapa da execução do workflow", + "ba8337dca3232880": "Abrir execução", "30fa4a764d11ae42": "Não foi possível baixar {name}", "4952f87dc98191a7": "O anexo não está disponível.", "2fd6d178493fb407": "Falha ao interromper o turno atual.", @@ -1805,6 +1855,7 @@ "04fd71efaa2c3b92": "Abrir pull requests", "57e875b79b98ab82": "Abrir issues", "f1db0a234c777a1d": "Usar o T3 Code em outro app (MCP)", + "6050f22f63e2bcb5": "Abrir workflows", "a0cc19e60dd99851": "Abrir uso", "46694969044eee98": "Focar a próxima área do workspace", "0a1011328ba42eef": "Focar a área anterior do workspace", @@ -2070,7 +2121,7 @@ "cd80122422577239": "Publicar repositório", "c85db9ac99efa605": "Push e criar {term, select, mr {MR} cr {solicitação de alteração} other {PR}}", "dbccf81ad4a03f48": "Sincronizar ref", - "4350ab8128b18105": "Pull", + "4350ab8128b18105": "Fazer pull", "dca2ca8303bfc14e": "Fazer commit e push na ref padrão?", "e196fda632e279d0": "Esta ação vai fazer commit e push das alterações em \"{branch}\". Você pode continuar nesta ref ou criar uma ref de feature e executar a mesma ação nela.", "87e714255e8be7f2": "Fazer push na ref padrão?", @@ -2496,8 +2547,7 @@ "2d1c111e1b4ae0b0": "Excluir a thread \"{title}\"?", "c568ab8dad798ec5": "Isso apaga permanentemente o histórico de conversa desta thread.", "0fd1c746a0e38003": "Falha ao excluir a thread", - "0ecde875b0dd2f93": "Filtrar threads por projeto: {projects}", - "1ef65b647231ff0b": "Filtrar threads por projeto", + "1c8fc3c4a42949ab": "Projetos: {projects}", "165511761be2855c": "Pesquisar projetos", "a46a6467883575a4": "Pesquisar projetos...", "fdc0e086438a3045": "Configurações do projeto {project}", @@ -2559,10 +2609,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Está em outra máquina, então o agente desta máquina não consegue lê-lo. Remova-o ou volte para enviar.", "5bbac0e5afeec779": "Thread atual", "33c7e68fca089036": "Thread, {title}", - "b4b98a0287c282e2": "Está em outra máquina, então o agente desta máquina não consegue lê-lo. Remova-o ou volte para enviar.", - "c6196d99000642b4": "Abrir thread", "34cc63390ad793cc": "Escolha uma thread", "8f12309ead62e38a": "Pesquisar threads ou projetos...", "2f664754d005d9a7": "Nenhuma thread ativa encontrada.", @@ -2572,6 +2621,7 @@ "a3178769f8308cbc": "A thread falhou", "89b5e8f3887812da": "Pedido de convidado", "62e626804919b294": "Resposta necessária", + "c6196d99000642b4": "Abrir thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Você:", "a1fbf2422c588292": "Agente:", @@ -2595,8 +2645,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Processo do terminal em execução", "fc2c9a91f498ad6b": "{count, plural, one {{count} processo do terminal em execução. Abrir terminal} other {{count} processos do terminal em execução. Abrir terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "pilha", "6831e9a46cbd8939": "cadeia", "9aa9e74a3b7eee91": "Adicionar ao chat", @@ -3033,8 +3081,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "A entrada de voz não tem um rascunho onde gravar.", "62450481c00d2ef3": "O ambiente do rascunho não está disponível para limpar a transcrição.", - "c64cb58d9cecbcd2": "Falha ao limpar a transcrição", "0674544195fcdc39": "A transcrição original foi adicionada.", + "c64cb58d9cecbcd2": "Falha ao limpar a transcrição", "296496693cdac0db": "O comando t3 não está disponível.", "efbcef7bc9bbda01": "Falha ao carregar o estado do comando t3.", "1bf6910332426e62": "O acesso à rede do desktop não está disponível.", @@ -3277,6 +3325,7 @@ "4d493d0bda4d403d": "Anexe novamente o arquivo interrompido ou remova-o", "c9cad1d84d5f1a32": "Anexe novamente os arquivos interrompidos ou remova-os", "536a820f2ff726da": "Selecione pelo menos um modelo.", + "48d6389202ad6754": "Enviando quando estiver pronto", "fbafbe78b5e37966": "Retomar thread", "bcd7eb979dd38dae": "Abrir o editor de mensagens para compactar e enviar", "95ee62a0d6968b89": "Enviar mensagem", @@ -3453,6 +3502,9 @@ "e778e4f446fdf873": "Sua próxima mensagem inicia uma nova sessão", "0e2f2da4f2d94785": "O agente não verá as mensagens anteriores desta thread.", "e1189d2e582b008d": "Manter a sessão atual", + "2bb448d605877a22": "Edite ou pressione Esc para cancelar", + "1a1f128d70c62304": "{count, plural, one {Enviando assim que a imagem estiver pronta} other {Enviando assim que {count} imagens estiverem prontas}}", + "5af3ab719a9725fb": "Enviando mensagem", "461c9f865f2e9b92": "{option} ativado", "f2aa17b5c620f2a4": "{option} desativado", "f59314a884aae1ff": "Padrão", @@ -3576,6 +3628,14 @@ "c53bc5a4b0314342": "Próxima mídia", "2950b1424a3cddf5": "Reconecte-se a este ambiente e abra a mídia novamente.", "ef638bf1479a5461": "O ambiente retornou uma URL de mídia inválida.", + "3ccfbf7e86868c35": "Feedback para a equipe do T3", + "4e0710d19dfc2e7e": "Enviar este relatório para a equipe do T3?", + "87d0ae0723ba75d1": "Isto é tudo o que sai da sua máquina. Nada é enviado até você clicar em Enviar.", + "bf19826f81484328": "Incluir a conversa", + "260c6b45f52d2f27": "Adiciona o texto das suas mensagens e das respostas do agente {textTurns, plural, one {no último turno} other {nos últimos {textTurns} turnos}}.", + "ddb7e6f8ce99e657": "Somente quem pode executar agentes nesta máquina pode enviar ou recusar o relatório.", + "03c1eb603c112f47": "Não enviar", + "653405e4ed498d9f": "Enviar", "262955d6eb632f9b": "A API da área de transferência não está disponível ao copiar o link de convidado.", "f1a4f2b04cdbb4ef": "Falha ao copiar o link de convidado para a área de transferência.", "cf3490a604e44d31": "Não foi possível criar um link de convidado.", @@ -3596,7 +3656,6 @@ "abd89e9eefedf11b": "Concluído", "18d166056c1ab6ff": "Parar de compartilhar", "7a2d510eac9e4587": "Link de convidado expirado", - "653405e4ed498d9f": "Enviar", "21888e302219891d": "Pré-visualização expandida de {title}", "419719298a7acaea": "Diminuir zoom", "ed8d5db95359cff4": "Redefinir zoom", @@ -3692,7 +3751,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Ações do bloco de código", "ebf3a2b1e314aa5f": "Executar no terminal", - "fe219642547fa0bf": "Executar no terminal", "122a8512abc51180": "Detalhes", "58c38c65c2783c5d": "Caminho completo", "f37e7d36b51c5b28": "Copiar caminho relativo", @@ -3704,10 +3762,6 @@ "4967584e8d0fb1c2": "Pré-visualizar mídia", "67589dd912eacb7c": "Abrir no navegador integrado", "a3c98d4c4b24cecb": "Opções do arquivo {label}", - "b4fe8a076e9fd2f8": "Equação em destaque", - "085d1407e8c92cce": "Equação em linha", - "a2ef393fa7b48ae8": "Rolar a equação em destaque", - "e94685ea5642e088": "Rolar a equação em linha", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabela", @@ -3984,9 +4038,11 @@ "973e99fa86d7f531": "Mensagem {position} de {total} na fila, não enviada", "0f6087c4f53c7f17": "Iniciar um turno com esta mensagem ({shortcut})", "adab89933af02669": "Pular a compactação e enviar esta mensagem ({shortcut})", + "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", "3de4016452e8d2bd": "Enviar para o turno atual ({shortcut})", "259cc9568148e8ad": "Iniciar um turno com esta mensagem", "bb7fddb812d5d29e": "Pular a compactação e enviar esta mensagem", + "425ab15036aec8a4": "Mover este comando para o início da fila", "a5fe1ee609b29a9f": "Enviar para o turno atual", "2b7fd345e4f4fd6e": "Cancelar a edição da mensagem na fila", "47f1726bf106d2c8": "Editar mensagem na fila", @@ -5598,7 +5654,6 @@ }, ". Verifique o caminho do link ou localize o arquivo em Arquivos." ], - "b9b6bbd1e1ea189f": "Arquivo completo", "d715e9494fdbaaf6": "Não foi possível carregar a fonte.", "ff17c777a72b4408": "As pré-visualizações de fontes são limitadas a 10 MB.", "6bd41ad699e22f10": "A fonte não está disponível.", @@ -5608,6 +5663,7 @@ "a9abaaa4220eae21": "{error} Salve-a para abrir em outro app.", "c508c9000d9656f8": "Pré-visualização da fonte", "1c416d621d250be8": "Um pequeno jabuti xereta viu dez cegonhas felizes.", + "d7d08260f16b7828": "O arquivo ainda está carregando. Tente novamente em instantes.", "76ebb03de52c92d6": "O visualizador de texto parou.", "f48162e8e8c12af7": "Não foi possível carregar o visualizador de texto. Feche o arquivo e tente novamente.", "bc4c5b13d38a5da7": "Pré-visualização fechada.", @@ -5615,8 +5671,6 @@ "9450d1827ef336a1": "Outra cópia está em andamento.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} linha} other {{formatted} linhas}}", "13b14784f8707ddd": "0 bytes", - "f6e9581cba3467fa": "Indexando…", - "2d1f293ac12463fc": "Carregando o restante do arquivo…", "b75105bef8f564a4": "Mostrando as primeiras 1.024 colunas. O código-fonte e o arquivo salvo mantêm todas as colunas.", "2a6e1b1f209c3888": "Este arquivo está vazio.", "192fc79eb3b5b2cb": "Este diagrama contém URLs de recursos, markup, metadados de nós ou configuração personalizada. Mostre o código Mermaid para inspecioná-lo com segurança.", @@ -5803,7 +5857,6 @@ "0061fff77e36bd4f": "Não foi possível acessar o servidor.", "04dfdd46e3dd4a2e": "Algo deu errado. Tente novamente.", "084bb2d8127a508d": "Enviada", - "e7c59185f8ab3987": "Não enviada", "77c01a15bd36d17c": "Este link expirou ou não é válido", "e0e736810f3cbef2": "Peça um novo link ao proprietário. Cada link funciona em um navegador.", "c3c53aa46f7330e5": "Este link expirou", @@ -8827,6 +8880,12 @@ "d3866ead082d14e5": "Adicionar atalho de teclado", "d4345c90894a3220": "Abrir keybindings.json", "e56a8d51219efaa0": "Nenhum atalho de teclado corresponde à sua pesquisa.", + "90a258fff61fd77e": "Desativado", + "4060244a7079a0d2": "Quando eu pedir", + "e88c9d8769544731": "Automático", + "f29d1dade4dde8aa": "Os agentes não enviam feedback para a equipe do T3.", + "93c4c53562d30a98": "Quando você pede, os agentes mostram um breve relatório sobre o T3 Code e o enviam para a equipe do T3 se você aprovar.", + "cd9ee803e8727017": "Os agentes também relatam por conta própria os problemas que encontram no T3 Code, como uma ferramenta do T3 que falhou.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Agrupa as threads da barra lateral em pastas de projeto. As threads fixadas ficam no topo, e Adiadas e Concluídas ficam abaixo das pastas.", "e4e91d155cb6a9b4": "Barra lateral sem graça (agrupar por projeto)", @@ -8835,11 +8894,16 @@ "9ae293971d93c819": "Compartilhe uma thread com um convidado que a acompanha ao vivo no navegador e envia mensagens que você aprova. Entre no T3 Connect para usar links de convidado.", "0aa5406ac4d7f7c7": "Links de convidado", "f0e853acd2006d53": "Ambientes vinculados", + "ef10c2dff987f3ea": "Execute workflows de várias etapas a partir de arquivos na pasta workflows da pasta T3 deste servidor. Abra-os pela paleta de comandos. Enquanto estiver desativado, nada dessa pasta é executado; as execuções aguardam até que seja ativado novamente.", + "2dadb2359422121c": "Workflows", "13e86eb5d8287a71": "Mostra uma próxima mensagem prevista no editor vazio após um turno do Claude ou do Codex. Tab a usa. Cada uma é uma requisição extra em cache no seu plano. Requer Codex 0.165+. As threads do Claude são atualizadas ao reiniciar.", "d4b2a2ec812aafb0": "Sugerir próximo prompt", "298c7150a7621c80": "Hosts de dispositivos Simlock", "67937aa49179285e": "No Mac, clona novos worktrees a partir de um checkout em cache na pasta T3 home em vez de gravar cada arquivo. Usa o checkout normal do Git quando não consegue. Desativar exclui o cache.", "f9904f78d3003f58": "Checkout rápido de worktree", + "9c2f647882522302": "As máquinas selecionadas usam modos diferentes de feedback dos agentes.", + "31bbf7bf8c0a5279": "Feedback dos agentes", + "d52b3d6bf9f2a013": "Misto", "ec7623deed751c05": [ "Compartilhe uma thread com um convidado que a acompanha ao vivo no navegador e envia mensagens que você aprova. Requer T3 Connect: entre e vincule esta máquina em", " ", @@ -8924,7 +8988,9 @@ "fb71127e5746a6bc": "Em Compartilhamento e acesso de lá, ou t3 pair", "1e3fee7084791773": "Vincular também {target} de volta a {source}", "ea34a190b0bd804c": "Os agentes de {target} poderão trabalhar também em {source}.", - "ad5ed0ce61b966eb": "Esquecer {label}? Os agentes daqui deixam de funcionar lá. Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", + "974f8c65e8b5f492": "Esquecer {label}? Os agentes daqui param de trabalhar lá, e a sessão deles em {label} também termina se ele responder.", + "6cf9e3083b15614f": "{label} não respondeu", + "34ccbdf619b83be3": "Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", "81c9796bf61b306a": "Não foi possível esquecer o vínculo", "130e51beb6cf5aad": "Vincular um ambiente", "122c3e355699e69d": "Os agentes daqui poderão então iniciar threads lá, enviar mensagens e aguardá-las. Ele aparece em Clientes autorizados em Compartilhamento e acesso daquele ambiente, onde pode ser revogado.", @@ -9154,7 +9220,6 @@ "0b4779a1825c85bc": "O nome compartilhado deste grupo de projetos na barra lateral e nas listas de threads.", "f68cbda4df83d739": "Redefinir o nome do projeto para o padrão", "56e37b85027e8431": "Ícone do projeto", - "e88c9d8769544731": "Automático", "c99736317da5b1fa": "Redefinir o ícone do projeto para o padrão", "6afaa3e3739dc570": "Escolha um ícone para o projeto", "51651ce45d481a20": "Escolha um arquivo de ícone para o projeto", @@ -10127,7 +10192,6 @@ "a0eb0e4f76608833": "Abre primeiro os pull requests vinculados. Caso contrário, abre Alterações para edições em pelo menos 3 arquivos ou 50 linhas.", "16bdc70b858c223f": "Redefinir os painéis proativos para o padrão", "3e99c5c14f4939c8": "Redefinir a compactação de threads ociosas para o padrão", - "d52b3d6bf9f2a013": "Misto", "cd72fe451ba0d6aa": "Novos projetos", "394c3bd0a1782c8e": "Deixe vazio para usar \"~/\" quando o navegador de Adicionar projeto abrir.", "f9b912a818bd869d": "Redefinir o diretório base para adicionar projetos para o padrão", @@ -11029,7 +11093,6 @@ "4a237f41ce592b7f": "Mantém os worktrees deste projeto até você excluí-los manualmente.", "00b8ffd8ea6e6a93": "Usa estas regras neste projeto.", "72c279824d15a999": "Usa as configurações de limpeza de worktrees de cada máquina.", - "90a258fff61fd77e": "Desativado", "b5702d0b64866b08": "Personalizado", "c009c901f3eefe78": "Excluir worktrees de threads excluídas", "431c7cd6d50102b7": "Remove worktrees sem uso quando threads ativas ou arquivadas são excluídas. Worktrees com alterações locais são mantidos.", @@ -11725,7 +11788,6 @@ "4c70e3e7b3e6c493": "Segredos", "79b768229c9ef672": "Manutenção", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Sobre", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versões e issues", "f2bf529f85e05494": "Compartilhamento", @@ -11780,6 +11842,7 @@ "d443390c4d2dcfd4": "acessibilidade a11y leitor de tela nvda jaws voiceover orca narrador título da janela título da aba alt tab barra de tarefas status da thread ordem trabalhando aprovação", "6826fa9579c22035": "beta compartilhar convidado convite link colega acompanhar t3 connect túnel", "f10c06cba0cdf7fe": "beta vincular outra máquina vps par agentes trabalham lá delegar", + "bc0b409d89ce086e": "beta workflow execuções duráveis automação etapas agendamento webhook pasta", "4a21cf825a2045b0": "beta tab autocompletar prever próxima mensagem claude codex texto fantasma", "fea2dc36585c4a20": "Hosts de dispositivos Simlock (alfa)", "9d834d178130180e": "beta alpha simlock callstack simulador emulador ios android pool lease gateway", @@ -11851,6 +11914,7 @@ "901a823214edc8c4": "telemetria analytics dados de uso rastreamento legal desativar", "82136480255a5106": "OTel OTLP telemetria exportar endpoints logs traces métricas Grafana", "659d081051faf7ff": "logs traces processos histórico de recursos falhas spans cpu memória", + "5eaeacfa9f82051a": "relatório bug problema t3 equipe enviar feedback agentes ferramentas automático quando eu pedir", "f537f91e1ee41d47": "atalhos de teclado teclas de atalho comandos bindings json", "1ba01e7ceed64b95": "janela captura captura de tela", "279b1cceb779ff38": "Incluir texto do app", @@ -12320,7 +12384,6 @@ "0bd41ff995d36a66": "Leitura de cache", "3f0dfe0cb15a3272": "Gravação de cache", "1c9d860be42b1c02": "Saída", - "78344b60f407928e": "Outros", "684e516076de81fe": "Padrão", "3bbcc1b826fef537": "Rápido", "66796576034c18ea": "Ultrarrápido", @@ -12336,6 +12399,262 @@ "2cddd6095abc734a": "7 dias", "53493056306708cf": "30 dias", "c719359d18d37ad3": "90 dias", + "0bd950151ddc6407": "Sair sem salvar? Suas alterações neste arquivo serão perdidas.", + "c0ba3f6756b09f30": "Alterações não salvas", + "6914e22d357f0ad6": "Salvo e em execução", + "aff389354a031d6f": "O arquivo no disco não carrega. A última versão que carregou continua em execução.", + "858effde748ab563": "Salvo, mas ainda não está em execução.", + "ddb37138df660942": "Não salvo. Nada mudou no servidor.", + "6ef4db489e40e39e": "Não foi possível salvar", + "c89624a2e9af1793": "{name} não está conectado", + "b5a352a43adb4c17": "Os fluxos de trabalho dele voltam a aparecer quando ele se reconectar. Escolha outro ambiente para ver as execuções dele.", + "3dcedb736d20aae5": "Não foi possível ler os arquivos de workflow", + "b09f4df8d76ae8ea": "Excluir {file}? Os workflows que ele define não poderão mais ser iniciados.", + "b4535f5a03689d27": "{name} não está conectado. O que você escrever aqui fica guardado e pode ser salvo assim que ele voltar.", + "b54c78d85fd942ea": "Excluído, mas o que está em execução ainda não foi atualizado.", + "407c228d7da0b7df": "Não excluído. Nada mudou no servidor.", + "1a6aa10f3cc14fff": "Estes arquivos não são compatíveis entre si. O que rodava antes continua em execução.", + "259312516a1dbe6f": "Nome do arquivo", + "2f48ab2aa0586853": "Não define nenhum workflow", + "ba5adfa37b55b8c5": [ + "Linha ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Excluir", + "84c900d1ae72adc6": "Salvar", + "5912d817be03247a": "O arquivo mudou no disco enquanto você editava. Salvar substitui essa alteração.", + "0b1e6f5608826387": "Carregar o arquivo e descartar minhas alterações", + "f47b4c06aeb77c1c": "Carregando os arquivos de workflow…", + "4353bfd401d58f87": [ + "Cada arquivo em", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "define workflows. Uma alteração em qualquer um deles é aplicada sem reiniciar." + ], + "0c165251a06f10f1": "Novo arquivo", + "8e97cf734b4463e7": "Criar", + "2ec0d5108fd6cebe": "Nenhum workflow ainda. Crie o primeiro arquivo aqui ou peça a um agente para escrever um nessa pasta.", + "5601350626e8cfe9": "Não carrega", + "21d778a1b9a0c234": "Aberto ao lado da execução", + "62dc4d3a19ff7ca0": "Fechar aba", + "1e25265f2758fce3": "Abrir como thread completa", + "672a3dae06b39402": "Abrir na própria página", + "7755500a4cde5066": "Fechar o painel", + "b8dcbc93a2ca1861": "Esta execução não o lista mais.", + "115c69de3202f664": "Abrir", + "644eafa9048b62df": "{count, plural, =1 {1ª tentativa} =2 {2ª tentativa} =3 {3ª tentativa} other {{count}ª tentativa}}", + "e39f89c909df4db0": "Não foi possível retomar a execução", + "865f034346b82f47": "Cancelar {title}? Os agentes param e a execução não pode ser retomada.", + "6bc75632fd9c9136": "Não foi possível cancelar a execução", + "64e50329dcfdd5b0": "Concluída", + "350162e7cc1ebea4": "Parada", + "0875cf506f4c6810": "Pulada", + "3cc43f1dbf3f8e0c": "Cancelada", + "ded70e75de6404ba": "Voltar à lista de execuções", + "2f4ed7dbd22be30d": "Cancelar execução", + "614e5ad58a795fb5": "Parar", + "04b050b0329f0ac8": "levou {duration}", + "aff78e1774818ff4": "{duration} até agora", + "38eddd466439afc9": "O que a execução tocou", + "156ec271d49ddd70": "O que aconteceu", + "34f59bbbead0b97f": "{names} e mais {count}", + "ac1556f6ce89a5ea": "{count} em paralelo", + "e197c4963bacc746": "{count} em execução", + "f5319ed9e18c0df1": "Pergunta a você", + "882a25e9084ae1b2": "Pausada", + "9a03d8a9afc60387": "Etapas até agora", + "2f2ae791afe01674": "aguarda sua aprovação", + "24f8060c4ccdf928": "iniciando", + "30a5be40eb956663": "trabalhando", + "dd7a1e58c2553933": "acorda em {duration}", + "95cc952724dd7310": "prestes a acordar", + "3cc34921c0128593": "em execução", + "e777db2880f53a46": "ninguém respondeu", + "dc90739d391a5e67": "Você disse {choice}", + "389f2563b5b763fd": "Etapas rápidas", + "a41c8d758121ad81": "em espera", + "9db248b770096984": "aguardou", + "c76124517af28686": "em execução há {duration}", + "89102905bf09b0e8": "Assistir ao vivo", + "bdf338cdff4118f0": "Transcrição", + "811e7e992f9ff820": "não pode continuar até que a versão do workflow seja registrada novamente", + "4d4cdf035e98dd57": "aguarda você retomá-la", + "eb5b21dd224a5941": "tenta de novo sozinha em {duration}", + "6ab3dfa749fde477": "prestes a tentar de novo sozinha", + "44b6463aa70aa14c": "Por que pausou", + "cf25e7169ab0eb7a": "Pausada em {step}", + "56c48c1f220f2754": "Não foi possível responder à pergunta", + "a3c43735e1a81498": "Motivo para {title}", + "bfad234f016cfa3f": "O motivo, em uma frase. Ele acompanha a resposta que você escolher.", + "004c41aff9c97873": "Execuções", + "4dc0c244a2419f6c": [ + "Parte de ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "iniciada", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "sua versão não está mais registrada", + "f92d9132f7b85d1a": "Carregando etapas…", + "6ebc59f64c761a49": "Nada ainda.", + "a759dccd157d7dae": [ + "Você disse", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Você disse", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Abrir execução", + "c8eb9be36d4d51ad": [ + "Thread em ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Retomar", + "8cebd63fc4c967d5": "Só a etapa que falhou é executada de novo; o que terminou antes dela é mantido.", + "bc1e0a2a0f1e9552": "Precisam de você", + "a812f51e970740f1": [ + "perguntou", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· a execução aguarda você" + ], + "02dfe6c63fd0b8a1": "Adicionar um motivo", + "19abd94828a3bdbc": "Perguntar ao agente primeiro", + "a18721fa8f328361": "Precisam de você", + "bbf24e7920c1e86b": "Em execução", + "8d6e18d2ad832db6": "Todas", + "f25af5332ffc3734": "Nada aguarda você.", + "c3f0119b8d6231f8": "Nada em execução.", + "33028dfc1229eaa6": "Nenhuma execução ainda.", + "5459bf696a187c26": "Não foi possível carregar as execuções de workflow", + "d57c35d43b0f163a": "Esta execução não está aqui", + "b9aae2f7cdb1a379": "Nenhuma execução de workflow ainda", + "8f15f66e545af7c0": "Quais execuções", + "b6409289e0c9a4dd": "Workflow", + "035cb02ca1ae4952": "Todos os workflows ({count})", + "46d614fa7b4bf1e5": "Execuções de workflow", + "1c635faa2fb45b8b": "Ainda não foi executado.", + "156ff7b625287a1e": "Ocultar puladas", + "69b985b97ab45e6b": "Mostrar puladas ({count})", + "2400254d362de84d": "Carregando execuções de workflow…", + "145e1f7503ba3b2c": [ + "Este ambiente não tem nenhuma execução com esse link.", + " ", + { + "t": "button", + "i": 1, + "c": "Voltar às execuções" + } + ], + "783e616cb0476c17": [ + "Um workflow reúne agentes, código, agendamentos e perguntas para você em uma única execução que sobrevive a reinicializações. Escreva um em", + " ", + { + "t": "button", + "i": 1, + "c": "Definições" + }, + ", ou peça a um agente.", + " ", + { + "t": "a", + "i": 2, + "c": "Leia o guia" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "Um arquivo de workflow tem um problema." + }, + " ", + "A última versão que carregou continua em execução." + ], + "ed8ce6ebc73dc12d": "Abrir o arquivo", + "5d8d278ff828102d": "Todos os workflows", + "39459da07479f482": "Agente", + "7741243632056b81": "{step} · transcrição", + "c512071143a5ba32": "Esta thread não existe mais.", + "ed169d23683fb6ac": "Carregando a thread…", + "290e0ab40b87dc17": "Trilha de navegação de workflows", + "683dd9831e54edc0": "Ambiente", + "34ad53646f06ed80": "Os workflows estão desativados", + "8f6589c9e0ac5d4e": "Nenhum ambiente conectado", + "744127f8dfad7d22": "Conecte um ambiente para ver as execuções de workflow dele.", + "036182ec7e2ee4d4": "Ao lado da execução", + "2d6107cb78382d08": "Workflows", + "16f7df687349b399": "Definições", + "f0a212aadfe1257b": "Carregando o editor…", + "20f194e003885e95": [ + "Ative-os para este servidor em", + " ", + { + "t": "Link", + "i": 1, + "c": "Configurações → Labs" + }, + "." + ], "8367779e149f723b": "A requisição ao ambiente principal falhou durante {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Token de pareamento inválido. Verifique o token e tente novamente.", "0e4b49c8203aae81": "Tempo esgotado aguardando a sessão autenticada após a inicialização.", @@ -12457,6 +12776,8 @@ "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", - "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", - "425ab15036aec8a4": "Mover este comando para o início da fila" + "99d51127f573296b": "Outra conta", + "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", + "99963c0142e17f00": "Para a nova conta do {tracker}.", + "6d8e4ebc889bace9": "Adicionar conta" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 377797e9430a3..2043881742c8e 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Установите {fj} 0.6 или новее с {fjUrl} и выполните {fjLogin} либо установите {tea} 0.16 или новее с {teaUrl} и выполните {teaLogin} для каждого сервера Forgejo или Gitea.", "d026a85e2e50e675": "Установите GitCafe CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", "22d3c0c48a34b5b3": "Установите TanStack Source CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", + "756c80ad262ef315": "Ожидание в исходном треде", + "d8df14f9905f38eb": "Отправлено", + "e7c59185f8ab3987": "Не отправлено", + "b54ddec9084fa955": "Закрыто без отправки", + "fbaa7ab5da716e50": "Ошибка", + "01bac997ea55272e": "Непонятное поведение", + "0f53bc8f74dfe56a": "Не хватает возможности", + "055560f307e15e30": "Ошибка в документации", + "78344b60f407928e": "Другое", + "f653846a95cd6e8f": "Тип", + "f41ea186c275b56e": "О приложении", + "2f6e4f7cd364da73": "Ожидалось", + "9d11c93d4035de3e": "Произошло", + "c87d0595693704f9": "Что сделано вместо этого", + "d7a4ea6ce5af44e0": "{speaker} · {count} симв.", + "f5114fb9c40fd929": "Вы", + "cd03eb1b84271c02": "Агент", + "bfe1a60f3f9c60fb": "Ход {turn} · {what}", + "dfdaa6255a416140": "Обзор {turns, plural, one {{turns} последнего хода} other {{turns} последних ходов}}, {textTurns, plural, =0 {без текста сообщений} =1 {с текстом сообщений последнего хода} one {с текстом сообщений последнего {textTurns} хода} other {с текстом сообщений последних {textTurns} ходов}}{truncated, select, yes {, сокращено до допустимого размера} other {}}", + "afac52a5cc2dc801": "Не удалось отправить ваш ответ. Попробуйте ещё раз.", "79d776428f4d0650": "Не удалось загрузить файл. Переподключитесь и попробуйте ещё раз.", "3ea34cbb1ca5ba9b": "Предпросмотр отменён.", "7c0af279ecb3da3a": "Потоковый предпросмотр файлов недоступен в этой среде выполнения.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Обычная", "f42c2a36b3507308": "{label}: вкл.", "77cc5f738cb7d459": "{label}: выкл.", - "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", "aba3bb73ce212f0c": "Для {names} нужен {providerName} {version} или новее, но в Homebrew cask claude-code есть только {latestVersion}. Перейдите на cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", "d887bea446534de5": "Ни один проект в этом окружении не может прочитать {host}/{repository}.", "4e466d60e2f7736b": "Вставьте полный URL пул-реквеста: у этого треда нет репозитория, по которому можно найти номер.", "302625058bacbe38": "Вставьте полный URL: для хоста этого проекта неизвестен формат URL {changeRequest}.", @@ -376,6 +396,31 @@ "476ca970255eaea4": "Привяжите это окружение к T3 Connect, чтобы получить публичный URL.", "6b80f5b38a8f9950": "Обращаться к этому адресу может только этот компьютер. Привяжите T3 Connect, чтобы получить публичный URL.", "c5a7b1d3891dd0b8": "Работает везде, где доступен адрес этого окружения, например через Tailscale или ваш прокси. Привяжите T3 Connect, чтобы получить публичный URL.", + "3669395daf36fd33": "Больше не зарегистрирован на этом сервере", + "fe513cf316e796e3": "Запускается в составе других воркфлоу", + "ccf00b97925efab3": "Запускается вручную", + "421e585eb092b07b": "Запускается по: {triggers}", + "7bd7c58592671384": "Ждут вас", + "834ca879c14c167b": "Работает", + "582d6df7dfab86fb": "Приостановлен", + "ea6583ce92507ee3": "Спит", + "7ea8cb8af281ce93": "Ожидает", + "1347868f2523140e": "Готово", + "57d76c4614054271": "Остановлен", + "5c7344bd51d0b966": "Пропущен", + "b2074e9bd23049a6": "Отменён", + "5bb7401807ee2fb5": "Спрашивает: {question} и ещё {more}", + "9e4286183d5f9e34": "Спрашивает: {question}", + "474c18d001bd6717": "Шаг завершился ошибкой", + "d3890f4eb1508781": "Выполняет свои шаги", + "3e7ced10c9482af0": "{step} работает", + "237e1bcb1cf1bdec": "Спит на шаге {step}", + "3f7b17ac5a20c8d2": "Запускает {run}", + "0306f5f324b8aaa5": "Запусков в работе: {count}", + "e8fd779b84a202a2": "Ожидает", + "b6d55657e1a027b8": "Ожидает шага {step}", + "e942562a42aede34": "Завершён", + "26b2b9727fe11289": "Завершён досрочно", "1bb995dcec481554": "Подтвердите это устройство на {host}. Там отображается код {verificationCode}.", "8696a33219944832": "Не удалось создать подтверждение авторизации WebSocket.", "5678f133a8631f7d": "Ваш облачный вход изменился. Войдите снова, чтобы авторизовать окружение.", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", @@ -1720,6 +1768,8 @@ "2e995206e087c3fc": "Попробуйте ответить после восстановления подключения или завершения ожидающего ввода.", "604ec3067171a0d7": "Беседа", "d6182a057ea12624": "Родительский тред", + "f2d8537c33cc55a5": "Шаг запуска воркфлоу", + "ba8337dca3232880": "Открыть запуск", "30fa4a764d11ae42": "Не удалось скачать {name}", "4952f87dc98191a7": "Вложение недоступно.", "2fd6d178493fb407": "Не удалось прервать текущий ход.", @@ -1805,6 +1855,7 @@ "04fd71efaa2c3b92": "Открыть пул-реквесты", "57e875b79b98ab82": "Открыть issue", "f1db0a234c777a1d": "Использовать T3 Code в другом приложении (MCP)", + "6050f22f63e2bcb5": "Открыть воркфлоу", "a0cc19e60dd99851": "Открыть использование", "46694969044eee98": "Фокус на следующую панель рабочей области", "0a1011328ba42eef": "Фокус на предыдущую панель рабочей области", @@ -2496,8 +2547,7 @@ "2d1c111e1b4ae0b0": "Удалить тред «{title}»?", "c568ab8dad798ec5": "История беседы этого треда будет удалена безвозвратно.", "0fd1c746a0e38003": "Не удалось удалить тред", - "0ecde875b0dd2f93": "Фильтр тредов по проекту: {projects}", - "1ef65b647231ff0b": "Фильтр тредов по проекту", + "1c8fc3c4a42949ab": "Проекты: {projects}", "165511761be2855c": "Поиск проектов", "a46a6467883575a4": "Поиск проектов...", "fdc0e086438a3045": "Настройки проекта {project}", @@ -2559,10 +2609,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", "5bbac0e5afeec779": "Текущий тред", "33c7e68fca089036": "Тред, {title}", - "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", - "c6196d99000642b4": "Открыть тред", "34cc63390ad793cc": "Выберите тред", "8f12309ead62e38a": "Поиск тредов или проектов...", "2f664754d005d9a7": "Активные треды не найдены.", @@ -2572,6 +2621,7 @@ "a3178769f8308cbc": "Ошибка в треде", "89b5e8f3887812da": "Запрос гостя", "62e626804919b294": "Нужен ввод", + "c6196d99000642b4": "Открыть тред", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Вы:", "a1fbf2422c588292": "Агент:", @@ -2595,8 +2645,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Процесс в терминале запущен", "fc2c9a91f498ad6b": "{count, plural, one {Запущен {count} процесс в терминале. Открыть терминал} few {Запущено {count} процесса в терминале. Открыть терминал} many {Запущено {count} процессов в терминале. Открыть терминал} other {Запущено {count} процесса в терминале. Открыть терминал}}", - "643c4b50feadc874": "Рабочее дерево: {path} ({branch})", - "fb7c44da0f0825ea": "Рабочее дерево: {path}", "56f37ff8ca568059": "стек", "6831e9a46cbd8939": "цепочка", "9aa9e74a3b7eee91": "Добавить в чат", @@ -3033,8 +3081,8 @@ "6f85f14f35b3f547": "{provider} через {environment}", "7c59a888a062a8bd": "Нет черновика для записи голосового ввода.", "62450481c00d2ef3": "Окружение черновика недоступно для очистки расшифровки.", - "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "0674544195fcdc39": "Добавлена исходная расшифровка.", + "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "296496693cdac0db": "Команда t3 недоступна.", "efbcef7bc9bbda01": "Не удалось загрузить состояние команды t3.", "1bf6910332426e62": "Сетевой доступ десктопа недоступен.", @@ -3277,6 +3325,7 @@ "4d493d0bda4d403d": "Прикрепите прерванный файл снова или удалите его", "c9cad1d84d5f1a32": "Прикрепите прерванные файлы снова или удалите их", "536a820f2ff726da": "Выберите хотя бы одну модель.", + "48d6389202ad6754": "Отправка по готовности", "fbafbe78b5e37966": "Возобновить тред", "bcd7eb979dd38dae": "Откройте поле ввода, чтобы сжать и отправить", "95ee62a0d6968b89": "Отправить сообщение", @@ -3453,6 +3502,9 @@ "e778e4f446fdf873": "Следующее сообщение начнёт новый сеанс", "0e2f2da4f2d94785": "Агент не увидит предыдущие сообщения этого треда.", "e1189d2e582b008d": "Оставить текущий сеанс", + "2bb448d605877a22": "Отредактируйте или нажмите Esc для отмены", + "1a1f128d70c62304": "{count, plural, one {Отправится, когда изображение будет готово} few {Отправится, когда {count} изображения будут готовы} many {Отправится, когда {count} изображений будут готовы} other {Отправится, когда {count} изображения будут готовы}}", + "5af3ab719a9725fb": "Отправка сообщения", "461c9f865f2e9b92": "{option}: вкл.", "f2aa17b5c620f2a4": "{option}: выкл.", "f59314a884aae1ff": "По умолчанию", @@ -3576,6 +3628,14 @@ "c53bc5a4b0314342": "Следующее медиа", "2950b1424a3cddf5": "Переподключитесь к этому окружению и откройте медиа снова.", "ef638bf1479a5461": "Окружение вернуло некорректный URL медиа.", + "3ccfbf7e86868c35": "Обратная связь для команды T3", + "4e0710d19dfc2e7e": "Отправить этот отчёт команде T3?", + "87d0ae0723ba75d1": "С этого компьютера отправится только это содержимое. Ничего не будет отправлено, пока вы не нажмёте «Отправить».", + "bf19826f81484328": "Включить переписку", + "260c6b45f52d2f27": "Добавляет текст ваших сообщений и ответов агента за {textTurns, plural, =1 {последний ход} one {последний {textTurns} ход} few {последние {textTurns} хода} many {последние {textTurns} ходов} other {последние {textTurns} хода}}.", + "ddb7e6f8ce99e657": "Отправить отчёт или отклонить его может только тот, кто может запускать агентов на этом компьютере.", + "03c1eb603c112f47": "Не отправлять", + "653405e4ed498d9f": "Отправить", "262955d6eb632f9b": "API буфера обмена недоступен при копировании гостевой ссылки.", "f1a4f2b04cdbb4ef": "Не удалось скопировать гостевую ссылку в буфер обмена.", "cf3490a604e44d31": "Не удалось создать гостевую ссылку.", @@ -3596,7 +3656,6 @@ "abd89e9eefedf11b": "Готово", "18d166056c1ab6ff": "Прекратить общий доступ", "7a2d510eac9e4587": "Срок гостевой ссылки истёк", - "653405e4ed498d9f": "Отправить", "21888e302219891d": "Развёрнутый предпросмотр: {title}", "419719298a7acaea": "Уменьшить", "ed8d5db95359cff4": "Сбросить масштаб", @@ -3692,7 +3751,6 @@ "7c1923203049d602": "Копировать код", "637817e4ff79c90e": "Действия с блоком кода", "ebf3a2b1e314aa5f": "Выполнить в терминале", - "fe219642547fa0bf": "Выполнить в терминале", "122a8512abc51180": "Подробности", "58c38c65c2783c5d": "Полный путь", "f37e7d36b51c5b28": "Копировать относительный путь", @@ -3704,10 +3762,6 @@ "4967584e8d0fb1c2": "Предпросмотр медиа", "67589dd912eacb7c": "Открыть во встроенном браузере", "a3c98d4c4b24cecb": "Параметры файла {label}", - "b4fe8a076e9fd2f8": "Формула в отдельной строке", - "085d1407e8c92cce": "Формула в строке", - "a2ef393fa7b48ae8": "Прокрутить формулу", - "e94685ea5642e088": "Прокрутить формулу в строке", "3a04583c8500e23d": "Показать диаграмму", "16d64f650840fe06": "Показать код", "6d329f7d3a50c7e7": "Копировать таблицу", @@ -3984,9 +4038,11 @@ "973e99fa86d7f531": "Сообщение в очереди {position} из {total}, не отправлено", "0f6087c4f53c7f17": "Начать ход с этим сообщением ({shortcut})", "adab89933af02669": "Пропустить сжатие и отправить сообщение ({shortcut})", + "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", "3de4016452e8d2bd": "Отправить в текущий ход ({shortcut})", "259cc9568148e8ad": "Начать ход с этим сообщением", "bb7fddb812d5d29e": "Пропустить сжатие и отправить сообщение", + "425ab15036aec8a4": "Переместить эту команду в начало очереди", "a5fe1ee609b29a9f": "Отправить в текущий ход", "2b7fd345e4f4fd6e": "Отменить редактирование сообщения в очереди", "47f1726bf106d2c8": "Редактировать сообщение в очереди", @@ -5598,7 +5654,6 @@ }, ". Проверьте путь в ссылке или найдите файл в «Файлах»." ], - "b9b6bbd1e1ea189f": "Файл целиком", "d715e9494fdbaaf6": "Не удалось загрузить шрифт.", "ff17c777a72b4408": "Предпросмотр шрифтов ограничен 10 МБ.", "6bd41ad699e22f10": "Шрифт недоступен.", @@ -5608,6 +5663,7 @@ "a9abaaa4220eae21": "{error} Сохраните его, чтобы открыть в другом приложении.", "c508c9000d9656f8": "Предпросмотр шрифта", "1c416d621d250be8": "Съешь же ещё этих мягких французских булок, да выпей чаю.", + "d7d08260f16b7828": "Файл ещё загружается. Повторите попытку через мгновение.", "76ebb03de52c92d6": "Просмотрщик текста остановился.", "f48162e8e8c12af7": "Не удалось загрузить просмотрщик текста. Закройте файл и повторите попытку.", "bc4c5b13d38a5da7": "Предпросмотр закрыт.", @@ -5615,8 +5671,6 @@ "9450d1827ef336a1": "Уже идёт другое копирование.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} строка} few {{formatted} строки} many {{formatted} строк} other {{formatted} строки}}", "13b14784f8707ddd": "0 байт", - "f6e9581cba3467fa": "Индексация…", - "2d1f293ac12463fc": "Загрузка остальной части файла…", "b75105bef8f564a4": "Показаны первые 1 024 столбца. «Исходник» и «Сохранить» сохраняют все столбцы.", "2a6e1b1f209c3888": "Этот файл пуст.", "192fc79eb3b5b2cb": "Эта диаграмма содержит URL ресурсов, разметку, метаданные узлов или собственную конфигурацию. Откройте исходник Mermaid, чтобы безопасно её изучить.", @@ -5803,7 +5857,6 @@ "0061fff77e36bd4f": "Не удалось связаться с сервером.", "04dfdd46e3dd4a2e": "Что-то пошло не так. Повторите попытку.", "084bb2d8127a508d": "Отправлено", - "e7c59185f8ab3987": "Не отправлено", "77c01a15bd36d17c": "Срок действия ссылки истёк или она недействительна", "e0e736810f3cbef2": "Попросите владельца прислать новую ссылку. Каждая ссылка работает в одном браузере.", "c3c53aa46f7330e5": "Срок действия ссылки истёк", @@ -8829,6 +8882,12 @@ "d3866ead082d14e5": "Добавить сочетание клавиш", "d4345c90894a3220": "Открыть keybindings.json", "e56a8d51219efaa0": "Нет сочетаний клавиш по вашему запросу.", + "90a258fff61fd77e": "Выкл.", + "4060244a7079a0d2": "По моему запросу", + "e88c9d8769544731": "Автоматически", + "f29d1dade4dde8aa": "Агенты не отправляют обратную связь команде T3.", + "93c4c53562d30a98": "По вашему запросу агенты показывают краткий отчёт о T3 Code и с вашего одобрения отправляют его команде T3.", + "cd9ee803e8727017": "Агенты также сообщают о проблемах T3 Code, с которыми сталкиваются самостоятельно, например о сбое инструмента T3.", "45fa271ea0e1ac8e": "Бета", "3a678332fc7142f7": "Группирует треды боковой панели по папкам проектов. Закреплённые треды остаются наверху, а отложенные и разобранные — под папками.", "e4e91d155cb6a9b4": "Простая боковая панель (группировка по проектам)", @@ -8837,11 +8896,16 @@ "9ae293971d93c819": "Поделитесь тредом с гостем: он смотрит его в браузере в реальном времени и отправляет сообщения, которые вы одобряете. Войдите в T3 Connect, чтобы использовать гостевые ссылки.", "0aa5406ac4d7f7c7": "Гостевые ссылки", "f0e853acd2006d53": "Привязанные окружения", + "ef10c2dff987f3ea": "Запускайте многошаговые воркфлоу из файлов в папке workflows домашней папки T3 этого сервера. Открывайте их из палитры команд. Пока функция выключена, ничего из этой папки не выполняется; запуски ждут, пока её снова не включат.", + "2dadb2359422121c": "Воркфлоу", "13e86eb5d8287a71": "Показывать предполагаемое следующее сообщение в пустом поле ввода после хода Claude или Codex. Tab вставляет его. Каждое — дополнительный кешированный запрос в рамках вашего плана. Нужен Codex 0.165+. Треды Claude обновятся после перезапуска.", "d4b2a2ec812aafb0": "Предлагать следующий промпт", "298c7150a7621c80": "Хосты устройств Simlock", "67937aa49179285e": "На Mac клонировать новые рабочие деревья из копии, закешированной в домашней папке T3, вместо записи каждого файла. Если это невозможно, используется обычный checkout Git. При выключении кеш удаляется.", "f9904f78d3003f58": "Быстрый checkout рабочих деревьев", + "9c2f647882522302": "На выбранных компьютерах используются разные режимы обратной связи от агентов.", + "31bbf7bf8c0a5279": "Обратная связь от агентов", + "d52b3d6bf9f2a013": "Разные", "ec7623deed751c05": [ "Поделитесь тредом с гостем: он смотрит его в браузере в реальном времени и отправляет сообщения, которые вы одобряете. Нужен T3 Connect: войдите и привяжите эту машину в разделе", " ", @@ -8925,7 +8989,9 @@ "fb71127e5746a6bc": "Из раздела «Общий доступ» там или через t3 pair", "1e3fee7084791773": "Также привязать {target} в ответ к {source}", "ea34a190b0bd804c": "Тогда агенты на {target} смогут работать и на {source}.", - "ad5ed0ce61b966eb": "Забыть {label}? Агенты отсюда перестанут там работать. Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", + "974f8c65e8b5f492": "Забыть {label}? Агенты отсюда перестанут там работать, а их сеанс на {label} тоже завершится, если он ответит.", + "6cf9e3083b15614f": "{label} не ответил", + "34ccbdf619b83be3": "Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", "81c9796bf61b306a": "Не удалось забыть привязку", "130e51beb6cf5aad": "Привязать окружение", "122c3e355699e69d": "После этого агенты отсюда смогут запускать треды там, писать в них и ждать их. Связь появится в разделе «Авторизованные клиенты» в «Общем доступе» того окружения, где её можно отозвать.", @@ -9155,7 +9221,6 @@ "0b4779a1825c85bc": "Общее название этой группы проектов на боковой панели и в списках тредов.", "f68cbda4df83d739": "Сбросить название проекта к значению по умолчанию", "56e37b85027e8431": "Значок проекта", - "e88c9d8769544731": "Автоматически", "c99736317da5b1fa": "Сбросить значок проекта к значению по умолчанию", "6afaa3e3739dc570": "Выберите значок проекта", "51651ce45d481a20": "Выберите файл значка проекта", @@ -10130,7 +10195,6 @@ "a0eb0e4f76608833": "Сначала открывать привязанные пул-реквесты. Иначе открывать «Изменения» при правках не менее 3 файлов или 50 строк.", "16bdc70b858c223f": "Сбросить заблаговременные панели к значению по умолчанию", "3e99c5c14f4939c8": "Сбросить сжатие простаивающих тредов к значению по умолчанию", - "d52b3d6bf9f2a013": "Разные", "cd72fe451ba0d6aa": "Новые проекты", "394c3bd0a1782c8e": "Оставьте пустым, чтобы при открытии «Добавить проект» использовался «~/».", "f9b912a818bd869d": "Сбросить базовый каталог для добавления проектов к значению по умолчанию", @@ -11030,7 +11094,6 @@ "4a237f41ce592b7f": "Хранить рабочие деревья этого проекта, пока вы не удалите их вручную.", "00b8ffd8ea6e6a93": "Использовать эти правила для этого проекта.", "72c279824d15a999": "Использовать настройки очистки рабочих деревьев каждой машины.", - "90a258fff61fd77e": "Выкл.", "b5702d0b64866b08": "Свои", "c009c901f3eefe78": "Удалять рабочие деревья вместе с удалёнными тредами", "431c7cd6d50102b7": "Удалять неиспользуемые рабочие деревья при удалении активных или архивных тредов. Рабочие деревья с локальными изменениями сохраняются.", @@ -11726,7 +11789,6 @@ "4c70e3e7b3e6c493": "Секреты", "79b768229c9ef672": "Обслуживание", "54b188d65247e42f": "Эксперименты", - "f41ea186c275b56e": "О приложении", "af4b7734da1d5ce7": "Голос", "4ec62c39ca3192bf": "Контроль версий и issue", "f2bf529f85e05494": "Общий доступ", @@ -11781,6 +11843,7 @@ "d443390c4d2dcfd4": "доступность a11y экранный диктор nvda jaws voiceover orca экранный диктор заголовок окна заголовок вкладки alt tab панель задач статус треда порядок в работе подтверждение", "6826fa9579c22035": "бета поделиться гость приглашение ссылка коллега наблюдать t3 connect туннель", "f10c06cba0cdf7fe": "бета привязать другой компьютер vps агенты работают там делегировать", + "bc0b409d89ce086e": "бета воркфлоу workflow надёжные запуски автоматизация шаги расписание webhook папка", "4a21cf825a2045b0": "бета tab автодополнение предсказать следующее сообщение claude codex подсказка", "fea2dc36585c4a20": "Хосты устройств Simlock (альфа)", "9d834d178130180e": "бета альфа simlock callstack симулятор эмулятор ios android пул аренда шлюз", @@ -11852,6 +11915,7 @@ "901a823214edc8c4": "телеметрия аналитика данные об использовании отслеживание юридическое отказ", "82136480255a5106": "OTel OTLP телеметрия экспорт конечные точки логи трассировки метрики Grafana", "659d081051faf7ff": "логи трассировки процессы история ресурсов сбои спаны cpu память", + "5eaeacfa9f82051a": "отчёт ошибка проблема t3 команда отправить обратная связь агенты инструменты автоматически по моему запросу", "f537f91e1ee41d47": "сочетания клавиш горячие клавиши команды привязки json", "1ba01e7ceed64b95": "окно захват снимок экрана", "279b1cceb779ff38": "Включать текст приложения", @@ -12321,7 +12385,6 @@ "0bd41ff995d36a66": "Чтение кеша", "3f0dfe0cb15a3272": "Запись кеша", "1c9d860be42b1c02": "Вывод", - "78344b60f407928e": "Другое", "684e516076de81fe": "Стандартная", "3bbcc1b826fef537": "Быстрая", "66796576034c18ea": "Сверхбыстрая", @@ -12337,6 +12400,262 @@ "2cddd6095abc734a": "7 дней", "53493056306708cf": "30 дней", "c719359d18d37ad3": "90 дней", + "0bd950151ddc6407": "Уйти без сохранения? Изменения в этом файле будут потеряны.", + "c0ba3f6756b09f30": "Несохранённые изменения", + "6914e22d357f0ad6": "Сохранено и работает", + "aff389354a031d6f": "Файл на диске не загружается. Продолжает работать последняя версия, которая загрузилась.", + "858effde748ab563": "Сохранено, но пока не запускается.", + "ddb37138df660942": "Не сохранено. На сервере ничего не изменилось.", + "6ef4db489e40e39e": "Не удалось сохранить", + "c89624a2e9af1793": "{name} не подключено", + "b5a352a43adb4c17": "Его рабочие процессы снова появятся после переподключения. Выберите другое окружение, чтобы увидеть его запуски.", + "3dcedb736d20aae5": "Не удалось прочитать файлы воркфлоу", + "b09f4df8d76ae8ea": "Удалить {file}? Воркфлоу, которые он определяет, больше нельзя будет запустить.", + "b4535f5a03689d27": "{name} не подключено. Написанное здесь сохранится, и его можно будет сохранить, когда подключение вернётся.", + "b54c78d85fd942ea": "Удалено, но то, что запущено, ещё не обновилось.", + "407c228d7da0b7df": "Не удалено. На сервере ничего не изменилось.", + "1a6aa10f3cc14fff": "Эти файлы не согласуются между собой. Продолжает работать то, что работало раньше.", + "259312516a1dbe6f": "Имя файла", + "2f48ab2aa0586853": "Не определяет ни одного воркфлоу", + "ba5adfa37b55b8c5": [ + "Строка ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Удалить", + "84c900d1ae72adc6": "Сохранить", + "5912d817be03247a": "Файл изменился на диске, пока вы его редактировали. Сохранение заменит это изменение.", + "0b1e6f5608826387": "Загрузить файл и сбросить мои изменения", + "f47b4c06aeb77c1c": "Загрузка файлов воркфлоу…", + "4353bfd401d58f87": [ + "Каждый файл в", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "определяет воркфлоу. Изменения в любом из них подхватываются без перезапуска." + ], + "0c165251a06f10f1": "Новый файл", + "8e97cf734b4463e7": "Создать", + "2ec0d5108fd6cebe": "Воркфлоу пока нет. Создайте первый файл здесь или попросите агента написать его в этой папке.", + "5601350626e8cfe9": "Не загружается", + "21d778a1b9a0c234": "Открыто рядом с запуском", + "62dc4d3a19ff7ca0": "Закрыть вкладку", + "1e25265f2758fce3": "Открыть как полноценный тред", + "672a3dae06b39402": "Открыть на отдельной странице", + "7755500a4cde5066": "Закрыть панель", + "b8dcbc93a2ca1861": "Этого больше нет в запуске.", + "115c69de3202f664": "Открыть", + "644eafa9048b62df": "{count, plural, =1 {1-я попытка} =2 {2-я попытка} =3 {3-я попытка} one {{count}-я попытка} few {{count}-я попытка} many {{count}-я попытка} other {{count}-я попытка}}", + "e39f89c909df4db0": "Не удалось возобновить запуск", + "865f034346b82f47": "Отменить {title}? Его агенты остановятся, и запуск нельзя будет возобновить.", + "6bc75632fd9c9136": "Не удалось отменить запуск", + "64e50329dcfdd5b0": "Завершён", + "350162e7cc1ebea4": "Остановлен", + "0875cf506f4c6810": "Пропущен", + "3cc43f1dbf3f8e0c": "Отменён", + "ded70e75de6404ba": "Назад к списку запусков", + "2f4ed7dbd22be30d": "Отменить запуск", + "614e5ad58a795fb5": "Остановить", + "04b050b0329f0ac8": "занял {duration}", + "aff78e1774818ff4": "пока {duration}", + "38eddd466439afc9": "Что затронул запуск", + "156ec271d49ddd70": "Что произошло", + "34f59bbbead0b97f": "{names} и ещё {count}", + "ac1556f6ce89a5ea": "параллельно: {count}", + "e197c4963bacc746": "выполняется: {count}", + "f5319ed9e18c0df1": "Спрашивает вас", + "882a25e9084ae1b2": "Приостановлен", + "9a03d8a9afc60387": "Шаги на данный момент", + "2f2ae791afe01674": "ждёт вашего одобрения", + "24f8060c4ccdf928": "запускается", + "30a5be40eb956663": "работает", + "dd7a1e58c2553933": "проснётся через {duration}", + "95cc952724dd7310": "вот-вот проснётся", + "3cc34921c0128593": "выполняется", + "e777db2880f53a46": "никто не ответил", + "dc90739d391a5e67": "Вы ответили: {choice}", + "389f2563b5b763fd": "Быстрые шаги", + "a41c8d758121ad81": "спал", + "9db248b770096984": "ждал", + "c76124517af28686": "выполняется {duration}", + "89102905bf09b0e8": "Смотреть вживую", + "bdf338cdff4118f0": "Транскрипт", + "811e7e992f9ff820": "не может продолжиться, пока версия его воркфлоу не будет снова зарегистрирована", + "4d4cdf035e98dd57": "ждёт, пока вы его возобновите", + "eb5b21dd224a5941": "повторит попытку сам через {duration}", + "6ab3dfa749fde477": "вот-вот повторит попытку сам", + "44b6463aa70aa14c": "Почему приостановлен", + "cf25e7169ab0eb7a": "Приостановлен на шаге {step}", + "56c48c1f220f2754": "Не удалось ответить на вопрос", + "a3c43735e1a81498": "Причина: {title}", + "bfad234f016cfa3f": "Причина в одном предложении. Она прикладывается к любому выбранному ответу.", + "004c41aff9c97873": "Запуски", + "4dc0c244a2419f6c": [ + "В составе: ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "запущен", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "его версия больше не зарегистрирована", + "f92d9132f7b85d1a": "Загрузка шагов…", + "6ebc59f64c761a49": "Пока ничего.", + "a759dccd157d7dae": [ + "Вы ответили:", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Вы ответили:", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " — ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Открыть запуск", + "c8eb9be36d4d51ad": [ + "Тред на ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Возобновить", + "8cebd63fc4c967d5": "Заново выполняется только упавший шаг; всё, что завершилось до него, сохраняется.", + "bc1e0a2a0f1e9552": "Ждут вас", + "a812f51e970740f1": [ + "спросил", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· запуск ждёт вас" + ], + "02dfe6c63fd0b8a1": "Добавить причину", + "19abd94828a3bdbc": "Сначала спросить агента", + "a18721fa8f328361": "Ждут вас", + "bbf24e7920c1e86b": "Выполняются", + "8d6e18d2ad832db6": "Все", + "f25af5332ffc3734": "Вас ничего не ждёт.", + "c3f0119b8d6231f8": "Ничего не выполняется.", + "33028dfc1229eaa6": "Запусков пока нет.", + "5459bf696a187c26": "Не удалось загрузить запуски воркфлоу", + "d57c35d43b0f163a": "Этого запуска здесь нет", + "b9aae2f7cdb1a379": "Запусков воркфлоу пока нет", + "8f15f66e545af7c0": "Какие запуски", + "b6409289e0c9a4dd": "Воркфлоу", + "035cb02ca1ae4952": "Все воркфлоу ({count})", + "46d614fa7b4bf1e5": "Запуски воркфлоу", + "1c635faa2fb45b8b": "Ещё не запускался.", + "156ff7b625287a1e": "Скрыть пропущенные", + "69b985b97ab45e6b": "Показать пропущенные ({count})", + "2400254d362de84d": "Загрузка запусков воркфлоу…", + "145e1f7503ba3b2c": [ + "В этом окружении нет запуска по этой ссылке.", + " ", + { + "t": "button", + "i": 1, + "c": "Вернуться к запускам" + } + ], + "783e616cb0476c17": [ + "Воркфлоу объединяет агентов, код, расписания и вопросы к вам в один запуск, который переживает перезапуски. Напишите его в разделе", + " ", + { + "t": "button", + "i": 1, + "c": "Определения" + }, + " или попросите об этом агента.", + " ", + { + "t": "a", + "i": 2, + "c": "Читать руководство" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "В файле воркфлоу есть ошибка." + }, + " ", + "Продолжает работать последняя версия, которая загрузилась." + ], + "ed8ce6ebc73dc12d": "Открыть файл", + "5d8d278ff828102d": "Все воркфлоу", + "39459da07479f482": "Агент", + "7741243632056b81": "{step} · расшифровка", + "c512071143a5ba32": "Этого треда больше нет.", + "ed169d23683fb6ac": "Загрузка треда…", + "290e0ab40b87dc17": "Навигационная цепочка воркфлоу", + "683dd9831e54edc0": "Окружение", + "34ad53646f06ed80": "Воркфлоу выключены", + "8f6589c9e0ac5d4e": "Нет подключённых окружений", + "744127f8dfad7d22": "Подключите окружение, чтобы увидеть его запуски воркфлоу.", + "036182ec7e2ee4d4": "Рядом с запуском", + "2d6107cb78382d08": "Воркфлоу", + "16f7df687349b399": "Определения", + "f0a212aadfe1257b": "Загрузка редактора…", + "20f194e003885e95": [ + "Включите их для этого сервера в разделе", + " ", + { + "t": "Link", + "i": 1, + "c": "«Настройки → Labs»" + }, + "." + ], "8367779e149f723b": "Запрос к основному окружению не удался во время {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Недействительный токен сопряжения. Проверьте токен и попробуйте ещё раз.", "0e4b49c8203aae81": "Истекло время ожидания аутентифицированного сеанса после начальной загрузки.", @@ -12457,6 +12776,8 @@ "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", - "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", - "425ab15036aec8a4": "Переместить эту команду в начало очереди" + "99d51127f573296b": "Другой аккаунт", + "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", + "99963c0142e17f00": "Для нового аккаунта {tracker}.", + "6d8e4ebc889bace9": "Добавить аккаунт" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index e60c36cd33a49..6229647851dfd 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installera {fj} 0.6 eller senare från {fjUrl} och kör {fjLogin}, eller installera {tea} 0.16 eller senare från {teaUrl} och kör {teaLogin} för varje Forgejo- eller Gitea-server.", "d026a85e2e50e675": "Installera GitCafe CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", "22d3c0c48a34b5b3": "Installera TanStack Source CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", + "756c80ad262ef315": "Väntar i den ursprungliga tråden", + "d8df14f9905f38eb": "Skickat", + "e7c59185f8ab3987": "Inte skickat", + "b54ddec9084fa955": "Stängd utan att skickas", + "fbaa7ab5da716e50": "Bugg", + "01bac997ea55272e": "Otydligt", + "0f53bc8f74dfe56a": "Funktion saknas", + "055560f307e15e30": "Fel i dokumentationen", + "78344b60f407928e": "Övrigt", + "f653846a95cd6e8f": "Typ", + "f41ea186c275b56e": "Om", + "2f6e4f7cd364da73": "Förväntat", + "9d11c93d4035de3e": "Vad som hände", + "c87d0595693704f9": "Gjorde i stället", + "d7a4ea6ce5af44e0": "{speaker} · {count} tecken", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Omgång {turn} · {what}", + "dfdaa6255a416140": "Översikt över {turns, plural, one {{turns} senaste omgång} other {{turns} senaste omgångar}}, {textTurns, plural, =0 {ingen meddelandetext} one {meddelandetext från den senaste omgången} other {meddelandetext från de senaste {textTurns} omgångarna}}{truncated, select, yes {, förkortad för att få plats} other {}}", + "afac52a5cc2dc801": "Det gick inte att skicka ditt svar. Försök igen.", "79d776428f4d0650": "Filen kunde inte läsas in. Återanslut och försök igen.", "3ea34cbb1ca5ba9b": "Förhandsvisningen avbröts.", "7c0af279ecb3da3a": "Strömmande förhandsvisning av filer är inte tillgänglig i den här körmiljön.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} på", "77cc5f738cb7d459": "{label} av", - "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", "aba3bb73ce212f0c": "{names} kräver {providerName} {version} eller senare, men Homebrew-casken claude-code har bara {latestVersion}. Byt till casken claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", "d887bea446534de5": "Inget projekt i den här miljön kan läsa {host}/{repository}.", "4e466d60e2f7736b": "Klistra in hela pull request-URL:en; den här tråden har inget repo att slå upp numret i.", "302625058bacbe38": "Klistra in en fullständig URL; det här projektets värd har ingen känd URL för {changeRequest}.", @@ -376,6 +396,31 @@ "476ca970255eaea4": "Länka den här miljön till T3 Connect för en publik URL.", "6b80f5b38a8f9950": "Bara den här datorn kan anropa den här adressen. Länka T3 Connect för en publik URL.", "c5a7b1d3891dd0b8": "Fungerar där den här miljöns adress kan nås, till exempel via Tailscale eller din egen proxy. Länka T3 Connect för en publik URL.", + "3669395daf36fd33": "Inte längre registrerat på den här servern", + "fe513cf316e796e3": "Körs som en del av andra arbetsflöden", + "ccf00b97925efab3": "Startas manuellt", + "421e585eb092b07b": "Startar vid {triggers}", + "7bd7c58592671384": "Behöver dig", + "834ca879c14c167b": "Arbetar", + "582d6df7dfab86fb": "Pausad", + "ea6583ce92507ee3": "Sover", + "7ea8cb8af281ce93": "Väntar", + "1347868f2523140e": "Klar", + "57d76c4614054271": "Stoppad", + "5c7344bd51d0b966": "Överhoppad", + "b2074e9bd23049a6": "Avbruten", + "5bb7401807ee2fb5": "Frågar: {question} och {more} till", + "9e4286183d5f9e34": "Frågar: {question}", + "474c18d001bd6717": "Ett steg misslyckades", + "d3890f4eb1508781": "Kör sina egna steg", + "3e7ced10c9482af0": "{step} arbetar", + "237e1bcb1cf1bdec": "Sover vid {step}", + "3f7b17ac5a20c8d2": "Kör {run}", + "0306f5f324b8aaa5": "{count} körningar pågår", + "e8fd779b84a202a2": "Väntar", + "b6d55657e1a027b8": "Väntar på {step}", + "e942562a42aede34": "Klar", + "26b2b9727fe11289": "Avslutad i förtid", "1bb995dcec481554": "Godkänn den här enheten på {host}. Den visar koden {verificationCode}.", "8696a33219944832": "Kunde inte skapa auktoriseringsbeviset för websocket.", "5678f133a8631f7d": "Din molninloggning har ändrats. Logga in igen för att auktorisera miljön.", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprätta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades från.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den här klienten inte kunde läsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", @@ -1720,6 +1768,8 @@ "2e995206e087c3fc": "Försök svara när anslutningen eller den väntande inmatningen är löst.", "604ec3067171a0d7": "Konversation", "d6182a057ea12624": "Överordnad tråd", + "f2d8537c33cc55a5": "Steg i arbetsflödeskörningen", + "ba8337dca3232880": "Öppna körning", "30fa4a764d11ae42": "Kunde inte ladda ned {name}", "4952f87dc98191a7": "Bilagan är inte tillgänglig.", "2fd6d178493fb407": "Det gick inte att avbryta den aktuella omgången.", @@ -1805,6 +1855,7 @@ "04fd71efaa2c3b92": "Öppna pull requests", "57e875b79b98ab82": "Öppna ärenden", "f1db0a234c777a1d": "Använd T3 Code i en annan app (MCP)", + "6050f22f63e2bcb5": "Öppna arbetsflöden", "a0cc19e60dd99851": "Öppna användning", "46694969044eee98": "Fokusera nästa område i arbetsytan", "0a1011328ba42eef": "Fokusera föregående område i arbetsytan", @@ -2496,8 +2547,7 @@ "2d1c111e1b4ae0b0": "Ta bort tråden ”{title}”?", "c568ab8dad798ec5": "Det här rensar konversationshistoriken för den här tråden permanent.", "0fd1c746a0e38003": "Det gick inte att ta bort tråden", - "0ecde875b0dd2f93": "Filtrera trådar efter projekt: {projects}", - "1ef65b647231ff0b": "Filtrera trådar efter projekt", + "1c8fc3c4a42949ab": "Projekt: {projects}", "165511761be2855c": "Sök projekt", "a46a6467883575a4": "Sök projekt...", "fdc0e086438a3045": "Projektinställningar för {project}", @@ -2559,10 +2609,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Finns på en annan dator, så den här datorns agent kan inte läsa den. Ta bort den eller byt tillbaka för att skicka.", "5bbac0e5afeec779": "Aktuell tråd", "33c7e68fca089036": "Tråd, {title}", - "b4b98a0287c282e2": "Finns på en annan dator, så den här datorns agent kan inte läsa den. Ta bort den eller byt tillbaka för att skicka.", - "c6196d99000642b4": "Öppna tråd", "34cc63390ad793cc": "Välj en tråd", "8f12309ead62e38a": "Sök trådar eller projekt...", "2f664754d005d9a7": "Inga aktiva trådar hittades.", @@ -2572,6 +2621,7 @@ "a3178769f8308cbc": "Tråden misslyckades", "89b5e8f3887812da": "Gästbegäran", "62e626804919b294": "Input behövs", + "c6196d99000642b4": "Öppna tråd", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", @@ -2595,8 +2645,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminalprocess körs", "fc2c9a91f498ad6b": "{count, plural, one {{count} terminalprocess körs. Öppna terminalen} other {{count} terminalprocesser körs. Öppna terminalen}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "stack", "6831e9a46cbd8939": "kedja", "9aa9e74a3b7eee91": "Lägg till i chatten", @@ -3033,8 +3081,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "Röstinmatningen har inget utkast att spela in i.", "62450481c00d2ef3": "Utkastets miljö är inte tillgänglig för att städa transkriptionen.", - "c64cb58d9cecbcd2": "Det gick inte att städa transkriptionen", "0674544195fcdc39": "Den ursprungliga transkriptionen lades till.", + "c64cb58d9cecbcd2": "Det gick inte att städa transkriptionen", "296496693cdac0db": "Kommandot t3 är inte tillgängligt.", "efbcef7bc9bbda01": "Det gick inte att läsa in statusen för kommandot t3.", "1bf6910332426e62": "Skrivbordsappens nätverksåtkomst är inte tillgänglig.", @@ -3277,6 +3325,7 @@ "4d493d0bda4d403d": "Bifoga den avbrutna filen igen eller ta bort den", "c9cad1d84d5f1a32": "Bifoga de avbrutna filerna igen eller ta bort dem", "536a820f2ff726da": "Välj minst en modell.", + "48d6389202ad6754": "Skickar när det är klart", "fbafbe78b5e37966": "Återuppta tråd", "bcd7eb979dd38dae": "Öppna inmatningsfältet för att komprimera och skicka", "95ee62a0d6968b89": "Skicka meddelande", @@ -3453,6 +3502,9 @@ "e778e4f446fdf873": "Ditt nästa meddelande startar en ny session", "0e2f2da4f2d94785": "Agenten ser inte tidigare meddelanden i den här tråden.", "e1189d2e582b008d": "Behåll den aktuella sessionen", + "2bb448d605877a22": "Redigera eller tryck Esc för att avbryta", + "1a1f128d70c62304": "{count, plural, one {Skickas när bilden är klar} other {Skickas när {count} bilder är klara}}", + "5af3ab719a9725fb": "Skickar meddelande", "461c9f865f2e9b92": "{option} på", "f2aa17b5c620f2a4": "{option} av", "f59314a884aae1ff": "Standard", @@ -3576,6 +3628,14 @@ "c53bc5a4b0314342": "Nästa media", "2950b1424a3cddf5": "Återanslut till den här miljön och öppna mediet igen.", "ef638bf1479a5461": "Miljön returnerade en ogiltig media-URL.", + "3ccfbf7e86868c35": "Återkoppling till T3-teamet", + "4e0710d19dfc2e7e": "Skicka den här rapporten till T3-teamet?", + "87d0ae0723ba75d1": "Det här är allt som lämnar din dator. Inget skickas förrän du trycker på Skicka.", + "bf19826f81484328": "Ta med konversationen", + "260c6b45f52d2f27": "Lägger till texten i dina meddelanden och agentens svar under {textTurns, plural, one {den senaste omgången} other {de senaste {textTurns} omgångarna}}.", + "ddb7e6f8ce99e657": "Bara den som kan köra agenter på den här datorn kan skicka eller avböja rapporten.", + "03c1eb603c112f47": "Skicka inte", + "653405e4ed498d9f": "Skicka", "262955d6eb632f9b": "Urklipps-API:t är inte tillgängligt vid kopiering av gästlänken.", "f1a4f2b04cdbb4ef": "Kunde inte kopiera gästlänken till urklipp.", "cf3490a604e44d31": "Kunde inte skapa en gästlänk.", @@ -3596,7 +3656,6 @@ "abd89e9eefedf11b": "Klar", "18d166056c1ab6ff": "Sluta dela", "7a2d510eac9e4587": "Gästlänken har gått ut", - "653405e4ed498d9f": "Skicka", "21888e302219891d": "Expanderad förhandsvisning av {title}", "419719298a7acaea": "Zooma ut", "ed8d5db95359cff4": "Återställ zoom", @@ -3692,7 +3751,6 @@ "7c1923203049d602": "Kopiera kod", "637817e4ff79c90e": "Åtgärder för kodblock", "ebf3a2b1e314aa5f": "Kör i terminalen", - "fe219642547fa0bf": "Kör i terminalen", "122a8512abc51180": "Detaljer", "58c38c65c2783c5d": "Fullständig sökväg", "f37e7d36b51c5b28": "Kopiera relativ sökväg", @@ -3704,10 +3762,6 @@ "4967584e8d0fb1c2": "Förhandsvisa media", "67589dd912eacb7c": "Öppna i den integrerade webbläsaren", "a3c98d4c4b24cecb": "Filalternativ för {label}", - "b4fe8a076e9fd2f8": "Fristående ekvation", - "085d1407e8c92cce": "Ekvation i texten", - "a2ef393fa7b48ae8": "Rulla fristående ekvation", - "e94685ea5642e088": "Rulla ekvation i texten", "3a04583c8500e23d": "Visa diagram", "16d64f650840fe06": "Visa kod", "6d329f7d3a50c7e7": "Kopiera tabell", @@ -3984,9 +4038,11 @@ "973e99fa86d7f531": "Köat meddelande {position} av {total}, inte skickat", "0f6087c4f53c7f17": "Starta en omgång med det här meddelandet ({shortcut})", "adab89933af02669": "Hoppa över komprimering och skicka det här meddelandet ({shortcut})", + "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", "3de4016452e8d2bd": "Skicka in i den aktuella omgången ({shortcut})", "259cc9568148e8ad": "Starta en omgång med det här meddelandet", "bb7fddb812d5d29e": "Hoppa över komprimering och skicka det här meddelandet", + "425ab15036aec8a4": "Flytta det här kommandot först i kön", "a5fe1ee609b29a9f": "Skicka in i den aktuella omgången", "2b7fd345e4f4fd6e": "Avbryt redigering av köat meddelande", "47f1726bf106d2c8": "Redigera köat meddelande", @@ -5599,7 +5655,6 @@ }, ". Kontrollera länkens sökväg eller leta upp filen i Filer." ], - "b9b6bbd1e1ea189f": "Hela filen", "d715e9494fdbaaf6": "Teckensnittet kunde inte läsas in.", "ff17c777a72b4408": "Förhandsvisningar av teckensnitt är begränsade till 10 MB.", "6bd41ad699e22f10": "Teckensnittet är inte tillgängligt.", @@ -5609,6 +5664,7 @@ "a9abaaa4220eae21": "{error} Spara det för att öppna det i en annan app.", "c508c9000d9656f8": "Förhandsvisning av teckensnitt", "1c416d621d250be8": "Flygande bäckasiner söka hwila på mjuka tuvor.", + "d7d08260f16b7828": "Filen läses fortfarande in. Försök igen om en stund.", "76ebb03de52c92d6": "Textvisaren stoppades.", "f48162e8e8c12af7": "Kunde inte läsa in textvisaren. Stäng filen och försök igen.", "bc4c5b13d38a5da7": "Förhandsvisningen stängdes.", @@ -5616,8 +5672,6 @@ "9450d1827ef336a1": "En annan kopiering pågår.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} rad} other {{formatted} rader}}", "13b14784f8707ddd": "0 byte", - "f6e9581cba3467fa": "Indexerar…", - "2d1f293ac12463fc": "Läser in resten av filen…", "b75105bef8f564a4": "Visar de första 1 024 kolumnerna. Källa och Spara behåller alla kolumner.", "2a6e1b1f209c3888": "Den här filen är tom.", "192fc79eb3b5b2cb": "Det här diagrammet innehåller resurs-URL:er, markup, nodmetadata eller anpassad konfiguration. Visa Mermaid-källan för att granska det säkert.", @@ -5804,7 +5858,6 @@ "0061fff77e36bd4f": "Kunde inte nå servern.", "04dfdd46e3dd4a2e": "Något gick fel. Försök igen.", "084bb2d8127a508d": "Skickat", - "e7c59185f8ab3987": "Inte skickat", "77c01a15bd36d17c": "Den här länken har upphört eller är ogiltig", "e0e736810f3cbef2": "Be ägaren om en ny länk. Varje länk fungerar i en webbläsare.", "c3c53aa46f7330e5": "Den här länken har upphört", @@ -8835,6 +8888,12 @@ "d3866ead082d14e5": "Lägg till kortkommando", "d4345c90894a3220": "Öppna keybindings.json", "e56a8d51219efaa0": "Inga kortkommandon matchar sökningen.", + "90a258fff61fd77e": "Av", + "4060244a7079a0d2": "När jag ber om det", + "e88c9d8769544731": "Automatisk", + "f29d1dade4dde8aa": "Agenter skickar ingen återkoppling till T3-teamet.", + "93c4c53562d30a98": "När du ber om det visar agenter en kort rapport om T3 Code och skickar den till T3-teamet om du godkänner den.", + "cd9ee803e8727017": "Agenter rapporterar även problem med T3 Code som de själva stöter på, till exempel ett T3-verktyg som misslyckats.", "45fa271ea0e1ac8e": "Beta", "3a678332fc7142f7": "Gruppera trådar i sidofältet i projektmappar. Fästa trådar ligger överst, och Snoozade och Klara ligger under mapparna.", "e4e91d155cb6a9b4": "Enkelt sidofält (gruppera per projekt)", @@ -8843,11 +8902,16 @@ "9ae293971d93c819": "Dela en tråd med en gäst som följer den live i en webbläsare och skickar meddelanden som du godkänner. Logga in på T3 Connect för att använda gästlänkar.", "0aa5406ac4d7f7c7": "Gästlänkar", "f0e853acd2006d53": "Länkade miljöer", + "ef10c2dff987f3ea": "Kör arbetsflöden i flera steg från filer i mappen workflows i serverns T3-hemkatalog. Öppna dem från kommandopaletten. När det är av körs inget i mappen; körningar väntar tills det slås på igen.", + "2dadb2359422121c": "Arbetsflöden", "13e86eb5d8287a71": "Visa ett förutsagt nästa meddelande i det tomma inmatningsfältet efter en omgång med Claude eller Codex. Tab använder det. Varje förslag är en extra cachad begäran i ditt abonnemang. Kräver Codex 0.165+. Claude-trådar uppdateras vid omstart.", "d4b2a2ec812aafb0": "Föreslå nästa prompt", "298c7150a7621c80": "Simlock-enhetsvärdar", "67937aa49179285e": "På en Mac klonas nya worktrees från en utcheckning som cachas i T3-hemmappen i stället för att varje fil skrivs. Använder Gits vanliga utcheckning när det inte går. Om du stänger av det tas cachen bort.", "f9904f78d3003f58": "Snabb utcheckning av worktree", + "9c2f647882522302": "De valda datorerna använder olika lägen för återkoppling från agenter.", + "31bbf7bf8c0a5279": "Återkoppling från agenter", + "d52b3d6bf9f2a013": "Blandat", "ec7623deed751c05": [ "Dela en tråd med en gäst som följer den live i en webbläsare och skickar meddelanden som du godkänner. Kräver T3 Connect: logga in och länka den här datorn under", " ", @@ -8931,7 +8995,9 @@ "fb71127e5746a6bc": "Från Delning och åtkomst där, eller t3 pair", "1e3fee7084791773": "Länka även {target} tillbaka till {source}", "ea34a190b0bd804c": "Agenter på {target} kan då också arbeta på {source}.", - "ad5ed0ce61b966eb": "Glöm {label}? Agenter här slutar arbeta där. Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", + "974f8c65e8b5f492": "Glöm {label}? Agenter här slutar arbeta där, och deras session på {label} avslutas också om den svarar.", + "6cf9e3083b15614f": "{label} svarade inte", + "34ccbdf619b83be3": "Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", "81c9796bf61b306a": "Kunde inte glömma länken", "130e51beb6cf5aad": "Länka en miljö", "122c3e355699e69d": "Agenter här kan sedan starta, skicka meddelanden till och vänta på trådar där. Den visas under Auktoriserade klienter i miljöns Delning och åtkomst, där den kan återkallas.", @@ -9160,7 +9226,6 @@ "0b4779a1825c85bc": "Det gemensamma namnet för projektgruppen i sidofältet och trådlistorna.", "f68cbda4df83d739": "Återställ projektnamn till standard", "56e37b85027e8431": "Projektikon", - "e88c9d8769544731": "Automatisk", "c99736317da5b1fa": "Återställ projektikon till standard", "6afaa3e3739dc570": "Välj en projektikon", "51651ce45d481a20": "Välj en fil för projektikonen", @@ -9510,9 +9575,9 @@ "d2b0987f8c907e13": "Samplar var {ms} ms", "4a3d538e12caed70": "{count, plural, one {Samplar var {seconds} sekund} other {Samplar var {seconds}:e sekund}}", "32c787e014d8f2ec": "Underprocess i backend", - "ca84041dbbfb9e45": "Electron main", + "ca84041dbbfb9e45": "Electrons huvudprocess", "0693ca29c961e19b": "Renderare", - "fb4e08f7e0f78d3b": "Electron utility", + "fb4e08f7e0f78d3b": "Electrons hjälpprocess", "7f206abc2cb38ab2": "Övervakare", "7cdfa8c2f4106d6a": "T3-process", "9bc60e1d0ef816cf": "Lagringsbyte", @@ -10135,7 +10200,6 @@ "a0eb0e4f76608833": "Öppna länkade pull requests först. Annars öppnas Ändringar för redigeringar av minst 3 filer eller 50 rader.", "16bdc70b858c223f": "Återställ proaktiva paneler till standard", "3e99c5c14f4939c8": "Återställ komprimering av inaktiva trådar till standard", - "d52b3d6bf9f2a013": "Blandat", "cd72fe451ba0d6aa": "Nya projekt", "394c3bd0a1782c8e": "Lämna tomt för att använda ”~/” när bläddraren Lägg till projekt öppnas.", "f9b912a818bd869d": "Återställ baskatalog för nya projekt till standard", @@ -11037,7 +11101,6 @@ "4a237f41ce592b7f": "Behåll projektets worktrees tills du tar bort dem manuellt.", "00b8ffd8ea6e6a93": "Använd de här reglerna för projektet.", "72c279824d15a999": "Använd varje dators inställningar för rensning av worktrees.", - "90a258fff61fd77e": "Av", "b5702d0b64866b08": "Anpassat", "c009c901f3eefe78": "Ta bort worktrees med borttagna trådar", "431c7cd6d50102b7": "Ta bort oanvända worktrees när aktiva eller arkiverade trådar tas bort. Worktrees med lokala ändringar behålls.", @@ -11733,7 +11796,6 @@ "4c70e3e7b3e6c493": "Hemligheter", "79b768229c9ef672": "Underhåll", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Om", "af4b7734da1d5ce7": "Röst", "4ec62c39ca3192bf": "Versioner och ärenden", "f2bf529f85e05494": "Delning och åtkomst", @@ -11788,6 +11850,7 @@ "d443390c4d2dcfd4": "tillgänglighet a11y skärmläsare nvda jaws voiceover orca skärmläsaren fönstertitel fliktitel alt tab aktivitetsfält trådstatus ordning arbetar godkännande", "6826fa9579c22035": "beta dela gäst bjud in länk kollega titta t3 connect tunnel", "f10c06cba0cdf7fe": "beta länka en annan dator vps peer agenter arbetar där delegera", + "bc0b409d89ce086e": "beta arbetsflöde workflow beständiga körningar automatisering steg schema webhook mapp", "4a21cf825a2045b0": "beta tabb autokomplettering förutsäg nästa meddelande claude codex spöktext", "fea2dc36585c4a20": "Simlock-enhetsvärdar (alfa)", "9d834d178130180e": "beta alpha simlock callstack simulator emulator ios android pool lån gateway", @@ -11859,6 +11922,7 @@ "901a823214edc8c4": "telemetri analys användningsdata spårning juridiskt avböj", "82136480255a5106": "OTel OTLP telemetri export slutpunkter loggar spår mätvärden Grafana", "659d081051faf7ff": "loggar spår processer resurshistorik fel spans cpu minne", + "5eaeacfa9f82051a": "rapport bugg problem t3 team skicka återkoppling agenter verktyg automatiskt när jag ber om det", "f537f91e1ee41d47": "kortkommandon snabbtangenter kommandon tangentbindningar json", "1ba01e7ceed64b95": "fönster fånga skärmbild", "279b1cceb779ff38": "Ta med apptext", @@ -12328,7 +12392,6 @@ "0bd41ff995d36a66": "Cacheläsning", "3f0dfe0cb15a3272": "Cacheskrivning", "1c9d860be42b1c02": "Utdata", - "78344b60f407928e": "Övrigt", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Snabb", "66796576034c18ea": "Ultrasnabb", @@ -12344,6 +12407,262 @@ "2cddd6095abc734a": "7 dagar", "53493056306708cf": "30 dagar", "c719359d18d37ad3": "90 dagar", + "0bd950151ddc6407": "Lämna utan att spara? Dina ändringar i filen går förlorade.", + "c0ba3f6756b09f30": "Osparade ändringar", + "6914e22d357f0ad6": "Sparad och körs", + "aff389354a031d6f": "Filen på disken går inte att läsa in. Den senaste versionen som gick att läsa in körs vidare.", + "858effde748ab563": "Sparad, men den körs inte än.", + "ddb37138df660942": "Inte sparad. Inget ändrades på servern.", + "6ef4db489e40e39e": "Kunde inte spara", + "c89624a2e9af1793": "{name} är inte ansluten", + "b5a352a43adb4c17": "Dess arbetsflöden visas igen när den ansluter igen. Välj en annan miljö för att se dess körningar.", + "3dcedb736d20aae5": "Kunde inte läsa arbetsflödesfilerna", + "b09f4df8d76ae8ea": "Ta bort {file}? Arbetsflödena som den definierar kan inte längre startas.", + "b4535f5a03689d27": "{name} är inte ansluten. Det du skriver här finns kvar och kan sparas när den är tillbaka.", + "b54c78d85fd942ea": "Borttagen, men det som körs har inte hunnit ikapp än.", + "407c228d7da0b7df": "Inte borttagen. Inget ändrades på servern.", + "1a6aa10f3cc14fff": "De här filerna passar inte ihop. Det som kördes förut körs vidare.", + "259312516a1dbe6f": "Filnamn", + "2f48ab2aa0586853": "Definierar inga arbetsflöden", + "ba5adfa37b55b8c5": [ + "Rad ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + ":" + ], + "d94eb9ab3201b641": "Ta bort", + "84c900d1ae72adc6": "Spara", + "5912d817be03247a": "Filen ändrades på disken medan du redigerade. Om du sparar ersätts den ändringen.", + "0b1e6f5608826387": "Läs in filen och släng mina ändringar", + "f47b4c06aeb77c1c": "Läser in arbetsflödesfilerna…", + "4353bfd401d58f87": [ + "Varje fil i", + " ", + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "definierar arbetsflöden. En ändring i någon av dem plockas upp utan omstart." + ], + "0c165251a06f10f1": "Ny fil", + "8e97cf734b4463e7": "Skapa", + "2ec0d5108fd6cebe": "Inga arbetsflöden än. Skapa den första filen här, eller be en agent skriva en i den mappen.", + "5601350626e8cfe9": "Går inte att läsa in", + "21d778a1b9a0c234": "Öppet bredvid körningen", + "62dc4d3a19ff7ca0": "Stäng flik", + "1e25265f2758fce3": "Öppna som en hel tråd", + "672a3dae06b39402": "Öppna på en egen sida", + "7755500a4cde5066": "Stäng panelen", + "b8dcbc93a2ca1861": "Körningen listar det inte längre.", + "115c69de3202f664": "Öppna", + "644eafa9048b62df": "{count, plural, =1 {1:a försöket} =2 {2:a försöket} =3 {3:e försöket} other {försök {count}}}", + "e39f89c909df4db0": "Kunde inte återuppta körningen", + "865f034346b82f47": "Avbryta {title}? Dess agenter stoppas och körningen kan inte återupptas.", + "6bc75632fd9c9136": "Kunde inte avbryta körningen", + "64e50329dcfdd5b0": "Klar", + "350162e7cc1ebea4": "Stoppad", + "0875cf506f4c6810": "Överhoppad", + "3cc43f1dbf3f8e0c": "Avbruten", + "ded70e75de6404ba": "Tillbaka till listan över körningar", + "2f4ed7dbd22be30d": "Avbryt körningen", + "614e5ad58a795fb5": "Stoppa", + "04b050b0329f0ac8": "tog {duration}", + "aff78e1774818ff4": "{duration} hittills", + "38eddd466439afc9": "Vad körningen rörde", + "156ec271d49ddd70": "Vad som hände", + "34f59bbbead0b97f": "{names} och {count} till", + "ac1556f6ce89a5ea": "{count} parallellt", + "e197c4963bacc746": "{count} körs", + "f5319ed9e18c0df1": "Frågar dig", + "882a25e9084ae1b2": "Pausad", + "9a03d8a9afc60387": "Steg hittills", + "2f2ae791afe01674": "väntar på ditt godkännande", + "24f8060c4ccdf928": "startar", + "30a5be40eb956663": "arbetar", + "dd7a1e58c2553933": "vaknar om {duration}", + "95cc952724dd7310": "vaknar strax", + "3cc34921c0128593": "körs", + "e777db2880f53a46": "ingen svarade", + "dc90739d391a5e67": "Du svarade {choice}", + "389f2563b5b763fd": "Snabba steg", + "a41c8d758121ad81": "sov", + "9db248b770096984": "väntade", + "c76124517af28686": "har körts i {duration}", + "89102905bf09b0e8": "Följ live", + "bdf338cdff4118f0": "Transkript", + "811e7e992f9ff820": "kan inte fortsätta förrän dess arbetsflödesversion registreras igen", + "4d4cdf035e98dd57": "väntar på att du återupptar den", + "eb5b21dd224a5941": "försöker igen själv om {duration}", + "6ab3dfa749fde477": "försöker strax igen själv", + "44b6463aa70aa14c": "Varför den pausades", + "cf25e7169ab0eb7a": "Pausad vid {step}", + "56c48c1f220f2754": "Kunde inte svara på frågan", + "a3c43735e1a81498": "Skäl för {title}", + "bfad234f016cfa3f": "Varför, i en mening. Det följer med vilket svar du än väljer.", + "004c41aff9c97873": "Körningar", + "4dc0c244a2419f6c": [ + "Del av ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + "startade", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8bffb377e2a6a7de": "dess version är inte längre registrerad", + "f92d9132f7b85d1a": "Läser in steg…", + "6ebc59f64c761a49": "Inget än.", + "a759dccd157d7dae": [ + "Du svarade", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + "." + ], + "593b425188346781": [ + "Du svarade", + " ", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ": ", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "Öppna körning", + "c8eb9be36d4d51ad": [ + "Tråd på ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "3d9761e81798fcd8": "Återuppta", + "8cebd63fc4c967d5": "Bara det misslyckade steget körs igen; det som blev klart före det behålls.", + "bc1e0a2a0f1e9552": "Behöver dig", + "a812f51e970740f1": [ + "frågade", + " ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " ", + "· körningen väntar på dig" + ], + "02dfe6c63fd0b8a1": "Lägg till ett skäl", + "19abd94828a3bdbc": "Fråga agenten först", + "a18721fa8f328361": "Behöver dig", + "bbf24e7920c1e86b": "Körs", + "8d6e18d2ad832db6": "Alla", + "f25af5332ffc3734": "Inget väntar på dig.", + "c3f0119b8d6231f8": "Inget körs.", + "33028dfc1229eaa6": "Inga körningar än.", + "5459bf696a187c26": "Kunde inte läsa in arbetsflödeskörningarna", + "d57c35d43b0f163a": "Den här körningen finns inte här", + "b9aae2f7cdb1a379": "Inga arbetsflödeskörningar än", + "8f15f66e545af7c0": "Vilka körningar", + "b6409289e0c9a4dd": "Arbetsflöde", + "035cb02ca1ae4952": "Alla arbetsflöden ({count})", + "46d614fa7b4bf1e5": "Arbetsflödeskörningar", + "1c635faa2fb45b8b": "Har inte körts än.", + "156ff7b625287a1e": "Dölj överhoppade", + "69b985b97ab45e6b": "Visa överhoppade ({count})", + "2400254d362de84d": "Läser in arbetsflödeskörningar…", + "145e1f7503ba3b2c": [ + "Den här miljön har ingen körning med den länken.", + " ", + { + "t": "button", + "i": 1, + "c": "Tillbaka till körningarna" + } + ], + "783e616cb0476c17": [ + "Ett arbetsflöde knyter ihop agenter, kod, scheman och frågor till dig i en enda körning som överlever omstarter. Skriv ett under", + " ", + { + "t": "button", + "i": 1, + "c": "Definitioner" + }, + ", eller be en agent göra det.", + " ", + { + "t": "a", + "i": 2, + "c": "Läs guiden" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "En arbetsflödesfil har ett problem." + }, + " ", + "Den senaste versionen som gick att läsa in körs vidare." + ], + "ed8ce6ebc73dc12d": "Öppna filen", + "5d8d278ff828102d": "Alla arbetsflöden", + "39459da07479f482": "Agent", + "7741243632056b81": "{step} · transkript", + "c512071143a5ba32": "Den här tråden finns inte längre.", + "ed169d23683fb6ac": "Läser in tråden…", + "290e0ab40b87dc17": "Brödsmulor för arbetsflöden", + "683dd9831e54edc0": "Miljö", + "34ad53646f06ed80": "Arbetsflöden är avstängda", + "8f6589c9e0ac5d4e": "Ingen miljö ansluten", + "744127f8dfad7d22": "Anslut en miljö för att se dess arbetsflödeskörningar.", + "036182ec7e2ee4d4": "Bredvid körningen", + "2d6107cb78382d08": "Arbetsflöden", + "16f7df687349b399": "Definitioner", + "f0a212aadfe1257b": "Läser in redigeraren…", + "20f194e003885e95": [ + "Slå på dem för den här servern i", + " ", + { + "t": "Link", + "i": 1, + "c": "Inställningar → Labs" + }, + "." + ], "8367779e149f723b": "Begäran till den primära miljön misslyckades under {operation} (HTTP {status}).", "c5cd027743a2b5a6": "Ogiltig parkopplingstoken. Kontrollera token och försök igen.", "0e4b49c8203aae81": "Tidsgränsen överskreds i väntan på en autentiserad session efter uppstart.", @@ -12464,6 +12783,8 @@ "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", - "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", - "425ab15036aec8a4": "Flytta det här kommandot först i kön" + "99d51127f573296b": "Ett konto till", + "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", + "99963c0142e17f00": "För det nya {tracker}-kontot.", + "6d8e4ebc889bace9": "Lägg till konto" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 607481f86fa88..bd4ddf30bd0f8 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "请从 {fjUrl} 安装 {fj} 0.6 或更高版本并运行 {fjLogin},或从 {teaUrl} 安装 {tea} 0.16 或更高版本,并为每个 Forgejo 或 Gitea 服务器运行 {teaLogin}。", "d026a85e2e50e675": "请使用 {install} 安装 GitCafe CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", "22d3c0c48a34b5b3": "请使用 {install} 安装 TanStack Source CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", + "756c80ad262ef315": "正在原始对话中等待", + "d8df14f9905f38eb": "已发送", + "e7c59185f8ab3987": "未发送", + "b54ddec9084fa955": "已关闭,未发送", + "fbaa7ab5da716e50": "错误", + "01bac997ea55272e": "难以理解", + "0f53bc8f74dfe56a": "缺少功能", + "055560f307e15e30": "文档有误", + "78344b60f407928e": "其他", + "f653846a95cd6e8f": "类型", + "f41ea186c275b56e": "关于", + "2f6e4f7cd364da73": "预期行为", + "9d11c93d4035de3e": "实际情况", + "c87d0595693704f9": "替代做法", + "d7a4ea6ce5af44e0": "{speaker} · {count} 个字符", + "f5114fb9c40fd929": "你", + "cd03eb1b84271c02": "智能体", + "bfe1a60f3f9c60fb": "第 {turn} 轮 · {what}", + "dfdaa6255a416140": "{turns, plural, one {最近 {turns} 轮的概要} other {最近 {turns} 轮的概要}},{textTurns, plural, =0 {不含消息文本} one {包含最后一轮的消息文本} other {包含最近 {textTurns} 轮的消息文本}}{truncated, select, yes {,已缩短以符合长度限制} other {}}", + "afac52a5cc2dc801": "无法发送你的回答。请重试。", "79d776428f4d0650": "无法加载文件。请重新连接后重试。", "3ea34cbb1ca5ba9b": "预览已取消。", "7c0af279ecb3da3a": "此运行时不支持流式文件预览。", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "普通", "f42c2a36b3507308": "{label} 开启", "77cc5f738cb7d459": "{label} 关闭", - "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", "aba3bb73ce212f0c": "使用 {names} 需要 {providerName} {version} 或更高版本,但 Homebrew 的 claude-code cask 只有 {latestVersion}。请切换到 claude-code@latest cask:{command}", + "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", + "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", "d887bea446534de5": "此环境中没有项目能读取 {host}/{repository}。", "4e466d60e2f7736b": "请粘贴完整的 pull request URL;此会话没有可用于解析编号的仓库。", "302625058bacbe38": "请粘贴完整 URL;此项目的托管平台没有已知的 {changeRequest} URL。", @@ -376,6 +396,31 @@ "476ca970255eaea4": "将此环境关联到 T3 Connect,获取公网 URL。", "6b80f5b38a8f9950": "只有本机可以访问此地址。关联 T3 Connect 可获取公网 URL。", "c5a7b1d3891dd0b8": "只要能连接此环境的地址(例如通过 Tailscale 或你自己的代理)即可使用。关联 T3 Connect 可获取公网 URL。", + "3669395daf36fd33": "已不再注册到此服务器", + "fe513cf316e796e3": "作为其他工作流的一部分运行", + "ccf00b97925efab3": "手动启动", + "421e585eb092b07b": "由 {triggers} 触发启动", + "7bd7c58592671384": "等你处理", + "834ca879c14c167b": "运行中", + "582d6df7dfab86fb": "已暂停", + "ea6583ce92507ee3": "休眠中", + "7ea8cb8af281ce93": "等待中", + "1347868f2523140e": "完成", + "57d76c4614054271": "已停止", + "5c7344bd51d0b966": "已跳过", + "b2074e9bd23049a6": "已取消", + "5bb7401807ee2fb5": "提问:{question},另有 {more} 个", + "9e4286183d5f9e34": "提问:{question}", + "474c18d001bd6717": "有步骤失败", + "d3890f4eb1508781": "正在运行自身的步骤", + "3e7ced10c9482af0": "{step} 正在运行", + "237e1bcb1cf1bdec": "在 {step} 休眠中", + "3f7b17ac5a20c8d2": "运行 {run}", + "0306f5f324b8aaa5": "{count} 个运行进行中", + "e8fd779b84a202a2": "等待中", + "b6d55657e1a027b8": "正在等待 {step}", + "e942562a42aede34": "已完成", + "26b2b9727fe11289": "提前结束", "1bb995dcec481554": "请在 {host} 上批准此设备。它会显示代码 {verificationCode}。", "8696a33219944832": "无法创建 WebSocket 授权证明。", "5678f133a8631f7d": "你的云端登录已变化。请重新登录以授权环境。", @@ -637,6 +682,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -1720,6 +1768,8 @@ "2e995206e087c3fc": "请在连接恢复或待处理的输入完成后重试回复。", "604ec3067171a0d7": "对话", "d6182a057ea12624": "父会话", + "f2d8537c33cc55a5": "工作流运行的步骤", + "ba8337dca3232880": "打开运行", "30fa4a764d11ae42": "无法下载 {name}", "4952f87dc98191a7": "附件不可用。", "2fd6d178493fb407": "无法中断当前这一轮。", @@ -1805,6 +1855,7 @@ "04fd71efaa2c3b92": "打开 PR", "57e875b79b98ab82": "打开 issue", "f1db0a234c777a1d": "在其他应用中使用 T3 Code(MCP)", + "6050f22f63e2bcb5": "打开工作流", "a0cc19e60dd99851": "打开用量", "46694969044eee98": "聚焦下一个工作区区域", "0a1011328ba42eef": "聚焦上一个工作区区域", @@ -2500,8 +2551,7 @@ "2d1c111e1b4ae0b0": "删除会话“{title}”?", "c568ab8dad798ec5": "这将永久清除此会话的对话历史。", "0fd1c746a0e38003": "删除会话失败", - "0ecde875b0dd2f93": "按项目筛选会话:{projects}", - "1ef65b647231ff0b": "按项目筛选会话", + "1c8fc3c4a42949ab": "项目:{projects}", "165511761be2855c": "搜索项目", "a46a6467883575a4": "搜索项目…", "fdc0e086438a3045": "{project} 的项目设置", @@ -2563,10 +2613,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", "5bbac0e5afeec779": "当前会话", "33c7e68fca089036": "会话,{title}", - "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", - "c6196d99000642b4": "打开会话", "34cc63390ad793cc": "选择会话", "8f12309ead62e38a": "搜索会话或项目…", "2f664754d005d9a7": "未找到活动会话。", @@ -2576,6 +2625,7 @@ "a3178769f8308cbc": "会话失败", "89b5e8f3887812da": "访客请求", "62e626804919b294": "需要输入", + "c6196d99000642b4": "打开会话", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "你:", "a1fbf2422c588292": "智能体:", @@ -2599,8 +2649,6 @@ "3260b22f72f7effb": "{tooltipLead}:{title}", "feac8e54b30c5a03": "终端进程正在运行", "fc2c9a91f498ad6b": "{count, plural, other {{count} 个终端进程正在运行。打开终端}}", - "643c4b50feadc874": "工作树:{path}({branch})", - "fb7c44da0f0825ea": "工作树:{path}", "56f37ff8ca568059": "堆叠", "6831e9a46cbd8939": "链", "9aa9e74a3b7eee91": "添加到对话", @@ -3037,8 +3085,8 @@ "6f85f14f35b3f547": "{provider}(经由 {environment})", "7c59a888a062a8bd": "语音输入没有可录入的草稿。", "62450481c00d2ef3": "草稿所在环境不可用,无法整理转写内容。", - "c64cb58d9cecbcd2": "转写文本整理失败", "0674544195fcdc39": "已添加原始转写文本。", + "c64cb58d9cecbcd2": "转写文本整理失败", "296496693cdac0db": "t3 命令不可用。", "efbcef7bc9bbda01": "无法加载 t3 命令状态。", "1bf6910332426e62": "桌面网络访问不可用。", @@ -3281,6 +3329,7 @@ "4d493d0bda4d403d": "请重新添加中断的文件,或将其移除", "c9cad1d84d5f1a32": "请重新添加中断的文件,或将它们移除", "536a820f2ff726da": "请至少选择一个模型。", + "48d6389202ad6754": "就绪后发送", "fbafbe78b5e37966": "继续会话", "bcd7eb979dd38dae": "打开输入框以压缩并发送", "95ee62a0d6968b89": "发送消息", @@ -3458,6 +3507,9 @@ "e778e4f446fdf873": "你的下一条消息将以全新上下文开始", "0e2f2da4f2d94785": "智能体将看不到这个会话里之前的消息。", "e1189d2e582b008d": "保留当前上下文", + "2bb448d605877a22": "编辑或按 Esc 取消", + "1a1f128d70c62304": "{count, plural, other {图片就绪后发送}}", + "5af3ab719a9725fb": "正在发送消息", "461c9f865f2e9b92": "{option} 开启", "f2aa17b5c620f2a4": "{option} 关闭", "f59314a884aae1ff": "默认", @@ -3581,6 +3633,14 @@ "c53bc5a4b0314342": "下一个媒体", "2950b1424a3cddf5": "请重新连接这个环境,然后再打开媒体。", "ef638bf1479a5461": "环境返回了无效的媒体 URL。", + "3ccfbf7e86868c35": "给 T3 团队的反馈", + "4e0710d19dfc2e7e": "将这份报告发送给 T3 团队?", + "87d0ae0723ba75d1": "只有这些内容会从你的机器发送出去。点击“发送”前,不会发送任何内容。", + "bf19826f81484328": "包含对话", + "260c6b45f52d2f27": "添加你在最近 {textTurns} 轮中的消息和智能体回复的文本。", + "ddb7e6f8ce99e657": "只有能在这台机器上运行智能体的人,才能发送或拒绝这份报告。", + "03c1eb603c112f47": "不发送", + "653405e4ed498d9f": "发送", "262955d6eb632f9b": "复制访客链接时剪贴板 API 不可用。", "f1a4f2b04cdbb4ef": "无法将访客链接复制到剪贴板。", "cf3490a604e44d31": "无法创建访客链接。", @@ -3601,7 +3661,6 @@ "abd89e9eefedf11b": "完成", "18d166056c1ab6ff": "停止分享", "7a2d510eac9e4587": "访客链接已过期", - "653405e4ed498d9f": "发送", "21888e302219891d": "展开的 {title} 预览", "419719298a7acaea": "缩小", "ed8d5db95359cff4": "重置缩放", @@ -3697,7 +3756,6 @@ "7c1923203049d602": "复制代码", "637817e4ff79c90e": "代码块操作", "ebf3a2b1e314aa5f": "在终端中运行", - "fe219642547fa0bf": "在终端中运行", "122a8512abc51180": "详情", "58c38c65c2783c5d": "完整路径", "f37e7d36b51c5b28": "复制相对路径", @@ -3709,10 +3767,6 @@ "4967584e8d0fb1c2": "预览媒体", "67589dd912eacb7c": "在内置浏览器中打开", "a3c98d4c4b24cecb": "{label} 的文件选项", - "b4fe8a076e9fd2f8": "独立公式", - "085d1407e8c92cce": "行内公式", - "a2ef393fa7b48ae8": "滚动查看独立公式", - "e94685ea5642e088": "滚动查看行内公式", "3a04583c8500e23d": "显示图表", "16d64f650840fe06": "显示代码", "6d329f7d3a50c7e7": "复制表格", @@ -3989,9 +4043,11 @@ "973e99fa86d7f531": "排队消息 {position}/{total},尚未发送", "0f6087c4f53c7f17": "用此消息开始一个轮次 ({shortcut})", "adab89933af02669": "跳过压缩并发送此消息 ({shortcut})", + "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", "3de4016452e8d2bd": "发送到当前轮次 ({shortcut})", "259cc9568148e8ad": "用这条消息开始新一轮", "bb7fddb812d5d29e": "跳过压缩并发送这条消息", + "425ab15036aec8a4": "将此命令移到队列最前面", "a5fe1ee609b29a9f": "发送到当前这一轮", "2b7fd345e4f4fd6e": "取消编辑排队消息", "47f1726bf106d2c8": "编辑排队消息", @@ -5605,7 +5661,6 @@ }, "。请检查链接的路径,或在“文件”中找到该文件。" ], - "b9b6bbd1e1ea189f": "完整文件", "d715e9494fdbaaf6": "无法加载该字体。", "ff17c777a72b4408": "字体预览限制为 10 MB。", "6bd41ad699e22f10": "该字体不可用。", @@ -5615,6 +5670,7 @@ "a9abaaa4220eae21": "{error} 保存后可在其他应用中打开。", "c508c9000d9656f8": "字体预览", "1c416d621d250be8": "敏捷的棕色狐狸跳过了那只懒狗。", + "d7d08260f16b7828": "文件仍在加载中。请稍后重试。", "76ebb03de52c92d6": "文本查看器已停止。", "f48162e8e8c12af7": "无法加载文本查看器。请关闭文件后重试。", "bc4c5b13d38a5da7": "预览已关闭。", @@ -5622,8 +5678,6 @@ "9450d1827ef336a1": "另一个复制操作正在进行。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 字节", - "f6e9581cba3467fa": "正在建立索引…", - "2d1f293ac12463fc": "正在加载文件的其余部分…", "b75105bef8f564a4": "仅显示前 1,024 列。查看源码或保存文件时会保留所有列。", "2a6e1b1f209c3888": "此文件为空。", "192fc79eb3b5b2cb": "此图表包含资源 URL、标记、节点元数据或自定义配置。请显示 Mermaid 源码以安全查看。", @@ -5810,7 +5864,6 @@ "0061fff77e36bd4f": "无法连接到服务器。", "04dfdd46e3dd4a2e": "出了点问题。请重试。", "084bb2d8127a508d": "已发送", - "e7c59185f8ab3987": "未发送", "77c01a15bd36d17c": "此链接已结束或无效", "e0e736810f3cbef2": "请向所有者索取新链接。每个链接只能在一个浏览器中使用。", "c3c53aa46f7330e5": "此链接已结束", @@ -8845,6 +8898,12 @@ "d3866ead082d14e5": "添加快捷键", "d4345c90894a3220": "打开 keybindings.json", "e56a8d51219efaa0": "没有匹配的快捷键。", + "90a258fff61fd77e": "关闭", + "4060244a7079a0d2": "当我要求时", + "e88c9d8769544731": "自动", + "f29d1dade4dde8aa": "智能体不会向 T3 团队发送反馈。", + "93c4c53562d30a98": "当你要求时,智能体会向你展示一份关于 T3 Code 的简短报告,经你批准后发送给 T3 团队。", + "cd9ee803e8727017": "智能体还会主动报告自己遇到的 T3 Code 问题,例如 T3 工具运行失败。", "45fa271ea0e1ac8e": "测试版", "3a678332fc7142f7": "将侧边栏会话按项目文件夹分组。置顶会话保留在顶部,已暂缓和已收尾会话显示在文件夹下方。", "e4e91d155cb6a9b4": "简洁侧边栏(按项目分组)", @@ -8853,11 +8912,16 @@ "9ae293971d93c819": "与访客共享会话,访客可在浏览器中实时查看,并发送需要你批准的消息。登录 T3 Connect 后即可使用访客链接。", "0aa5406ac4d7f7c7": "访客链接", "f0e853acd2006d53": "关联环境", + "ef10c2dff987f3ea": "从此服务器 T3 主目录下 workflows 文件夹中的文件运行多步骤工作流。可从命令面板打开。关闭期间,该文件夹中的内容都不会运行;运行会等到重新开启后继续。", + "2dadb2359422121c": "工作流", "13e86eb5d8287a71": "Claude 或 Codex 完成一轮回复后,在空输入框中预测下一条消息。按 Tab 使用它。每次预测都会在你的套餐上产生一次额外的缓存请求。需要 Codex 0.165+。Claude 会话在重启后更新。", "d4b2a2ec812aafb0": "建议下一条提示词", "298c7150a7621c80": "Simlock 设备主机", "67937aa49179285e": "在 Mac 上,从缓存在 T3 主目录中的工作副本克隆新的工作树,无需逐个写入每个文件。无法使用时改为 Git 的常规检出。关闭后会删除缓存。", "f9904f78d3003f58": "快速创建工作树", + "9c2f647882522302": "所选机器使用的智能体反馈模式不同。", + "31bbf7bf8c0a5279": "智能体反馈", + "d52b3d6bf9f2a013": "各不相同", "ec7623deed751c05": [ "与访客共享会话,访客可在浏览器中实时观看并发送需经你批准的消息。需要 T3 Connect:请登录并在", " ", @@ -8941,7 +9005,9 @@ "fb71127e5746a6bc": "从远端“共享与访问”页面或 t3 pair 获取", "1e3fee7084791773": "同时将 {target} 反向关联到 {source}", "ea34a190b0bd804c": "之后 {target} 上的智能体也能在 {source} 上工作。", - "ad5ed0ce61b966eb": "忘记 {label}?此处的智能体将停止在那里工作。在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", + "974f8c65e8b5f492": "忘记 {label}?此处的代理将不再在那里工作;如果 {label} 有响应,它们在那里的会话也会结束。", + "6cf9e3083b15614f": "{label} 没有响应", + "34ccbdf619b83be3": "在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", "81c9796bf61b306a": "无法移除关联", "130e51beb6cf5aad": "关联环境", "122c3e355699e69d": "这里的智能体随后就能在该环境中启动会话、发送消息并等待结果。此连接将显示在该环境“共享与访问”的“已授权客户端”中,可在那里撤销。", @@ -9171,7 +9237,6 @@ "0b4779a1825c85bc": "此项目组在侧边栏和会话列表中共用的名称。", "f68cbda4df83d739": "重置项目名称为默认值", "56e37b85027e8431": "项目图标", - "e88c9d8769544731": "自动", "c99736317da5b1fa": "重置项目图标为默认值", "6afaa3e3739dc570": "选择项目图标", "51651ce45d481a20": "选择项目图标文件", @@ -10143,7 +10208,6 @@ "a0eb0e4f76608833": "优先打开关联的 pull request;否则在改动至少 3 个文件或 50 行时打开“改动”面板。", "16bdc70b858c223f": "重置主动面板为默认值", "3e99c5c14f4939c8": "重置压缩空闲会话为默认值", - "d52b3d6bf9f2a013": "各不相同", "cd72fe451ba0d6aa": "新项目", "394c3bd0a1782c8e": "留空时,“添加项目”浏览器从“~/”打开。", "f9b912a818bd869d": "重置添加项目基础目录为默认值", @@ -11051,7 +11115,6 @@ "4a237f41ce592b7f": "保留此项目的工作树,直到你手动删除。", "00b8ffd8ea6e6a93": "此项目使用以下规则。", "72c279824d15a999": "使用各机器的工作树清理设置。", - "90a258fff61fd77e": "关闭", "b5702d0b64866b08": "自定义", "c009c901f3eefe78": "删除会话时删除工作树", "431c7cd6d50102b7": "删除活跃或已归档会话时,移除不再使用的工作树。保留有本地改动的工作树。", @@ -11750,7 +11813,6 @@ "4c70e3e7b3e6c493": "凭据", "79b768229c9ef672": "维护", "54b188d65247e42f": "实验功能", - "f41ea186c275b56e": "关于", "af4b7734da1d5ce7": "语音", "4ec62c39ca3192bf": "版本控制与 issue", "f2bf529f85e05494": "共享与访问", @@ -11805,6 +11867,7 @@ "d443390c4d2dcfd4": "无障碍 a11y 屏幕阅读器 nvda jaws voiceover orca 讲述人 窗口标题 标签页标题 alt tab 任务栏 会话状态 顺序 运行中 批准", "6826fa9579c22035": "测试版 共享 访客 邀请 链接 队友 观看 t3 connect 隧道", "f10c06cba0cdf7fe": "测试版 关联 另一台机器 vps 对等 智能体 在那里工作 委派", + "bc0b409d89ce086e": "测试版 工作流 workflow 持久 运行 自动化 步骤 计划 webhook 文件夹", "4a21cf825a2045b0": "测试版 tab 自动补全 预测 下一条消息 claude codex 幽灵文本", "fea2dc36585c4a20": "Simlock 设备主机(早期测试)", "9d834d178130180e": "测试版 alpha simlock callstack 模拟器 ios android 池 租用 网关", @@ -11876,6 +11939,7 @@ "901a823214edc8c4": "遥测 分析 用量数据 跟踪 法律 退出", "82136480255a5106": "OTel OTLP 遥测 导出 端点 日志 追踪 指标 Grafana", "659d081051faf7ff": "日志 追踪 进程 资源历史 失败 span cpu 内存", + "5eaeacfa9f82051a": "报告 错误 问题 t3 团队 发送 反馈 智能体 工具 自动 当我要求时", "f537f91e1ee41d47": "键盘 快捷键 热键 命令 绑定 json", "1ba01e7ceed64b95": "窗口 捕获 截图", "279b1cceb779ff38": "包含应用文本", @@ -12346,7 +12410,6 @@ "0bd41ff995d36a66": "缓存读取", "3f0dfe0cb15a3272": "缓存写入", "1c9d860be42b1c02": "输出", - "78344b60f407928e": "其他", "684e516076de81fe": "标准", "3bbcc1b826fef537": "快速", "66796576034c18ea": "极速", @@ -12362,6 +12425,255 @@ "2cddd6095abc734a": "7 天", "53493056306708cf": "30 天", "c719359d18d37ad3": "90 天", + "0bd950151ddc6407": "不保存就离开?对此文件的更改将丢失。", + "c0ba3f6756b09f30": "未保存的更改", + "6914e22d357f0ad6": "已保存并生效", + "aff389354a031d6f": "磁盘上的文件无法加载。上一个可加载的版本会继续运行。", + "858effde748ab563": "已保存,但尚未运行。", + "ddb37138df660942": "未保存。服务器上没有任何更改。", + "6ef4db489e40e39e": "无法保存", + "c89624a2e9af1793": "{name} 未连接", + "b5a352a43adb4c17": "重新连接后,它的工作流会再次显示。选择其他环境可查看其运行。", + "3dcedb736d20aae5": "无法读取工作流文件", + "b09f4df8d76ae8ea": "要删除 {file} 吗?它定义的工作流将无法再启动。", + "b4535f5a03689d27": "{name} 未连接。你在这里写的内容会保留,重新连接后即可保存。", + "b54c78d85fd942ea": "已删除,但正在运行的内容尚未更新。", + "407c228d7da0b7df": "未删除。服务器上没有任何更改。", + "1a6aa10f3cc14fff": "这些文件彼此不匹配。之前的版本会继续运行。", + "259312516a1dbe6f": "文件名", + "2f48ab2aa0586853": "未定义任何工作流", + "ba5adfa37b55b8c5": [ + "第 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 行:" + ], + "d94eb9ab3201b641": "删除", + "84c900d1ae72adc6": "保存", + "5912d817be03247a": "编辑期间磁盘上的文件发生了变化。保存会覆盖该变化。", + "0b1e6f5608826387": "加载该文件并放弃我的更改", + "f47b4c06aeb77c1c": "正在加载工作流文件…", + "4353bfd401d58f87": [ + { + "t": "code", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + " ", + "中的每个文件都定义工作流。修改后无需重启即可生效。" + ], + "0c165251a06f10f1": "新建文件", + "8e97cf734b4463e7": "创建", + "2ec0d5108fd6cebe": "还没有工作流。在这里创建第一个文件,或让智能体在该文件夹中编写一个。", + "5601350626e8cfe9": "无法加载", + "21d778a1b9a0c234": "在运行旁打开的内容", + "62dc4d3a19ff7ca0": "关闭标签页", + "1e25265f2758fce3": "作为完整会话打开", + "672a3dae06b39402": "在单独的页面打开", + "7755500a4cde5066": "关闭面板", + "b8dcbc93a2ca1861": "此运行不再列出它。", + "115c69de3202f664": "打开", + "644eafa9048b62df": "{count, plural, =1 {第 1 次尝试} =2 {第 2 次尝试} =3 {第 3 次尝试} other {第 {count} 次尝试}}", + "e39f89c909df4db0": "无法继续此运行", + "865f034346b82f47": "要取消 {title} 吗?其智能体将停止,且此运行无法再继续。", + "6bc75632fd9c9136": "无法取消此运行", + "64e50329dcfdd5b0": "已完成", + "350162e7cc1ebea4": "已停止", + "0875cf506f4c6810": "已跳过", + "3cc43f1dbf3f8e0c": "已取消", + "ded70e75de6404ba": "返回运行列表", + "2f4ed7dbd22be30d": "取消运行", + "614e5ad58a795fb5": "停止", + "04b050b0329f0ac8": "用时 {duration}", + "aff78e1774818ff4": "已用时 {duration}", + "38eddd466439afc9": "此运行涉及的内容", + "156ec271d49ddd70": "经过", + "34f59bbbead0b97f": "{names} 等另外 {count} 个", + "ac1556f6ce89a5ea": "{count} 个并行", + "e197c4963bacc746": "{count} 个运行中", + "f5319ed9e18c0df1": "向你提问", + "882a25e9084ae1b2": "已暂停", + "9a03d8a9afc60387": "目前的步骤", + "2f2ae791afe01674": "等待你的批准", + "24f8060c4ccdf928": "正在启动", + "30a5be40eb956663": "工作中", + "dd7a1e58c2553933": "{duration} 后唤醒", + "95cc952724dd7310": "即将唤醒", + "3cc34921c0128593": "运行中", + "e777db2880f53a46": "无人回答", + "dc90739d391a5e67": "你的回答:{choice}", + "389f2563b5b763fd": "快速步骤", + "a41c8d758121ad81": "已休眠", + "9db248b770096984": "已等待", + "c76124517af28686": "已运行 {duration}", + "89102905bf09b0e8": "实时查看", + "bdf338cdff4118f0": "对话记录", + "811e7e992f9ff820": "需重新注册其工作流版本后才能继续", + "4d4cdf035e98dd57": "等你手动继续", + "eb5b21dd224a5941": "{duration} 后自动重试", + "6ab3dfa749fde477": "即将自动重试", + "44b6463aa70aa14c": "暂停原因", + "cf25e7169ab0eb7a": "暂停于 {step}", + "56c48c1f220f2754": "无法回答此问题", + "a3c43735e1a81498": "{title} 的理由", + "bfad234f016cfa3f": "用一句话说明理由。无论你选哪个回答,它都会一并附上。", + "004c41aff9c97873": "运行", + "4dc0c244a2419f6c": [ + "属于 ", + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + } + ], + "8c303e8335acb135": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "开始" + ], + "8bffb377e2a6a7de": "其版本已不再注册", + "f92d9132f7b85d1a": "正在加载步骤…", + "6ebc59f64c761a49": "暂无内容。", + "a759dccd157d7dae": [ + "你的回答:", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + } + ], + "593b425188346781": [ + "你的回答:", + { + "t": "span", + "i": 1, + "c": { + "i": 2, + "k": "_gt_value_2", + "v": "v" + } + }, + ":", + { + "i": 3, + "k": "_gt_value_3", + "v": "v" + } + ], + "c98009be9a273b31": "打开运行", + "c8eb9be36d4d51ad": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + " 上的会话" + ], + "3d9761e81798fcd8": "继续", + "8cebd63fc4c967d5": "只会重新运行失败的步骤;此前已完成的内容会保留。", + "bc1e0a2a0f1e9552": "等你处理", + "a812f51e970740f1": [ + { + "i": 1, + "k": "_gt_value_1", + "v": "v" + }, + "提问", + " ", + "· 运行正在等你回答" + ], + "02dfe6c63fd0b8a1": "添加理由", + "19abd94828a3bdbc": "先问问智能体", + "a18721fa8f328361": "等你处理", + "bbf24e7920c1e86b": "运行中", + "8d6e18d2ad832db6": "全部", + "f25af5332ffc3734": "没有等你处理的内容。", + "c3f0119b8d6231f8": "没有正在运行的内容。", + "33028dfc1229eaa6": "还没有运行。", + "5459bf696a187c26": "无法加载工作流运行", + "d57c35d43b0f163a": "此运行不在这里", + "b9aae2f7cdb1a379": "还没有工作流运行", + "8f15f66e545af7c0": "显示哪些运行", + "b6409289e0c9a4dd": "工作流", + "035cb02ca1ae4952": "全部 {count} 个工作流", + "46d614fa7b4bf1e5": "工作流运行", + "1c635faa2fb45b8b": "尚未运行过。", + "156ff7b625287a1e": "隐藏已跳过", + "69b985b97ab45e6b": "显示 {count} 个已跳过", + "2400254d362de84d": "正在加载工作流运行…", + "145e1f7503ba3b2c": [ + "此环境中没有该链接对应的运行。", + " ", + { + "t": "button", + "i": 1, + "c": "返回运行列表" + } + ], + "783e616cb0476c17": [ + "工作流将智能体、代码、定时计划和向你提出的问题串联成一次重启后仍会继续的运行。可在", + " ", + { + "t": "button", + "i": 1, + "c": "定义" + }, + " ", + "中编写,或让智能体代写。", + " ", + { + "t": "a", + "i": 2, + "c": "阅读指南" + } + ], + "cae5c3205c01d062": [ + { + "t": "span", + "i": 1, + "c": "有工作流文件存在问题。" + }, + "上一个可加载的版本会继续运行。" + ], + "ed8ce6ebc73dc12d": "打开文件", + "5d8d278ff828102d": "全部工作流", + "39459da07479f482": "智能体", + "7741243632056b81": "{step} · 记录", + "c512071143a5ba32": "此会话已不存在。", + "ed169d23683fb6ac": "正在加载会话…", + "290e0ab40b87dc17": "工作流面包屑导航", + "683dd9831e54edc0": "环境", + "34ad53646f06ed80": "工作流已关闭", + "8f6589c9e0ac5d4e": "未连接任何环境", + "744127f8dfad7d22": "连接一个环境以查看其工作流运行。", + "036182ec7e2ee4d4": "运行旁", + "2d6107cb78382d08": "工作流", + "16f7df687349b399": "定义", + "f0a212aadfe1257b": "正在加载编辑器…", + "20f194e003885e95": [ + "在此服务器的", + " ", + { + "t": "Link", + "i": 1, + "c": "设置 → Labs" + }, + " 中开启。" + ], "8367779e149f723b": "主环境请求在 {operation} 期间失败(HTTP {status})。", "c5cd027743a2b5a6": "配对 token 无效。请检查后重试。", "0e4b49c8203aae81": "引导完成后等待登录状态超时。", @@ -12483,6 +12795,8 @@ "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", "9e91e9a77b664e4e": "无法开始生成审查导览", - "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", - "425ab15036aec8a4": "将此命令移到队列最前面" + "99d51127f573296b": "其他账号", + "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", + "99963c0142e17f00": "用于新的 {tracker} 账号。", + "6d8e4ebc889bace9": "添加账号" } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index e88ca7caf122c..f864b6f0d4970 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -231,6 +231,10 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil --animate-stash-pulse-row: stash-pulse-row 1400ms; --animate-stash-pulse-row-alt: stash-pulse-row-alt 1400ms; --animate-stash-pulse-count: stash-pulse-count 1400ms step-start; + /* One-off arrivals in a workflow run's timeline; nothing here loops. */ + --animate-step-in: step-in 180ms ease-out; + --animate-step-ping: step-ping 520ms ease-out; + --animate-check-draw: check-draw 200ms ease-out; --color-warning-foreground: var(--warning-foreground); --color-warning: var(--warning); --color-warning-surface: var(--warning-surface); @@ -345,6 +349,27 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil opacity: 1; } } + @keyframes step-in { + from { + opacity: 0; + translate: 0 4px; + } + } + @keyframes step-ping { + from { + opacity: 0.55; + scale: 0.7; + } + to { + opacity: 0; + scale: 1.45; + } + } + @keyframes check-draw { + from { + stroke-dashoffset: 12; + } + } @keyframes status-ping { /* Burst first (immediate feedback for click ripples), then hold invisible for the rest of the cycle. Mirrors animate-ping's @@ -1889,10 +1914,6 @@ code { margin: 0.65rem 0; } -.chat-markdown-math-display .katex-display { - margin: 0; -} - :is(.chat-markdown, .composer-tiptap) h1, :is(.chat-markdown, .composer-tiptap) h2, :is(.chat-markdown, .composer-tiptap) h3, @@ -2314,6 +2335,15 @@ code { overflow-wrap: break-word; } +.chat-markdown [data-markdown-math] { + font-weight: normal; + font-style: normal; +} + +.chat-markdown [data-markdown-math] > svg { + font-size: 1.21em; +} + /* Formula cells keep their natural width and scroll with the table. */ .chat-markdown :is(th, td):has([data-markdown-math]) { max-width: none; diff --git a/apps/web/src/lib/chunkReloadGuard.ts b/apps/web/src/lib/chunkReloadGuard.ts index c4b41e6ef3f36..ba8f7f102ed4a 100644 --- a/apps/web/src/lib/chunkReloadGuard.ts +++ b/apps/web/src/lib/chunkReloadGuard.ts @@ -1,5 +1,3 @@ -import { chunkReloadBuild } from "../fork/chunkReloadBuild"; - // Deploys and desktop server swaps can invalidate lazy chunks; one reload fetches the fresh index. // Keyed by build and kept across boots: a chunk loaded after boot can fail on every visit. const CHUNK_RELOAD_GUARD_KEY = "t3code:chunk-load-reloaded"; @@ -36,3 +34,26 @@ export function isChunkLoadError(error: unknown): boolean { message !== undefined && CHUNK_LOAD_ERROR_PREFIXES.some((prefix) => message.startsWith(prefix)) ); } + +export const chunkLoadState = { reloadScheduled: false }; + +// Registered from the entry before main loads, so main-chunk and route-chunk failures share one decision. +export function handleChunkLoadErrors() { + window.addEventListener("vite:preloadError", (event) => { + if (reloadOnceForChunkLoadError()) { + chunkLoadState.reloadScheduled = true; + event.preventDefault(); + } + }); +} + +// The bundler's entry hash covers the hashed names it imports, so any changed chunk renames the entry. +function chunkReloadBuild(): string { + if (typeof document === "undefined") return import.meta.env.APP_VERSION; + const buildAssetPrefix = `${import.meta.env.BASE_URL}assets/`; + const entryPath = Array.from( + document.querySelectorAll('script[type="module"][src]'), + (script) => script.getAttribute("src")?.split(/[?#]/, 1)[0], + ).find((path) => path?.startsWith(buildAssetPrefix)); + return entryPath ?? import.meta.env.APP_VERSION; +} diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts index 31b7239719f1a..6f1c9d3bb8227 100644 --- a/apps/web/src/lib/composerContextRecords.ts +++ b/apps/web/src/lib/composerContextRecords.ts @@ -9,6 +9,8 @@ import { COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, } from "@t3tools/contracts"; import type { + ChatFileAttachment, + ChatImageAttachment, ComposerContextId, ComposerContextRecord, EnvironmentContextRecord, @@ -488,39 +490,59 @@ export function fileContextReference(file: ComposerFileAttachment): ComposerCont }; } +export type ComposerContextAttachment = + | ComposerImageAttachment + | ComposerFileAttachment + | (Omit & { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; + }) + | ChatImageAttachment + | ChatFileAttachment; + export interface BoundComposerAttachment { - attachment: ComposerImageAttachment | ComposerFileAttachment; + attachment: ComposerContextAttachment; attachmentId: string; + contextId?: ComposerContextId | undefined; } /** Returns null until the attachment has a server id. */ export function uploadedAttachmentContextRecord( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: ComposerContextAttachment, upload: AttachmentUploadState | undefined, + contextId?: ComposerContextId, ): ImageContextRecord | FileContextRecord | null { const attachmentId = - attachment.type === "file" && attachment.uploadedAttachmentId !== undefined + "uploadedAttachmentId" in attachment && attachment.uploadedAttachmentId !== undefined ? attachment.uploadedAttachmentId : upload?.status === "ready" ? upload.attachmentId : undefined; - return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId }); + return attachmentId === undefined + ? null + : attachmentContextRecord({ attachment, attachmentId, contextId }); } export function attachmentContextRecord( bound: BoundComposerAttachment, ): ImageContextRecord | FileContextRecord { - const { attachment, attachmentId } = bound; + const { attachment, attachmentId, contextId } = bound; const base = { version: 1 as const, - contextId: toKindScopedComposerContextId(attachment.type, attachment.id), + contextId: contextId ?? toKindScopedComposerContextId(attachment.type, attachment.id), label: sanitizeComposerContextLabel(attachment.name, attachment.type), attachmentId, name: attachment.name, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, }; - return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" }; + return attachment.type === "image" + ? { + ...base, + kind: "image", + ...(attachment.source !== undefined ? { source: attachment.source } : {}), + } + : { ...base, kind: "file" }; } export function buildMessageContext(input: { diff --git a/apps/web/src/lib/discardComposerDraft.test.ts b/apps/web/src/lib/discardComposerDraft.test.ts index 6c63482dfe52b..340ed6b2606e3 100644 --- a/apps/web/src/lib/discardComposerDraft.test.ts +++ b/apps/web/src/lib/discardComposerDraft.test.ts @@ -80,6 +80,23 @@ describe("discardComposerDraft", () => { } }); + it("discards and restores a draft session that has no composer record", async () => { + useComposerDraftStore.getState().setProjectDraftThreadId(projectRef, draftId); + const before = useComposerDraftStore.getState(); + expect(before.draftsByThreadKey).toEqual({}); + + discardComposerDraft(draftId); + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); + + await undoNotice().undo(); + const after = useComposerDraftStore.getState(); + expect(after.getDraftSession(draftId)).toEqual(before.getDraftSession(draftId)); + expect(after.draftsByThreadKey).toEqual({}); + expect(after.logicalProjectDraftThreadKeyByLogicalProjectKey).toEqual( + before.logicalProjectDraftThreadKeyByLogicalProjectKey, + ); + }); + it("releases a discarded existing-thread preview when Undo is committed", async () => { using preview = imagePreview(); useComposerDraftStore.getState().addImage(threadRef, preview.image); diff --git a/apps/web/src/lib/discardComposerDraft.ts b/apps/web/src/lib/discardComposerDraft.ts index bd52b0a02879f..f1847a737dc0a 100644 --- a/apps/web/src/lib/discardComposerDraft.ts +++ b/apps/web/src/lib/discardComposerDraft.ts @@ -19,8 +19,9 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { const store = useComposerDraftStore.getState(); const key = resolveComposerDraftKey(store, target); const draft = key === null ? undefined : store.draftsByThreadKey[key]; - if (key === null || !draft) return; + if (key === null) return; const session = store.draftThreadsByThreadKey[key]; + if (!draft && !session) return; const logicalProjectKeys = Object.entries(store.logicalProjectDraftThreadKeyByLogicalProjectKey) .filter(([, draftKey]) => draftKey === key) .map(([logicalProjectKey]) => logicalProjectKey); @@ -38,6 +39,7 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { } const releaseDiscardedDraft = () => { + if (!draft) return; releaseDraftAttachments([...draft.images, ...draft.files]); // Draft-session removal already revoked these previews. if (!discardsSession) { @@ -65,19 +67,21 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { logicalProjectDraftThreadKeyByLogicalProjectKey[logicalProjectKey] ??= key; } return { - draftsByThreadKey: { - ...state.draftsByThreadKey, - [key]: discardsSession - ? { - ...draft, - images: draft.images.map((image) => - image.previewUrl.startsWith("blob:") - ? { ...image, previewUrl: URL.createObjectURL(image.file) } - : image, - ), - } - : draft, - }, + draftsByThreadKey: draft + ? { + ...state.draftsByThreadKey, + [key]: discardsSession + ? { + ...draft, + images: draft.images.map((image) => + image.previewUrl.startsWith("blob:") + ? { ...image, previewUrl: URL.createObjectURL(image.file) } + : image, + ), + } + : draft, + } + : state.draftsByThreadKey, draftThreadsByThreadKey: session ? { ...state.draftThreadsByThreadKey, [key]: session } : state.draftThreadsByThreadKey, diff --git a/apps/web/src/lib/pageTranslationGuard.browser.test.tsx b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx new file mode 100644 index 0000000000000..40d7e7597ccf8 --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { guardDomAgainstPageTranslation } from "./pageTranslationGuard"; + +// What Chrome's page translator does: swap each text node for translation. +function translatePage(root: Element) { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const textNodes: Text[] = []; + while (walker.nextNode()) textNodes.push(walker.currentNode as Text); + for (const text of textNodes) { + if (!text.nodeValue?.trim()) continue; + const outer = document.createElement("font"); + const inner = document.createElement("font"); + inner.textContent = `译:${text.nodeValue}`; + outer.append(inner); + text.replaceWith(outer); + } +} + +function Status({ running }: { running: boolean }) { + return ( +
    + {running ? "Working" : } + {"for 2s"} +
    + ); +} + +describe("guardDomAgainstPageTranslation", () => { + it("keeps React committing after page translation replaced its text nodes", async () => { + guardDomAgainstPageTranslation(); + await using screen = await render(, { router: false }); + translatePage(screen.container); + + // Removing "Working" hits removeChild; placing the icon before "for 2s" hits insertBefore. + await screen.rerender(); + await expect.element(screen.getByTestId("done")).toBeInTheDocument(); + await screen.rerender(); + await expect.element(screen.getByTestId("done")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/lib/pageTranslationGuard.ts b/apps/web/src/lib/pageTranslationGuard.ts new file mode 100644 index 0000000000000..de8dbceb8e2bf --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.ts @@ -0,0 +1,20 @@ +// Browser page translation (Chrome, Edge) swaps text nodes for wrappers React does not +// know about, so a later removeChild or insertBefore on the original node throws NotFoundError +// and takes down the whole tree. See facebook/react#11538. +export function guardDomAgainstPageTranslation(): void { + const proto = Node.prototype; + const removeChild = proto.removeChild; + const insertBefore = proto.insertBefore; + + proto.removeChild = function (this: Node, child: T): T { + // Already detached by the translator: nothing left to remove. + if (child.parentNode !== this) return child; + return removeChild.call(this, child) as T; + }; + + proto.insertBefore = function (this: Node, node: T, reference: Node | null): T { + // The anchor was replaced; append so the new node still shows. + const anchor = reference && reference.parentNode !== this ? null : reference; + return insertBefore.call(this, node, anchor) as T; + }; +} diff --git a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx index 981beeafdfd38..f93c53aff89fd 100644 --- a/apps/web/src/lib/resourceTelemetryState.browser.test.tsx +++ b/apps/web/src/lib/resourceTelemetryState.browser.test.tsx @@ -173,6 +173,7 @@ function setup({ retryFails = false, holdRetry = false } = {}) { const registry = AtomRegistry.make(); return { registry, + snapshot, historyQueries, historyReads, releaseRetry, @@ -265,4 +266,48 @@ describe("resource monitor retry", () => { await expect.element(screen.getByText(startError, { exact: true })).toBeVisible(); await expect.element(screen.getByText(historyError, { exact: true })).toBeVisible(); }); + + it("stops showing refresh as pending after the first live snapshot arrives", async () => { + using fixture = setup(); + const liveTelemetry = Atom.make< + AsyncResult.AsyncResult + >(AsyncResult.initial(true)).pipe(Atom.keepAlive); + monitor.telemetry.mockImplementation(() => liveTelemetry); + + await using screen = await render( + + + , + ); + const refreshButton = screen.getByRole("button", { name: "Refresh resource telemetry" }); + await expect.element(refreshButton).toBeDisabled(); + + await act(() => { + fixture.registry.set( + liveTelemetry, + AsyncResult.waiting(AsyncResult.success(fixture.snapshot)), + ); + }); + await expect.element(refreshButton).toBeEnabled(); + }); + + it("stops showing refresh as pending after a live subscription error", async () => { + using fixture = setup(); + const liveTelemetry = Atom.make< + AsyncResult.AsyncResult + >(AsyncResult.waiting(AsyncResult.fail(new MonitorError({ message: startError })))).pipe( + Atom.keepAlive, + ); + monitor.telemetry.mockImplementation(() => liveTelemetry); + + await using screen = await render( + + + , + ); + await expect.element(screen.getByText(startError, { exact: true })).toBeVisible(); + await expect + .element(screen.getByRole("button", { name: "Refresh resource telemetry" })) + .toBeEnabled(); + }); }); diff --git a/apps/web/src/lib/resourceTelemetryState.ts b/apps/web/src/lib/resourceTelemetryState.ts index 5105195d41e28..1fe63398c95b7 100644 --- a/apps/web/src/lib/resourceTelemetryState.ts +++ b/apps/web/src/lib/resourceTelemetryState.ts @@ -60,7 +60,9 @@ export function useResourceTelemetry( return result.value.snapshot; }; - return { ...query, retry }; + // The live subscription keeps waiting for updates after its first snapshot. + const isPending = query.isPending && query.data === null && query.error === null; + return { ...query, isPending, retry }; } export function useResourceTelemetryHistory( diff --git a/apps/web/src/lib/t3ProjectFileDefaults.ts b/apps/web/src/lib/t3ProjectFileDefaults.ts index b5000b4ddd92f..a780a1d906cdb 100644 --- a/apps/web/src/lib/t3ProjectFileDefaults.ts +++ b/apps/web/src/lib/t3ProjectFileDefaults.ts @@ -1,6 +1,12 @@ -import { T3_PROJECT_FILE_NAME, type EnvironmentId, type T3ProjectFile } from "@t3tools/contracts"; +import { + T3_PROJECT_FILE_NAME, + type EnvironmentId, + type ProjectReadFileResult, + type T3ProjectFile, +} from "@t3tools/contracts"; import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile"; import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; +import { AsyncResult } from "effect/reactivity"; import { getProjectFileQueryAtom, @@ -8,6 +14,21 @@ import { } from "~/components/files/projectFilesQueryState"; import { appAtomRegistry } from "~/rpc/atomRegistry"; +function toT3ProjectFile( + environmentId: EnvironmentId, + workspaceRoot: string, + result: ProjectReadFileResult | null, +): T3ProjectFile | null { + const data = resolveProjectFileQueryData( + environmentId, + workspaceRoot, + T3_PROJECT_FILE_NAME, + result, + ); + if (data === null || data.exists === false || data.truncated) return null; + return parseT3ProjectFile(data.contents); +} + export async function readT3ProjectFile( environmentId: EnvironmentId, workspaceRoot: string, @@ -17,12 +38,22 @@ export async function readT3ProjectFile( getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME), { reportDefect: false, reportFailure: false }, ); - const data = resolveProjectFileQueryData( + return toT3ProjectFile( environmentId, workspaceRoot, - T3_PROJECT_FILE_NAME, result._tag === "Success" ? result.value : null, ); - if (data === null || data.exists === false || data.truncated) return null; - return parseT3ProjectFile(data.contents); +} + +/** The project's t3.json from an earlier read, or `undefined` when none has loaded yet. */ +export function peekT3ProjectFile( + environmentId: EnvironmentId, + workspaceRoot: string, +): T3ProjectFile | null | undefined { + const result = appAtomRegistry.get( + getProjectFileQueryAtom(environmentId, workspaceRoot, T3_PROJECT_FILE_NAME), + ); + return AsyncResult.isSuccess(result) + ? toT3ProjectFile(environmentId, workspaceRoot, result.value) + : undefined; } diff --git a/apps/web/src/main.test.ts b/apps/web/src/main.test.ts index 68544483cd443..8ea2aba1fd165 100644 --- a/apps/web/src/main.test.ts +++ b/apps/web/src/main.test.ts @@ -5,7 +5,7 @@ vi.mock("./AppRoot", () => ({ AppRoot: () => null })); vi.mock("./i18n/runtime", () => ({ whenLocaleReady: async () => {} })); vi.mock("react-dom/client", () => ({ default: { createRoot: () => ({ render: () => {} }) } })); -// Boots main in a fresh page that shares the tab's sessionStorage, as a reload does. +// Boots the entry in a fresh page that shares the tab's sessionStorage, as a reload does. async function bootThenFailLazyChunk(sessionStorage: Map) { vi.resetModules(); const reload = vi.fn().mockName("location.reload"); @@ -21,8 +21,8 @@ async function bootThenFailLazyChunk(sessionStorage: Map) { const entry = { getAttribute: () => "/assets/index-A.js" }; vi.stubGlobal("document", { getElementById: () => ({}), querySelectorAll: () => [entry] }); try { - const { startup } = await import("./main"); - await startup; + const { boot } = await import("./bootstrap"); + await boot; page.dispatchEvent(new Event("vite:preloadError", { cancelable: true })); return reload; } finally { diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 112de4848170c..51aeeade6863d 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -9,20 +9,12 @@ import { isElectron } from "./env"; import { startAppServices } from "./appInit"; import { AppRoot } from "./AppRoot"; import { whenLocaleReady } from "./i18n/runtime"; -import { reloadOnceForChunkLoadError } from "./lib/chunkReloadGuard"; +import { chunkLoadState } from "./lib/chunkReloadGuard"; const router = startAppServices(); const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined; -let reloadScheduled = false; -window.addEventListener("vite:preloadError", (event) => { - if (reloadOnceForChunkLoadError()) { - reloadScheduled = true; - event.preventDefault(); - } -}); - const app = ; // Split by runtime to keep Clerk out of local startup and clerk-js out of browser builds. @@ -40,7 +32,7 @@ export const startup = Promise.all([ ]) .then(([ManagedAuthShell]) => { // Route chunk failures resolve router.load() and surface later through the error boundary. - if (reloadScheduled) return; + if (chunkLoadState.reloadScheduled) return; ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( {ManagedAuthShell && clerkPublishableKey ? ( @@ -52,6 +44,6 @@ export const startup = Promise.all([ ); }) .catch((error: unknown) => { - if (reloadScheduled) return; + if (chunkLoadState.reloadScheduled) return; throw error; }); diff --git a/apps/web/src/markdown-clipboard.test.ts b/apps/web/src/markdown-clipboard.test.ts index 1b0aa804a8437..7a50785c726c7 100644 --- a/apps/web/src/markdown-clipboard.test.ts +++ b/apps/web/src/markdown-clipboard.test.ts @@ -11,19 +11,27 @@ import { collectAssistantCitations, serializeAssistantCitation, } from "@t3tools/shared/assistantCitations"; -import { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; +import type { Element as HastElement, ElementContent, Root } from "hast"; -import { unified } from "unified"; -import remarkParse from "remark-parse"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_USER_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { markdownTree } from "./markdown/wordsHast"; -const userMarkdown = unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS); +// Copied Markdown read back as the chat reads it, to check it says what was copied. +const elementsOf = (node: Root | HastElement) => + (node.children as ElementContent[]).filter( + (child): child is HastElement => child.type === "element", + ); +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; +const readBack = (markdown: string, options?: Parameters[1]) => + elementsOf(markdownTree(markdown, options))[0]!; +// A user message's reading: a single `~` stays text. +const readUserBack = (markdown: string) => readBack(markdown, { singleTilde: false }); +const inline = (node: ElementContent) => + node.type === "element" ? [node.tagName, textOf(node)] : [node.type, textOf(node)]; const TEXT_NODE = 3; const ELEMENT_NODE = 1; @@ -223,10 +231,10 @@ describe("serializeRenderedMarkdownFragment", () => { new FakeText(" here."), ), ); - const paragraph = parseMarkdownWithMath(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children.find((child) => child.type === "inlineCode")?.value).toBe(value); + const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container))); + const code = elementsOf(paragraph).find((child) => child.tagName === "code"); + expect(paragraph.tagName).toBe("p"); + expect(code && textOf(code)).toBe(value); }); it.each([ @@ -238,28 +246,24 @@ describe("serializeRenderedMarkdownFragment", () => { String.raw`before\ after\ end`, ])("copies prose that parses back unchanged: %s", (value) => { const container = new FakeElement("DIV").append(new FakeText(value)); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ type: "paragraph", children: [{ type: "text", value }] }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.tagName).toBe("p"); + expect(paragraph.children.map(inline)).toEqual([["text", value]]); }); it.each([ - ["*", "EM", "word", "emphasis"], - ["\\", "CODE", "value", "inlineCode"], - ])("keeps a text edge %j beside %s", (edge, tag, value, type) => { + ["*", "EM", "word"], + ["\\", "CODE", "value"], + ])("keeps a text edge %j beside %s", (edge, tag, value) => { const container = new FakeElement("DIV").append( new FakeText(edge), new FakeElement(tag).append(new FakeText(value)), ); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ - type: "paragraph", - children: [ - { type: "text", value: edge }, - type === "inlineCode" ? { type, value } : { type, children: [{ type: "text", value }] }, - ], - }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.children.map(inline)).toEqual([ + ["text", edge], + [tag.toLowerCase(), value], + ]); }); it("copies email links with their address and drops in-app destinations", () => { @@ -288,10 +292,10 @@ describe("serializeRenderedMarkdownFragment", () => { expect(copied).toBe( "Write to support@example.com, [Support](mailto:support@example.com?subject=Help), [Support](mailto:support@example.com?subject=Help\\)) or the thread.", ); - const paragraph = parseMarkdownWithMath(copied).children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); expect( - paragraph.children.filter((child) => child.type === "link").map((link) => link.url), + elementsOf(readBack(copied)) + .filter((child) => child.tagName === "a") + .map((link) => link.properties.href), ).toEqual([ "mailto:support@example.com", "mailto:support@example.com?subject=Help", @@ -312,12 +316,14 @@ describe("serializeRenderedMarkdownFragment", () => { ])("keeps the link label and destination: %s", (label, href) => { const anchor = new FakeElement("A", [], { href }).append(new FakeText(label)); const container = new FakeElement("DIV").append(anchor); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children).toMatchObject([ - { type: "link", url: href, children: [{ type: "text", value: label }] }, - ]); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect( + paragraph.children.map((child) => + child.type === "element" + ? [child.tagName, decodeURI(String(child.properties.href)), textOf(child)] + : [child.type, textOf(child)], + ), + ).toEqual([["a", href, label]]); }); it("copies alert and insight callouts as their Markdown instead of the rendered label", () => { @@ -484,31 +490,25 @@ describe("copying rendered Markdown tables", () => { ); const markdown = serializeTableElementToMarkdown(table as unknown as Element); - const tree = parseMarkdownWithMath(markdown); - const parsed = tree.children[0]; - if (parsed?.type !== "table") throw new Error("Expected a table"); - expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]); - expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([ - "|x|", - "\\|x\\|", - "|y|", - "|z|", - ]); - expect(parsed.children[1]?.children[1]?.children).toMatchObject([ - { type: "text", value: "*a* | ~~b~~" }, - ]); - expect(parsed.children[4]?.children[1]?.children).toMatchObject([ - { type: "text", value: "> c | d" }, - ]); - const [, , codeRow, linkRow] = parsed.children; - expect(codeRow?.children[1]?.children[0]).toMatchObject({ - type: "inlineCode", - value: "\\(c|d\\)", - }); - expect(linkRow?.children[0]?.children[0]).toMatchObject({ - type: "link", - url: "https://example.com/?q=a|b", - }); + const parsed = readBack(markdown, { math: true }); + expect(parsed.tagName).toBe("table"); + const rows = elementsOf(parsed).flatMap((section) => elementsOf(section)); + const cells = rows.map((row) => elementsOf(row)); + expect(cells.map((row) => row.length)).toEqual([2, 2, 2, 2, 2]); + const formulas: string[] = []; + const visit = (node: HastElement) => { + if (node.tagName === "svg") formulas.push(String(node.properties.ariaLabel)); + else elementsOf(node).forEach(visit); + }; + visit(parsed); + expect(formulas).toEqual(["|x|", "\\|x\\|", "|y|", "|z|"]); + expect(textOf(cells[1]![1]!)).toBe("*a* | ~~b~~"); + expect(textOf(cells[4]![1]!).trim()).toBe("> c | d"); + expect(inline(cells[2]![1]!.children[0]!)).toEqual(["code", "\\(c|d\\)"]); + const link = cells[3]![0]!.children[0]!; + expect(link.type === "element" && decodeURI(String(link.properties.href))).toBe( + "https://example.com/?q=a|b", + ); }); it("copies code and diagrams in cells without markers or unescaped pipes", () => { diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts index 7421dbadd4bae..39ef90b2ec19a 100644 --- a/apps/web/src/markdown-clipboard.ts +++ b/apps/web/src/markdown-clipboard.ts @@ -1,4 +1,4 @@ -import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownWindowsPaths"; +import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownLinks"; const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]); const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"]; @@ -428,7 +428,7 @@ export function serializeTableElementToMarkdown(table: Element): string { return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim(); } -// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops +// The wrapper wordsHast puts on every formula it renders. The sanitizer drops // the attribute from authored HTML. const MATH_SELECTOR = "[data-markdown-math]"; diff --git a/apps/web/src/markdown-incremental.test.tsx b/apps/web/src/markdown-incremental.test.tsx deleted file mode 100644 index 3682deb281fa9..0000000000000 --- a/apps/web/src/markdown-incremental.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -import { CHAT_MARKDOWN_REHYPE_PLUGINS } from "@t3tools/shared/markdownPipeline"; -import type { Root } from "mdast"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkGfm from "remark-gfm"; -import type { Plugin } from "unified"; -import { describe, expect, it } from "vite-plus/test"; - -import { remarkCodexDirectives } from "@t3tools/shared/codexMarkdownDirectives"; -import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts"; -import { createIncrementalMarkdownPlugin } from "./markdown-incremental"; -import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation"; - -function render(source: string, incremental?: Plugin<[], Root>, parsedSources?: string[]) { - let tree: Root | undefined; - const observeParsing: Plugin<[], Root> = function () { - const original = this.parser; - if (original) { - this.parser = (text, file) => { - parsedSources?.push(text); - return original(text, file); - }; - } - }; - const capture: Plugin<[], Root> = () => (root) => { - tree = structuredClone(root); - }; - const html = renderToStaticMarkup( - - {source} - , - ); - return { html, tree }; -} - -const prefix = "# Before\n\n```ts\nconst values = [1, 2];\n```\n\n"; - -describe("incremental Markdown parsing", () => { - it("keeps the document prefix cached when list recovery parses contain fences", () => { - const source = - prefix + - "- first block\n\n ```ts\n const nested = 1;\n ```\n\n tail"; - const incremental = createIncrementalMarkdownPlugin(); - const parsedSources: string[] = []; - expect(render(source, incremental, parsedSources)).toEqual(render(source)); - parsedSources.length = 0; - const next = source + " more"; - expect(render(next, incremental, parsedSources)).toEqual(render(next)); - expect(parsedSources).not.toContain(next); - expect(parsedSources.some((text) => text.startsWith("t3-markdown-inline-prefix:"))).toBe(true); - }); - - it.each([ - "a\n===\n\nb\n---\n", - "- first\n\n continued\n\n- next\n", - "> quoted\n>\n> ```js\n> abc\n> ```\n\nend", - "
    \nhello\n\n
    \n\nend", - "[ref]\n\n[ref]: /later", - "a[^x]\n\n[^x]: note", - "a | b\n--|--\na | b\n", - "```\na\n```\n\nnext\n\n~~~\nb\n~~~\n\nmore", - "\n\n\tcode\n\nmore", - "text *bold*", - "> [!NOTE]\n> alert\n\n- [ ] task", - "\uFEFFtext after a byte-order mark", - ])("preserves the parse tree, positions, and HTML while streaming %j", (tail) => { - const source = prefix + tail; - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental), `prefix ${end}`).toEqual(render(text)); - } - }); - - it.each(["\r\n", "\r"])("preserves partial %j line endings", (newline) => { - const source = (prefix + "next\n\n```\nlast\n```\n\nend").replaceAll("\n", newline); - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental)).toEqual(render(text)); - } - }); - - it("updates earlier references when definitions arrive after the cached prefix", () => { - const before = "[later] and footnote[^note]\n\n" + prefix; - const incremental = createIncrementalMarkdownPlugin(); - for (const tail of ["text", "[later]: /target", "[later]: /target\n\n[^note]: a note"]) { - expect(render(before + tail, incremental)).toEqual(render(before + tail)); - } - }); - - it("handles edits, replacements, and repeated renders without leaking transformed nodes", () => { - const incremental = createIncrementalMarkdownPlugin(); - const documents = [ - prefix + "- first\n - second", - prefix + "> [!NOTE]\n> transformed alert", - prefix + "plain text", - "replacement without fences", - prefix.replace("Before", "Edited") + "edited prefix", - prefix + "plain text", - prefix + "plain text", - ]; - for (const document of documents) { - expect(render(document, incremental)).toEqual(render(document)); - } - }); - - it("does not freeze unclosed, nested, indented, or mismatched fences", () => { - const prefixes = [ - "```\nopen\n\n", - "````\n```\n\n", - "> ```\n> code\n> ```\n\n", - "- ```\n code\n ```\n\n", - " ```\n code\n ```\n\n", - " $y$', + { ...ASSISTANT, math: true }, + ), + ); + expect(html).not.toMatch(/onload|javascript|position| ReadonlyArray) | null; + }; + /** Expand GitHub `:alias:` emoji shortcodes in prose outside code. */ + readonly githubEmoji?: boolean; +} + +export interface WordsHastOptions extends ForkWordsOptions { + /** `$…$`, `$$…$$` and `math` code blocks render as SVG. */ + readonly math: boolean; + /** Soft line breaks render as `
    `, as remark-breaks does. */ + readonly breaks: boolean; + /** Raw HTML shows as the text it was written as. */ + readonly escapeHtml: boolean; + /** `★ Insight ───` blocks render as insight callouts. */ + readonly insights: boolean; + readonly extensions: MarkdownExtensions; +} + +const CODEX_DIRECTIVES = ["codex-file-citation", "codex-followup", "artifact-template"]; + +const VOID = new Set("area base br col embed hr img input link meta source track wbr".split(" ")); + +const TAG = + /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|)|]*>|<\?[\s\S]*?\?>/g; +const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g; + +// Start tags an HTML parser closes an open `

    ` for, and the elements that scope that search. +const CLOSES_PARAGRAPH = new Set( + "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split( + " ", + ), +); +const PARAGRAPH_SCOPE = new Set([ + "applet", + "caption", + "table", + "td", + "th", + "marquee", + "object", + "template", + "button", +]); + +type RenderOptions = Omit; + +const decoder = new TextDecoder(); +const encoder = new TextEncoder(); + +function renderToHtml(markdown: string, options: RenderOptions): Uint8Array { + try { + return wordsRenderToHtml(markdown, options); + } catch { + return encoder.encode( + `

    ${markdown.replaceAll("&", "&").replaceAll("<", "<").replaceAll("\n", "
    ")}

    `, + ); + } +} + +const decode = (value: string) => (value.includes("&") ? decodeHTML(value) : value); + +function properties(source: string | undefined, inSvg: boolean): Element["properties"] { + const result: Element["properties"] = {}; + if (!source) return result; + for (const match of source.matchAll(ATTRIBUTE)) { + const name = match[1]!; + const info = find(inSvg ? svgSchema : htmlSchema, inSvg ? name : name.toLowerCase()); + const raw = match[2] ?? match[3] ?? match[4]; + if (raw === undefined) { + result[info.property] = info.boolean || info.overloadedBoolean ? true : ""; + continue; + } + // Attribute values decode as attributes: `©=` in a query stays as written. + const value = raw.includes("&") ? decodeHTMLAttribute(raw) : raw; + result[info.property] = + info.spaceSeparated || info.commaSeparated + ? value.split(info.commaSeparated ? "," : /\s+/).filter(Boolean) + : info.boolean + ? true + : value; + } + return result; +} + +interface Tokenized { + readonly root: Root; + /** Elements with a `data-sourcepos`, which raw HTML can write too. */ + readonly positioned: Element[]; +} + +/** + * Hast for Words' HTML. Its own markup is well formed; raw HTML closes where its end tags say, + * and is sanitized afterwards, so a misnested tag can only change structure, never safety. + */ +function tokenize(html: string, offsetOf: (byte: number) => number): Tokenized { + const root: Root = { type: "root", children: [] }; + const positioned: Element[] = []; + const stack: Array = [root]; + let svgDepth = 0; + let last = 0; + // rehypePreserveBareAnchorPlaceholders: an `
    ` with no attributes that never closes is text. + const anchors: Array<{ element: Element; parent: Root | Element; tag: string } | null> = []; + const text = (end: number) => { + if (end <= last) return; + const parent = stack.at(-1)!; + const value = decode(html.slice(last, end)); + const previous = parent.children.at(-1); + if (previous?.type === "text") previous.value += value; + else parent.children.push({ type: "text", value } as Text); + }; + for (const match of html.matchAll(TAG)) { + text(match.index); + last = match.index + match[0].length; + const tagName = match[2]?.toLowerCase(); + if (!tagName) continue; + if (match[1]) { + if (tagName === "a") anchors.pop(); + if (tagName === "p" && openParagraph(stack) < 0) { + // A stray `

    ` is an empty paragraph to an HTML parser. + (stack.at(-1)!.children as ElementContent[]).push({ + type: "element", + tagName: "p", + properties: {}, + children: [], + }); + continue; + } + const at = stack.findLastIndex((node) => node.type === "element" && node.tagName === tagName); + if (at > 0) { + for (let index = at; index < stack.length; index++) { + if ((stack[index] as Element).tagName === "svg") svgDepth--; + } + stack.length = at; + } + continue; + } + const inSvg = svgDepth > 0 || tagName === "svg"; + if (!inSvg && CLOSES_PARAGRAPH.has(tagName)) { + const paragraph = openParagraph(stack); + if (paragraph > 0) stack.length = paragraph; + } + const element: Element = { + type: "element", + tagName: inSvg ? match[2]! : tagName, + properties: properties(match[3], inSvg), + children: [], + }; + const sourcepos = element.properties.dataSourcepos; + if (typeof sourcepos === "string") { + delete element.properties.dataSourcepos; + const [start, end] = sourcepos.split("-").map((byte) => offsetOf(Number(byte))); + element.position = { + start: { line: 1, column: start! + 1, offset: start! }, + end: { line: 1, column: end! + 1, offset: end! }, + }; + positioned.push(element); + } + const parent = stack.at(-1)!; + (parent.children as ElementContent[]).push(element); + if (tagName === "a") { + anchors.push(match[3]?.trim() ? null : { element, parent, tag: match[0] }); + } + // The HTML parser ignores `/>` on elements that are not void, such as `
    `. + if (!VOID.has(tagName) && (!match[4] || !inSvg)) { + stack.push(element); + if (tagName === "svg") svgDepth++; + } + } + text(html.length); + for (const anchor of anchors) { + if (!anchor) continue; + const siblings = anchor.parent.children as ElementContent[]; + const at = siblings.indexOf(anchor.element); + if (at >= 0) + siblings.splice(at, 1, { type: "text", value: anchor.tag }, ...anchor.element.children); + } + normalizeRawTables(root); + // Words ends each block with a newline; hast from remark has none after the last. + const end = root.children.at(-1); + if (end?.type === "text") { + end.value = end.value.replace(/\n$/, ""); + if (end.value.trim() === "") root.children.pop(); + } + return { root, positioned }; +} + +const positionKey = (node: Element) => + `${node.tagName.toLowerCase()}:${node.position!.start.offset}-${node.position!.end.offset}`; + +/** + * Words' HTML for `markdown` as hast. A position marks what Words generated, so raw HTML that + * writes its own `data-sourcepos` keeps none: Words' elements are those it also writes with raw + * HTML escaped, and a range claimed more often than that is trusted for none of its claimants. + */ +function parse(markdown: string, options: RenderOptions): Root { + const offsetOf = utf16Offsets(markdown); + const render = (escapeHtml?: true) => + tokenize( + decoder.decode( + renderToHtml(markdown, { + ...options, + ...(escapeHtml ? { escapeHtml } : {}), + sourcePositions: true, + }), + ), + offsetOf, + ); + const { root, positioned } = render(); + if (options.escapeHtml || options.skipHtml || !/data-sourcepos/i.test(markdown)) return root; + const generated = new Map(); + for (const node of render(true).positioned) { + const key = positionKey(node); + generated.set(key, (generated.get(key) ?? 0) + 1); + } + const claimed = new Map(); + for (const node of positioned) { + const key = positionKey(node); + claimed.set(key, (claimed.get(key) ?? 0) + 1); + } + for (const node of positioned) { + const key = positionKey(node); + if (claimed.get(key)! > (generated.get(key) ?? 0)) delete node.position; + } + return root; +} + +/** The stack index of the `

    ` an HTML parser would close, or -1 when none is in scope. */ +function openParagraph(stack: ReadonlyArray): number { + for (let index = stack.length - 1; index > 0; index--) { + const tagName = (stack[index] as Element).tagName; + if (tagName === "p") return index; + if (PARAGRAPH_SCOPE.has(tagName)) return -1; + } + return -1; +} + +/** parse5 puts a raw HTML table's rows in a ``; Words' own tables start with ``. */ +function normalizeRawTables(node: Root | Element) { + for (const child of node.children) { + if (child.type === "element") normalizeRawTables(child); + } + if (node.type !== "element" || node.tagName !== "table") return; + const first = node.children.findIndex((child) => isElement(child, "tr")); + if (first < 0) return; + node.children = [ + ...node.children.slice(0, first), + { type: "element", tagName: "tbody", properties: {}, children: node.children.slice(first) }, + ]; +} + +// Words leaves these raw in Markdown destinations, where micromark percent-encodes them. +const UNSAFE_URL_CHARACTERS = /[\\[\]`{}|^"<> ]/g; +const normalizeUri = (value: string) => + value.replace(UNSAFE_URL_CHARACTERS, (character) => encodeURIComponent(character)); + +const windowsPath = (url: string) => { + const path = url.replace(/%5C/gi, "\\"); + return /^[A-Za-z]:[\\/]/.test(path) ? path : undefined; +}; + +const isElement = (node: unknown, tagName?: string): node is Element => + (node as Element | undefined)?.type === "element" && + (tagName === undefined || (node as Element).tagName === tagName); + +const isElementNode = (node: ElementContent): node is Element => node.type === "element"; + +const isMarkdownImage = (node: unknown): boolean => + (isElement(node, "img") && node.position !== undefined) || + (isElement(node, "a") && + node.position !== undefined && + node.children.length === 1 && + isMarkdownImage(node.children[0])); + +const BREAK: ElementContent = { type: "element", tagName: "br", properties: {}, children: [] }; + +// Words' math: these elements and presentation attributes, and no links or handlers. +const MATH_ELEMENTS = new Set(["svg", "g", "text", "tspan", "rect", "path"]); +const MATH_PROPERTIES = new Set([ + "xmlns", + "width", + "height", + "viewBox", + "fill", + "fontFamily", + "fontSize", + "fontStyle", + "fontWeight", + "role", + "ariaLabel", + "x", + "y", + "dx", + "dy", + "d", + "transform", + "stroke", + "strokeWidth", + "textAnchor", +]); +const MATH_STYLE = /^(?:display|vertical-align|overflow|margin|white-space)$/; + +function sanitizeMath(node: Element): Element | null { + if (!MATH_ELEMENTS.has(node.tagName)) return null; + const properties: Element["properties"] = {}; + for (const [key, value] of Object.entries(node.properties)) { + if (MATH_PROPERTIES.has(key)) properties[key] = value; + } + if (typeof node.properties.style === "string") { + const style = node.properties.style + .split(";") + .filter((rule) => MATH_STYLE.test(rule.split(":")[0]!.trim())) + .join(";"); + if (style) properties.style = style; + } + const children: ElementContent[] = []; + for (const child of node.children) { + if (child.type === "text") children.push(child); + else if (child.type === "element") { + const clean = sanitizeMath(child); + if (clean) children.push(clean); + } + } + return { ...node, properties, children }; +} + +interface Walk { + /** Words' hast for more Markdown, rendered with the same options; `indent` as leadingWhitespace's. */ + readonly render: (markdown: string, indent: number) => Root; + readonly source: string; + readonly options: WordsHastOptions; + readonly math: Map; + /** A per-render id prefix for math placeholders, which authored ids cannot share. */ + readonly mathKey: string; + /** What insightSource opened each insight block with, when it opened any. */ + readonly insightMarker: RegExp | null; +} + +/** UTF-16 offsets for the UTF-8 byte offsets in Words' `data-sourcepos`. */ +function utf16Offsets(source: string): (byte: number) => number { + if (!/[^\x00-\x7f]/.test(source)) return (byte) => byte; + const offsets: number[] = []; + for (let index = 0; index < source.length; index++) { + const code = source.codePointAt(index)!; + const bytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4; + for (let byte = 0; byte < bytes; byte++) offsets.push(index); + if (code >= 0x10000) index++; + } + offsets.push(source.length); + return (byte) => offsets[byte] ?? source.length; +} + +const sourceOf = (node: Element, source: string) => + node.position ? source.slice(node.position.start.offset, node.position.end.offset) : ""; + +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; + +/** A directive's attributes, as strings; anything else Words would never write reads as none. */ +function directiveAttributes(node: Element): Record { + let parsed: unknown; + try { + parsed = JSON.parse(String(node.properties.dataAttributes ?? "{}")); + } catch { + return {}; + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {}; + return Object.fromEntries( + Object.entries(parsed).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ); +} + +/** remarkCodexDirectives: what a directive Words parsed becomes, as the remark plugin builds it. */ +function codexDirective(node: Element, walk: Walk, inLink: boolean): ElementContent { + const name = node.properties.dataDirective; + const attributes = directiveAttributes(node); + const asText = (): ElementContent => { + const value: ElementContent = { type: "text", value: sourceOf(node, walk.source) }; + return node.tagName === "div" + ? { type: "element", tagName: "p", properties: {}, children: [value] } + : value; + }; + if (name === "codex-file-citation") { + const citation = resolveCodexFileCitationLink(attributes); + if (!citation || inLink) return asText(); + return { + type: "element", + tagName: "a", + properties: { href: citation.href }, + children: [{ type: "text", value: citation.label }], + ...(node.position ? { position: node.position } : {}), + }; + } + if (name === "codex-followup") { + if (!attributes.prompt?.trim() || !node.children.map(textOf).join("").trim()) return asText(); + return { type: "element", tagName: "span", properties: {}, children: node.children }; + } + const template = resolveCodexArtifactTemplate(attributes); + if (!template) return asText(); + return { + type: "element", + tagName: "div", + properties: { + dataCodexArtifactTemplate: "true", + dataArtifactKind: template.artifactKind, + dataDisplayName: template.displayName, + ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }), + dataSkillDirectory: template.skillDirectory, + dataSkillName: template.skillName, + }, + children: [], + }; +} + +const INLINE_PREFIX = "t3-markdown-inline-prefix:"; + +function stripPositions(node: ElementContent) { + delete node.position; + if (node.type === "element") node.children.forEach(stripPositions); +} + +/** + * remarkNormalizeListItemIndentation: four spaces after a list marker make indented code, but + * agents mean wide indentation, so code starting on the marker's line is Markdown again. True + * when it recovered the item, whose children it then has transformed. + */ +function recoverIndentedCode( + item: Element, + list: Root | Element, + walk: Walk, + inLink: boolean, + inCode: boolean, +): boolean { + const code = item.children.find((child) => child.type === "element"); + const start = code?.position?.start.offset; + const itemStart = item.position?.start.offset; + if (!isElement(code, "pre") || start === undefined || itemStart === undefined) return false; + const value = textOf(code); + if (!/^[\t ]/.test(value)) return false; + if (walk.source.slice(itemStart, start).includes("\n") || /[`~]/.test(walk.source[start]!)) { + return false; + } + // The trimmed first line sets where the item's content starts. + const indent = [.../^[\t ]*/.exec(value)![0]].reduce( + (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1), + 0, + ); + // The prefix keeps block syntax at the start, such as `#`, from opening a block. + const source = `${INLINE_PREFIX}${value.trim()}`; + const recovered = walk.render(source, indent); + const paragraph = recovered.children.find((child) => child.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + if (first?.type !== "text" || !first.value.startsWith(INLINE_PREFIX)) return false; + first.value = first.value.slice(INLINE_PREFIX.length); + if (first.value === "") paragraph!.children.shift(); + transform(recovered, { ...walk, source }, inLink, inCode); + transform(item, walk, inLink, inCode); + let blocks = recovered.children.filter( + (child) => !(child.type === "text" && child.value.trim() === ""), + ) as ElementContent[]; + // Their positions point into `source`, not the message. + blocks.forEach(stripPositions); + let at = item.children.indexOf(code); + let remove = 1; + if (!isLooseList(list, walk.source)) { + // A tight item shows its text bare, as remark-rehype unwraps its paragraphs. + blocks = blocks.flatMap((block, index) => [ + ...(index > 0 ? [{ type: "text", value: "\n" } as Text] : []), + ...(isElement(block, "p") ? block.children : [block]), + ]); + const isBlank = (node: ElementContent | undefined) => + node?.type === "text" && node.value.trim() === ""; + if (at === 1 && isBlank(item.children[0])) [at, remove] = [0, 2]; + if (at + remove === item.children.length - 1 && isBlank(item.children.at(-1))) remove++; + } + item.children.splice(at, remove, ...blocks); + return true; +} + +/** remark-rehype's listLoose: a blank line between items, or an item Words wrote as paragraphs. */ +function isLooseList(list: Root | Element, source: string): boolean { + const items = (list.children as ElementContent[]).filter((child): child is Element => + isElement(child, "li"), + ); + return items.some( + (item, index) => + item.children.some((child) => isElement(child, "p")) || + (index > 0 && + /\n[ \t>]*\n/.test( + source.slice( + items[index - 1]!.position?.end.offset ?? 0, + item.position?.start.offset ?? 0, + ), + )), + ); +} + +const WRITTEN_NUMBER = /[ \t]*(\d{1,9})[.)]/y; + +function keepListNumbers(list: Element, source: string) { + let expected = Number(list.properties.start ?? 1); + for (const item of list.children) { + if (!isElement(item, "li")) continue; + const offset = item.position?.start.offset; + WRITTEN_NUMBER.lastIndex = offset ?? 0; + const digits = offset === undefined ? undefined : WRITTEN_NUMBER.exec(source)?.[1]; + const value = digits === undefined ? expected : Number(digits); + if (value !== expected) item.properties.value = String(value); + expected = value + 1; + } +} + +/** What the chat's remark plugins add that Words does not. */ +const link = (href: string, label: string, properties: Element["properties"] = {}): Element => ({ + type: "element", + tagName: "a", + properties: { href, ...properties }, + children: [{ type: "text", value: label }], +}); + +/** Links in text: absolute file paths (remarkLinkAbsoluteFilePaths), then a change request's references. */ +function linkText(value: string, walk: Walk): ElementContent[] | null { + let parts: ElementContent[] = []; + let offset = 0; + for (const { index, path } of absoluteFilePathMatches(value)) { + if (index > offset) parts.push({ type: "text", value: value.slice(offset, index) }); + parts.push(link(path, path)); + offset = index + path.length; + } + if (offset < value.length) parts.push({ type: "text", value: value.slice(offset) }); + const autolinks = walk.options.extensions.changeRequest?.autolinks; + if (autolinks) { + parts = parts.flatMap((part) => { + if (part.type !== "text") return [part]; + const found = autolinks(part.value); + if (found.length === 0) return [part]; + const linked: ElementContent[] = []; + let start = 0; + for (const reference of found) { + if (start < reference.index) { + linked.push({ type: "text", value: part.value.slice(start, reference.index) }); + } + linked.push( + link(reference.url, reference.label, { dataPullRequestAutolink: reference.kind }), + ); + start = reference.index + reference.text.length; + } + if (start < part.value.length) linked.push({ type: "text", value: part.value.slice(start) }); + return linked; + }); + } + return parts.length === 1 && parts[0]!.type === "text" ? null : parts; +} + +function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: boolean) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type === "text") { + if (inCode) continue; + if (walk.options.extensions.githubEmoji && child.value.includes(":")) { + child.value = expandGithubEmojiAliases(child.value); + } + if (inLink) continue; + const parts = linkText(child.value, walk); + if (!parts) continue; + children.splice(index, 1, ...parts); + index += parts.length - 1; + continue; + } + if (child.type !== "element") continue; + // Words gives what it generates a source position; raw HTML that copies its attributes has none. + if (child.properties.dataDirective !== undefined && child.position) { + children[index] = codexDirective(child, walk, inLink); + index--; + continue; + } + const { tagName, properties: props } = child; + if (tagName === "svg") { + // Sanitizing drops SVG, so math waits under a placeholder until after it. + const clean = walk.options.math && child.position ? sanitizeMath(child) : null; + if (clean) { + const key = `${walk.mathKey}-${walk.math.size}`; + walk.math.set(key, clean); + children[index] = { + type: "element", + tagName: "span", + properties: { id: key }, + children: [], + }; + } + continue; + } + if (tagName === "a" && props.dataFootnoteRef !== undefined) { + // remark-rehype's footnote markup, before rehype-sanitize prefixes ids again. + props.href = `#user-content-${String(props.href).slice(1)}`; + props.id = `user-content-${String(props.id)}`; + props.ariaDescribedBy = ["footnote-label"]; + } else if (tagName === "a" && props.dataFootnoteBackref !== undefined) { + const { href, ariaLabel } = props; + child.properties = { + href: `#user-content-${String(href).slice(1)}`, + dataFootnoteBackref: "", + ariaLabel, + className: ["data-footnote-backref"], + }; + } else if (tagName === "li" && typeof props.id === "string" && props.id.startsWith("fn-")) { + props.id = `user-content-${props.id}`; + } else if (tagName === "section" && props.dataFootnotes !== undefined) { + child.properties = { dataFootnotes: "", className: ["footnotes"] }; + child.children.unshift({ + type: "element", + tagName: "h2", + properties: { className: ["sr-only"], id: "footnote-label" }, + children: [{ type: "text", value: "Footnotes" }], + }); + } else if (tagName === "a" && typeof props.href === "string") { + // remarkNormalizeLinksAndTagInlineCode: a Windows drive path links as a file URL. + const path = windowsPath(props.href); + props.href = path ? `file:///${path.replaceAll("\\", "/")}` : normalizeUri(props.href); + } else if (tagName === "img" && typeof props.src === "string") { + const changeRequest = walk.options.extensions.changeRequest; + const src = changeRequest + ? resolveChangeRequestMediaUrl(props.src, changeRequest.repositoryUrl) + : props.src; + props.src = windowsPath(src) ?? normalizeUri(src); + } else if (tagName === "code" && isElement(node, "pre")) { + if (props.dataMeta !== undefined) { + props.dataCodeMeta = props.dataMeta; + delete props.dataMeta; + } + } else if (tagName === "code" && !inLink) { + props.dataInlineCode = ""; + } else if (tagName === "ol" && walk.options.extensions.userMessage) { + keepListNumbers(child, walk.source); + } else if (tagName === "li") { + const firstBlock = child.children.find(isElementNode); + if (isElement(firstBlock, "pre") && recoverIndentedCode(child, node, walk, inLink, inCode)) { + continue; + } + // Tight items put the checkbox directly in `

  • `, loose ones inside its first `

    `. + const checkbox = isElement(child.children[0], "input") + ? child.children[0] + : isElement(firstBlock, "p") && isElement(firstBlock.children[0], "input") + ? firstBlock.children[0] + : undefined; + if (checkbox) { + props.className = ["task-list-item"]; + const { checked } = checkbox.properties; + checkbox.properties = { type: "checkbox", checked, disabled: true }; + if (node.type === "element") node.properties.className = ["contains-task-list"]; + } + breakLines(child, walk.options.breaks); + } else if (tagName === "p") { + breakLines(child, walk.options.breaks); + } else if (tagName === "blockquote") { + // remarkGithubAlerts + const paragraph = child.children.find((item) => item.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + const text = first?.type === "text" ? first.value : ""; + const insight = walk.insightMarker?.exec(text); + const alert = GITHUB_ALERT_MARKER.exec(text); + // An alert marker followed by more inline content on its line is text, as remarkGithubAlerts reads it. + const match = insight + ? ([insight[0], "insight"] as const) + : alert && (alert[0].endsWith("\n") || (paragraph as Element).children.length === 1) + ? alert + : null; + if (match && first?.type === "text" && isElement(paragraph, "p")) { + first.value = first.value.slice(match[0].length); + if (first.value === "") paragraph.children.shift(); + if (paragraph.children.length === 0) { + const at = child.children.indexOf(paragraph); + const next = child.children[at + 1]; + // The line ending after it goes too, as remark leaves none for a removed paragraph. + const blank = next?.type === "text" && next.value.trim() === "" ? 2 : 1; + child.children.splice(at, blank); + } + props.dataAlert = match[1]!.toLowerCase(); + } + } + transform( + child, + walk, + inLink || tagName === "a", + inCode || tagName === "code" || tagName === "pre", + ); + } +} + +/** + * remark-breaks puts a `
    ` before every soft line ending, and remarkBreakAroundImageLines + * before those next to a Markdown image. Both keep the line ending after it. + */ +/** A Markdown image alone on its line: nothing but a line ending (or the paragraph's edge) around it. */ +function imageOwnsLine(items: ElementContent[], at: number): boolean { + if (!isMarkdownImage(items[at])) return false; + const before = items[at - 1]; + const after = items[at + 1]; + const startsLine = + before === undefined || + (before.type === "text" && /\n[ \t]*$/.test(before.value)) || + isElement(before, "br"); + const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value)); + return startsLine && endsLine; +} + +const isBlockElement = (node: ElementContent | undefined) => + node?.type === "element" && CLOSES_PARAGRAPH.has(node.tagName); + +function breakLines(paragraph: Element, breaks: boolean) { + const items = paragraph.children; + for (let at = 0; at < items.length; at++) { + const item = items[at]!; + if ( + item.type === "element" && + breaks && + item.tagName !== "code" && + !CLOSES_PARAGRAPH.has(item.tagName) + ) { + breakLines(item, breaks); + } + if (item.type !== "text" || !item.value.includes("\n")) continue; + const afterImage = imageOwnsLine(items, at - 1); + const beforeImage = imageOwnsLine(items, at + 1); + const afterBlock = isBlockElement(items[at - 1]) || (at === 0 && paragraph.tagName === "li"); + const beforeBlock = + isBlockElement(items[at + 1]) || (at === items.length - 1 && paragraph.tagName === "li"); + const lines = item.value.split("\n"); + const parts: ElementContent[] = []; + lines.forEach((line, index) => { + // A hard break's own line ending follows its
    , and adds no second one; + // structural line endings around a list item's block children stay breaks between blocks. + const afterHardBreak = index === 1 && isElement(items[at - 1], "br"); + const blockBoundary = + (index === 1 && lines[0] === "" && afterBlock) || + (index === lines.length - 1 && line === "" && beforeBlock); + const breaksHere = + index > 0 && + !afterHardBreak && + !blockBoundary && + (breaks || (index === 1 && afterImage) || (index === lines.length - 1 && beforeImage)); + if (index > 0) { + if (breaksHere) { + const previous = parts.at(-1); + if (previous?.type === "text") previous.value = previous.value.replace(/[ \t]+$/, ""); + parts.push(BREAK); + } + parts.push({ type: "text", value: `\n${line}` }); + } else if (line) { + parts.push({ type: "text", value: line }); + } + }); + // Rejoin text that did not break, so the tree matches remark's text nodes. + const merged: ElementContent[] = []; + for (const part of parts) { + const previous = merged.at(-1); + if (part.type === "text" && previous?.type === "text") previous.value += part.value; + else merged.push(part); + } + items.splice(at, 1, ...merged); + at += merged.length - 1; + } +} + +/** + * The wrapper copying reads (markdown-clipboard's MATH_SELECTOR): the formula's TeX, as the source + * Words drew it from, so copying any part of a formula copies the whole of it. + */ +// A formula wider than its block scrolls, with room for the glyphs that reach past its box; in a +// table it keeps its width and the table scrolls. +const MATH_SCROLL = [ + "max-w-full", + "overflow-x-auto", + "overflow-y-hidden", + "px-0.5", + "py-0.75", + "in-[.chat-markdown-table-container]:max-w-none", + "in-[.chat-markdown-table-container]:overflow-visible", +]; + +function mathWrapper(svg: Element): Element { + const tex = String(svg.properties.ariaLabel ?? "").trim(); + const display = /display:\s*block/.test(String(svg.properties.style ?? "")); + return { + type: "element", + tagName: "span", + properties: display + ? { + className: ["chat-markdown-math-display", "block", ...MATH_SCROLL], + dataMarkdownMath: "display", + dataMarkdownCopy: `\\[\n${tex}\n\\]\n\n`, + } + : { + className: ["inline-block", "align-middle", ...MATH_SCROLL], + dataMarkdownMath: "inline", + dataMarkdownCopy: `\\(${tex}\\)`, + }, + children: [svg], + }; +} + +function restoreMath(node: Root | Element, math: Map) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + const id = child.properties.id; + const svg = typeof id === "string" ? math.get(id.replace(/^user-content-/, "")) : undefined; + if (svg) children[index] = mathWrapper(svg); + else restoreMath(child, math); + } +} + +const addHeadingIds = rehypeHeadingIds(); +const addTextDirection = rehypeTextDirection(); +const preserveImageSourceMeta = rehypePreserveImageSourceMeta(); +const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks(); +const groupChipPunctuation = rehypeChipPunctuation(); + +const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; +const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; + +interface InsightSource { + readonly source: string; + readonly tree: Root; + readonly marker: RegExp; + /** The offset in the message for an offset in `source`. */ + readonly toOriginal: (offset: number) => number; +} + +/** + * remarkAssistantInsights: a `★ Insight ───` line opens a quoted insight block, which a `───` line + * at the same indentation closes; the end of the text closes one that never does. Lines in code + * neither open nor close one, and an opening Words does not read as a quote's first line, as in + * an HTML block or a quote's lazy line, stays text. + */ +function insightSource(text: string, options: RenderOptions): InsightSource | null { + if (!text.includes("★ Insight")) return null; + const code: Array = []; + const findCode = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "pre" && child.position) { + code.push([child.position.start.offset!, child.position.end.offset!]); + } else findCode(child); + } + }; + findCode(parse(text, options)); + const nonce = Math.random().toString(36).slice(2); + const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`); + const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g"); + const lines = text.split(/(?<=\n)/u); + const skipped = new Set(); + for (;;) { + // Each line's offset in the message and in the source, and how much longer it got. + const offsets: Array<{ original: number; source: number; length: number; delta: number }> = []; + let original = 0; + let rewritten = 0; + let opened = 0; + let indent: string | undefined; + const source = lines + .map((line, lineIndex) => { + const value = line.replace(/[\r\n]+$/u, ""); + const ending = line.slice(value.length); + const inCode = code.some(([start, end]) => original >= start && original < end); + let output = line; + if (indent === undefined) { + const opening = inCode ? null : INSIGHT_OPENING.exec(value); + if (opening && !skipped.has(lineIndex)) { + indent = opening[1] ?? ""; + opened++; + output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`; + } + } else { + const closing = inCode ? null : INSIGHT_CLOSING.exec(value); + if (closing && closing[1] === indent) { + indent = undefined; + output = ending; + } else output = `> ${line}`; + } + offsets.push({ + original, + source: rewritten, + length: line.length, + delta: output.length - line.length, + }); + original += line.length; + rewritten += output.length; + return output; + }) + .join(""); + if (opened === 0) return null; + const tree = parse(source, options); + let stranded = false; + const visit = (node: Root | Element, quoteStart: Text | undefined) => { + for (const child of node.children) { + if (child.type === "text") { + for (const found of child.value.matchAll(anywhere)) { + if (child === quoteStart && found.index === 0) continue; + skipped.add(Number(found[1])); + stranded = true; + } + } else if (child.type === "element") { + const paragraph = + child.tagName === "blockquote" ? child.children.find(isElementNode) : undefined; + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + visit(child, first?.type === "text" ? first : quoteStart); + } + } + }; + visit(tree, undefined); + if (stranded) continue; + return { + source, + tree, + marker, + toOriginal: (offset) => { + const line = offsets.findLast((entry) => entry.source <= offset) ?? offsets[0]!; + return ( + line.original + Math.min(Math.max(offset - line.source - line.delta, 0), line.length) + ); + }, + }; + } +} + +/** Positions that point into an insight's rewritten source, moved back into the message. */ +function restorePositions(node: Root | Element, toOriginal: (offset: number) => number) { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.position) { + const start = toOriginal(child.position.start.offset!); + const end = toOriginal(child.position.end.offset!); + child.position = { + start: { line: 1, column: start + 1, offset: start }, + end: { line: 1, column: end + 1, offset: end }, + }; + } + restorePositions(child, toOriginal); + } +} + +const PREVIEW_SEPARATED = new Set([ + "blockquote", + "ul", + "ol", + "li", + "table", + "thead", + "tbody", + "tr", +]); + +/** remarkThoughtPreview: the message as one line of text, keeping math, cut at `maxLength`. */ +function flattenPreview(tree: Root, preview: NonNullable): Root { + const children: ElementContent[] = []; + let remaining = preview.maxLength; + let fragments: string[] = []; + const flush = () => { + if (fragments.length === 0) return; + children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); + fragments = []; + }; + const take = (value: string) => { + const text = value.slice(0, remaining); + remaining = text.length < value.length ? 0 : remaining - text.length; + // A cut must not leave half a surrogate pair. + return text.replace(/[\uD800-\uDBFF]$/, ""); + }; + const visit = (node: Root | ElementContent) => { + if (remaining === 0) return; + if (node.type === "text") { + fragments.push(take(node.value)); + return; + } + if (node.type === "element" && node.properties.dataMarkdownMath !== undefined) { + flush(); + // One line has no room for display math, which a preview shows inline. + const svg = node.children[0]; + children.push( + node.properties.dataMarkdownMath === "display" && svg?.type === "element" + ? mathWrapper({ + ...svg, + properties: { + ...svg.properties, + style: "display:inline;vertical-align:middle;overflow:visible", + }, + }) + : node, + ); + return; + } + if (node.type === "element" && node.tagName === "img") { + fragments.push(take(String(node.properties.alt ?? ""))); + return; + } + if (node.type === "element" && node.tagName === "br") { + fragments.push(take(" ")); + return; + } + if (node.type !== "root" && node.type !== "element") return; + const separates = node.type === "root" || PREVIEW_SEPARATED.has(node.tagName); + let first = true; + for (const child of node.children as ElementContent[]) { + if (remaining === 0) break; + if (child.type === "text" && child.value.trim() === "" && separates) continue; + if (!first && separates) fragments.push(take(" ")); + first = false; + visit(child); + } + }; + visit(tree); + flush(); + const head = children[0]; + const tail = children.at(-1); + if (head?.type === "text") head.value = head.value.trimStart(); + if (tail?.type === "text") tail.value = tail.value.trimEnd(); + const visible = children.some((child) => child.type !== "text" || child.value); + return { + type: "root", + children: visible ? children : [{ type: "text", value: preview.fallback }], + }; +} + +/** Links become their text, images their alt text, inline code plain text, Mermaid plain code. */ +function makeInert(node: Root | Element) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + if (child.tagName === "a") { + children.splice(index, 1, ...child.children); + index--; + continue; + } + if (child.tagName === "img") { + children[index] = { type: "text", value: String(child.properties.alt ?? "") }; + continue; + } + if (child.tagName === "code" && child.properties.dataInlineCode !== undefined) { + children[index] = { type: "text", value: textOf(child) }; + continue; + } + if ( + child.tagName === "code" && + String(child.properties.className ?? "").includes("language-mermaid") + ) { + child.properties.className = ["language-text"]; + } + makeInert(child); + } +} + +/** ChatMarkdown's sanitized hast for `text`, rendered by Words. */ +export function wordsHast(written: string, options: WordsHastOptions): Root { + const { extensions } = options; + const text = forkSource(written, options.math ? markdownMathRanges : null); + const renderOptions: RenderOptions = { + math: options.math, + // llm-math's `\(…\)` and `\[…\]`, which agents write as often as `$`. + texDelimiters: options.math, + autolinkBoundaries: true, + ...forkRenderOptions(options), + leadingWhitespace: extensions.leadingWhitespace === true, + windowsPaths: true, + codeMeta: true, + directives: CODEX_DIRECTIVES, + // Previews and inert Markdown drop raw HTML, as their remark plugins dropped html nodes. + ...(extensions.preview || extensions.inert + ? { skipHtml: true } + : { escapeHtml: options.escapeHtml }), + }; + const insights = options.insights ? insightSource(text, renderOptions) : null; + const source = insights?.source ?? text; + const tree = insights?.tree ?? parse(source, renderOptions); + const walk: Walk = { + render: (markdown, indent) => + parse(markdown, { + ...renderOptions, + leadingWhitespace: extensions.leadingWhitespace === true && { indent }, + }), + source, + options, + math: new Map(), + mathKey: `t3-math-${Math.random().toString(36).slice(2)}`, + insightMarker: insights?.marker ?? null, + }; + transform(tree, walk, false, false); + preserveImageSourceMeta(tree as never); + normalizeLocalEditorLinks(tree as never); + const hast = sanitizeChatHast(tree); + if (walk.math.size > 0) restoreMath(hast, walk.math); + if (insights) restorePositions(hast, insights.toOriginal); + forkHast(hast, written, text, options); + if (extensions.inert) makeInert(hast); + if (extensions.preview) return flattenPreview(hast, extensions.preview); + addHeadingIds(hast); + addTextDirection(hast as never); + groupChipPunctuation(hast as never); + return hast; +} + +export interface CodexDirectiveSource { + readonly name: string; + readonly attributes: Record; + /** UTF-16 offsets of the whole directive in the source. */ + readonly start: number; + readonly end: number; + /** The label's text as written. */ + readonly label: string; + /** Inside a link, where a file citation stays text. */ + readonly inLink: boolean; +} + +/** The Codex directives in `markdown`, as Words reads them. */ +export function codexDirectiveSources(markdown: string): CodexDirectiveSource[] { + const found: CodexDirectiveSource[] = []; + const visit = (node: Root | Element, inLink: boolean) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const name = child.properties.dataDirective; + if (typeof name === "string" && child.position) { + const { start, end } = child.position; + found.push({ + name, + attributes: directiveAttributes(child), + start: start.offset!, + end: end.offset!, + label: directiveLabel(markdown.slice(start.offset, end.offset)), + inLink, + }); + } + visit(child, inLink || child.tagName === "a"); + } + }; + visit( + parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + directives: CODEX_DIRECTIVES, + }), + false, + ); + return found; +} + +/** The label of a directive as written, `:name[label]{…}`: brackets nest in it, and `\` escapes. */ +function directiveLabel(written: string): string { + const open = written.indexOf("["); + if (open < 0) return ""; + let depth = 0; + for (let index = open; index < written.length; index++) { + const character = written[index]; + if (character === "\\") index++; + else if (character === "[") depth++; + else if (character === "]" && --depth === 0) return written.slice(open + 1, index); + } + return ""; +} + +/** + * Words' HTML for `markdown` as hast, unsanitized and without the chat's additions. Code blocks, + * links, list items and math carry source positions. + */ +export function markdownTree( + markdown: string, + options: { skipHtml?: boolean; singleTilde?: boolean; math?: boolean } = {}, +): Root { + return parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + skipHtml: options.skipHtml === true, + singleTilde: options.singleTilde !== false, + math: options.math === true, + texDelimiters: options.math === true, + }); +} + +/** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */ +export function markdownMathRanges(text: string): Array<{ start: number; end: number }> { + if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return []; + const ranges: Array<{ start: number; end: number }> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "svg") { + if (child.position) { + ranges.push({ start: child.position.start.offset!, end: child.position.end.offset! }); + } + continue; + } + visit(child); + } + }; + visit(parse(text, { math: true, texDelimiters: true })); + return ranges; +} + +/** The HTML comments Words reads as raw HTML in `markdown`, not as code or text, as source offsets. */ +export function markdownHtmlComments(markdown: string): Array<{ start: number; end: number }> { + const openers = [...markdown.matchAll(/", start + 4); + return { start, end: close < 0 ? markdown.length : close + 3 }; + }); +} + +/** + * The first definition of each label in `markdown`, as one line of Markdown. Words decides which + * `[label]:` text defines one: each label is looked up again after the text. + */ +export function markdownReferenceDefinitions(markdown: string): string[] { + const labels = new Map(); + for (const match of markdown.matchAll(/\[((?:[^\\[\]]|\\.){1,999})\]:/g)) { + const key = match[1]!.replace(/\s+/g, " ").trim().toLowerCase(); + // `[^1]:` is a footnote. + if (key !== "" && !key.startsWith("^") && !labels.has(key)) labels.set(key, match[1]!); + } + if (labels.size === 0) return []; + let probe = `${markdown}\n\n`; + const lookups = new Map(); + for (const label of labels.values()) { + lookups.set(probe.length, label); + probe += `[${label}]\n\n`; + } + const definitions: string[] = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const label = lookups.get(child.position?.start.offset ?? -1); + if (child.tagName === "a" && label !== undefined) { + const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent); + const title = child.properties.title; + definitions.push( + `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`, + ); + } else visit(child); + } + }; + visit(parse(probe, { windowsPaths: true })); + return definitions; +} diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 58c04d0624387..7c1afbbec7770 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -18,6 +18,7 @@ import { Route as ApproveAgentRouteImport } from './routes/approve-agent' import { Route as ChatRouteImport } from './routes/_chat' import { Route as ChatIndexRouteImport } from './routes/_chat.index' import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey' +import { Route as ChatWorkflowsRouteImport } from './routes/_chat.workflows' import { Route as ChatUsageRouteImport } from './routes/_chat.usage' import { Route as ChatSettingsRouteImport } from './routes/_chat.settings' import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests' @@ -100,6 +101,11 @@ const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({ path: '/projects/$projectKey', getParentRoute: () => rootRouteImport, } as any) +const ChatWorkflowsRoute = ChatWorkflowsRouteImport.update({ + id: '/workflows', + path: '/workflows', + getParentRoute: () => ChatRoute, +} as any) const ChatUsageRoute = ChatUsageRouteImport.update({ id: '/usage', path: '/usage', @@ -308,6 +314,7 @@ export interface FileRoutesByFullPath { '/pull-requests': typeof ChatPullRequestsRoute '/settings': typeof ChatSettingsRouteWithChildren '/usage': typeof ChatUsageRoute + '/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute '/draft/$draftId': typeof ChatDraftDraftIdRoute @@ -354,6 +361,7 @@ export interface FileRoutesByTo { '/pull-requests': typeof ChatPullRequestsRoute '/settings': typeof ChatSettingsRouteWithChildren '/usage': typeof ChatUsageRoute + '/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/': typeof ChatIndexRoute '/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute @@ -403,6 +411,7 @@ export interface FileRoutesById { '/_chat/pull-requests': typeof ChatPullRequestsRoute '/_chat/settings': typeof ChatSettingsRouteWithChildren '/_chat/usage': typeof ChatUsageRoute + '/_chat/workflows': typeof ChatWorkflowsRoute '/projects/$projectKey': typeof ProjectsProjectKeyRoute '/_chat/': typeof ChatIndexRoute '/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute @@ -453,6 +462,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/$environmentId/$threadId' | '/draft/$draftId' @@ -499,6 +509,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/' | '/$environmentId/$threadId' @@ -547,6 +558,7 @@ export interface FileRouteTypes { | '/_chat/pull-requests' | '/_chat/settings' | '/_chat/usage' + | '/_chat/workflows' | '/projects/$projectKey' | '/_chat/' | '/_chat/$environmentId/$threadId' @@ -660,6 +672,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ProjectsProjectKeyRouteImport parentRoute: typeof rootRouteImport } + '/_chat/workflows': { + id: '/_chat/workflows' + path: '/workflows' + fullPath: '/workflows' + preLoaderRoute: typeof ChatWorkflowsRouteImport + parentRoute: typeof ChatRoute + } '/_chat/usage': { id: '/_chat/usage' path: '/usage' @@ -994,6 +1013,7 @@ interface ChatRouteChildren { ChatPullRequestsRoute: typeof ChatPullRequestsRoute ChatSettingsRoute: typeof ChatSettingsRouteWithChildren ChatUsageRoute: typeof ChatUsageRoute + ChatWorkflowsRoute: typeof ChatWorkflowsRoute ChatIndexRoute: typeof ChatIndexRoute ChatEnvironmentIdThreadIdRoute: typeof ChatEnvironmentIdThreadIdRoute ChatDraftDraftIdRoute: typeof ChatDraftDraftIdRoute @@ -1006,6 +1026,7 @@ const ChatRouteChildren: ChatRouteChildren = { ChatPullRequestsRoute: ChatPullRequestsRoute, ChatSettingsRoute: ChatSettingsRouteWithChildren, ChatUsageRoute: ChatUsageRoute, + ChatWorkflowsRoute: ChatWorkflowsRoute, ChatIndexRoute: ChatIndexRoute, ChatEnvironmentIdThreadIdRoute: ChatEnvironmentIdThreadIdRoute, ChatDraftDraftIdRoute: ChatDraftDraftIdRoute, diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx index c97534939f743..637bf8f9a2236 100644 --- a/apps/web/src/routes/_chat.settings.tsx +++ b/apps/web/src/routes/_chat.settings.tsx @@ -52,22 +52,41 @@ function SettingsScopeBoundary({ pathname, children }: { pathname: string; child const m = useMessages(); const hash = useLocation({ select: (location) => location.hash }); const searchTarget = getSettingsSearchTargetScope(hash); - const autoSettlementAvailability = searchTarget?.requiresThreadAutoSettlement - ? getThreadAutoSettlementSearchAvailability(environments, scope) + const agentFeedbackAvailability = searchTarget?.agentFeedbackOnly + ? { + eligibleEnvironmentIds: environments + .filter( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ) + .map((environment) => environment.environmentId), + isTargetAvailable: + connectedEnvironments.length > 0 && + connectedEnvironments.every( + (environment) => + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ), + } : null; + const targetAvailability = + agentFeedbackAvailability ?? + (searchTarget?.requiresThreadAutoSettlement + ? getThreadAutoSettlementSearchAvailability(environments, scope) + : null); if ( scope.kind !== "unavailable" && searchTarget && - autoSettlementAvailability && - !autoSettlementAvailability.isTargetAvailable + targetAvailability && + !targetAvailability.isTargetAvailable ) { return ( - {autoSettlementAvailability.eligibleEnvironmentIds.length > 0 + {targetAvailability.eligibleEnvironmentIds.length > 0 ? gt("{title} requires a supporting environment. Choose one to continue.", { title: m(searchTarget.title), }) diff --git a/apps/web/src/routes/_chat.workflows.tsx b/apps/web/src/routes/_chat.workflows.tsx new file mode 100644 index 0000000000000..c755da76d5b38 --- /dev/null +++ b/apps/web/src/routes/_chat.workflows.tsx @@ -0,0 +1,15 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { readWorkflowPane } from "../components/workflows/workflowPane.logic"; +import { WorkflowsPage, type WorkflowsSearch } from "../components/workflows/WorkflowsPage"; + +export const Route = createFileRoute("/_chat/workflows")({ + validateSearch: (raw: Record): WorkflowsSearch => ({ + ...(typeof raw.env === "string" && raw.env ? { env: raw.env.slice(0, 200) } : {}), + ...(typeof raw.run === "string" && raw.run ? { run: raw.run.slice(0, 200) } : {}), + ...readWorkflowPane(raw.pane, raw.tab), + ...(raw.definitions === true || raw.definitions === "true" ? { definitions: true } : {}), + ...(typeof raw.file === "string" && raw.file ? { file: raw.file.slice(0, 200) } : {}), + }), + component: WorkflowsPage, +}); diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index f4670665add6c..2155fedaa83c1 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -290,7 +290,10 @@ describe("V2 session presentation", () => { }, }; }); - const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({ + const checkpoint = ( + ordinal: number, + status: "ready" | "missing" | "stale" | "error" = "ready", + ) => ({ runId: runId(ordinal), checkpointTurnCount: ordinal, checkpointRef: `checkpoint-${ordinal}` as never, @@ -326,6 +329,11 @@ describe("V2 session presentation", () => { "user-1": 0, "user-2": 1, }); + // A failed snapshot capture still pins the conversation; only file restore needs one. + expect(targets([1, 2], [checkpoint(1, "error")])).toEqual({ + "user-1": 0, + "user-2": 1, + }); }); it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 1122c3122aca0..99a1fc62a0bc3 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -245,6 +245,7 @@ const STANDALONE_V2_ITEM_TYPES = new Set) { - return checkpoint.status === "ready" || checkpoint.status === "missing"; + return checkpoint.status !== "stale"; } export function findRevertCheckpoint( diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index adeb858c23cab..4194e07834811 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -11,7 +11,7 @@ import { useNavigate, useRouter } from "@tanstack/react-router"; import { AsyncResult, Atom } from "effect/reactivity"; import type { TurnItemSource } from "../components/chat/timelineRowContext"; -import { useRightPanelStore } from "../rightPanelStore"; +import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; import { connectPairing, reachesEnvironment } from "../connection/onboarding"; import { openLinkedThreadRead } from "../lib/sideChatPane"; import type { LinkedThreadSurface } from "../linkedThreadSurface"; @@ -107,14 +107,17 @@ const tabViewAtom = Atom.family((key: string) => { const view = peerLinkEnvironment.threadView( targetOf({ viaEnvironmentId, environmentId, threadId }), ); - return Atom.make((get) => { - const live = get(view); - const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; - if (title && panelRef !== null) { - useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); - } - return live; - }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); + return Atom.readable( + (get) => { + const live = get(view); + const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; + if (title && panelRef !== null) { + useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + } + return live; + }, + (refresh) => refresh(view), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); }); /** @@ -203,8 +206,17 @@ export function useConnectLinkedEnvironment( const connect = async () => { setState({ phase: "connecting" }); const startedOn = router.state.location.href; + let tabClosed = false; + // A tab can close and reopen with the same ID while pairing is in flight. + const stopWatchingTab = + panelRef === null + ? undefined + : useRightPanelStore.subscribe((state) => { + const { surfaces } = selectThreadRightPanelState(state.byThreadKey, panelRef); + if (!surfaces.some((tab) => tab.id === surface.id)) tabClosed = true; + }); // Pairing takes a moment; a user who has gone elsewhere since is not moved again. - const stayed = () => router.state.location.href === startedOn; + const stayed = () => !tabClosed && router.state.location.href === startedOn; const outcome = await connectLinkedEnvironment({ label: surface.label, requestPairing: async () => { @@ -228,13 +240,14 @@ export function useConnectLinkedEnvironment( }); return result._tag === "Success"; }, - }); + }).finally(stopWatchingTab); if (outcome.type === "unreachable") { setState({ phase: "unreachable", label: outcome.label }); return outcome; } if (outcome.type === "connected") { setState({ phase: "idle" }); + if (tabClosed) return outcome; // The thread opens where every thread on a connected environment does, so its tab is done. if (panelRef !== null) useRightPanelStore.getState().closeSurface(panelRef, surface.id); if (!stayed()) return outcome; diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 8eaca1b774c85..0915810b47fed 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -22,7 +22,13 @@ import { AsyncResult, Atom } from "effect/reactivity"; import { formatEnvironmentQueryError } from "./query"; import { terminalEnvironment } from "./terminal"; -import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session"; +import { environmentAtomList, environmentIdsKey } from "./environmentAtomList"; +import { + environmentSession, + sessionHasScope, + useEnvironmentScope, + useEnvironmentsWithScope, +} from "./session"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; @@ -274,3 +280,43 @@ export function useThreadRunningTerminalIds(input: { const sessions = useKnownTerminalSessions(input); return selectRunningSubprocessTerminalIds(sessions ?? []); } + +// A string so status updates that keep every label notify no one. +const terminalLabelsFamily = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const metadata = get(terminalEnvironment.metadata({ environmentId, input: null })); + if (metadata._tag !== "Success") return "[]"; + return JSON.stringify( + Array.from(terminalMetadataIndex(metadata.value).byThreadId, ([threadId, summaries]) => [ + threadId, + summaries[0]!.label, + ]), + ); + }).pipe(Atom.withLabel(`web-terminal-labels:${environmentId}`)), +); +const terminalLabelsListAtom = environmentAtomList("web-terminal-labels", terminalLabelsFamily); +const terminalLabelsByResults = new WeakMap, ReadonlyMap>(); + +/** First terminal label of each thread that has one, keyed `${environmentId}:${threadId}`. */ +export function useTerminalLabelsByThreadKey( + environmentIds: ReadonlyArray, +): ReadonlyMap { + const readable = useEnvironmentsWithScope( + environmentIds.map((environmentId) => ({ environmentId })), + AuthTerminalReadScope, + ); + const readableIds = environmentIds.filter((environmentId) => readable.has(environmentId)); + const results = useAtomValue(terminalLabelsListAtom(environmentIdsKey(readableIds))); + let labels = terminalLabelsByResults.get(results); + if (!labels) { + const next = new Map(); + results.forEach((encoded, index) => { + for (const [threadId, label] of JSON.parse(encoded) as Array<[string, string]>) { + next.set(`${readableIds[index]}:${threadId}`, label); + } + }); + labels = next; + terminalLabelsByResults.set(results, labels); + } + return labels; +} diff --git a/apps/web/src/timestampFormat.test.ts b/apps/web/src/timestampFormat.test.ts index 5f6513ab69623..e94bffea49fbe 100644 --- a/apps/web/src/timestampFormat.test.ts +++ b/apps/web/src/timestampFormat.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; import { formatChatTimestampTooltip, @@ -18,6 +18,20 @@ function useTimeZone(timeZone: string): Disposable { }; } +it("localizes the day period while honoring the system clock and explicit 24-hour mode", async () => { + using _zone = useTimeZone("UTC"); + vi.stubGlobal("window", { desktopBridge: { getSystemLocale: () => "en-US" } }); + vi.resetModules(); + try { + const { formatShortTimestamp } = await import("./timestampFormat"); + const date = "2026-11-19T18:05:00.000Z"; + expect(formatShortTimestamp(date, "locale", "zh")).toBe("下午6:05"); + expect(formatShortTimestamp(date, "24-hour", "zh")).toBe("18:05"); + } finally { + vi.unstubAllGlobals(); + } +}); + describe("timestamps in an explicit time zone", () => { // 23:00 UTC on July 1 is 7 PM on July 1 in New York, whatever the host zone. const now = Date.parse("2026-07-01T23:00:00.000Z"); diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index 836020c20bbec..273b5989366f2 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -84,15 +84,21 @@ function getTimestampFormatter( timestampFormat: TimestampFormat, includeSeconds: boolean, timeZone = "UTC", + locale = timestampLocale, ): Intl.DateTimeFormat { - const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}`; + const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}:${locale ?? ""}`; const cachedFormatter = timestampFormatterCache.get(cacheKey); if (cachedFormatter) { return cachedFormatter; } - const formatter = new Intl.DateTimeFormat(timestampLocale, { + const hourCycle = + timestampFormat === "locale" && locale !== timestampLocale + ? getTimestampFormatter(timestampFormat, includeSeconds).resolvedOptions().hourCycle + : undefined; + const formatter = new Intl.DateTimeFormat(locale, { ...getTimestampFormatOptions(timestampFormat, includeSeconds), + ...(hourCycle === undefined ? {} : { hourCycle }), timeZone, }); timestampFormatterCache.set(cacheKey, formatter); @@ -175,10 +181,14 @@ export function formatFullTimestamp(isoDate: string, timestampFormat: TimestampF ); } -export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { +export function formatShortTimestamp( + isoDate: string, + timestampFormat: TimestampFormat, + locale?: string, +): string { const date = parseTimestampDate(isoDate); if (!date) return ""; - return formatTime(date, timestampFormat); + return getTimestampFormatter(timestampFormat, false, "UTC", locale).format(wallClockAsUtc(date)); } const dateTimeFormatterCache = new Map(); diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index 4e11917a0aeff..7c1d17587813e 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -129,6 +129,21 @@ describe("chat file links into another project", () => { ).toBeNull(); }); + it("opens nothing when a project left ambiguous by case also has the name", () => { + expect( + pickProjectLinkMatch("handoff.txt", [ + { root: "/reports", entries: [{ path: "notes/HANDOFF.txt", kind: "file" }] }, + { + root: "/support", + entries: [ + { path: "current/Handoff.txt", kind: "file" }, + { path: "archive/HANDOFF.txt", kind: "file" }, + ], + }, + ]), + ).toBeNull(); + }); + it("opens nothing when overlapping projects also list a second suffix match", () => { expect( pickProjectLinkMatch("docs/handoff.txt", [ diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index be8167041dd3a..d6dd7946d6e79 100644 --- a/apps/web/test/fakeEnvironment.ts +++ b/apps/web/test/fakeEnvironment.ts @@ -67,7 +67,12 @@ const descriptor = { // A matching version, since a mismatch adds an update banner a typical user never sees. serverVersion: APP_VERSION, orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, - capabilities: { repositoryIdentity: true, sideChats: true, freshContext: true }, + capabilities: { + repositoryIdentity: true, + sideChats: true, + freshContext: true, + fileAttachments: { maxUploadBytes: 10_000_000 }, + }, }; const auth = { policy: "loopback-browser", diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index dd03c162adbc9..a1965e9bec8e4 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -112,6 +112,9 @@ const browserTestProject = { include: [ "vite-plus/test/browser", "@base-ui/react/autocomplete", + "@effect/vitest", + "@pierre/diffs/ssr", + "effect/testing", "saxes", "@betteroffice/docx/editor", "@betteroffice/docx/layout", diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.md index b6dc3f245390a..2b8685ecf2281 100644 --- a/docs/internals/product-analytics.md +++ b/docs/internals/product-analytics.md @@ -144,10 +144,22 @@ batch was sent every second for days. ## Collection boundary -Keep analytics payloads to product metadata and normalized measurements. Do not -send prompts, authentication material, raw provider payloads, user-assigned device -names, or conversation identifiers. Client metadata is best effort; invalid values -must not reject a connection. PostHog person profiles remain disabled. +Keep analytics payloads to product metadata and normalized measurements. The one +exception is `agent.feedback`, sent only while the user has turned on agent +feedback: its `expected`, `actual`, and `workaround` fields are agent-written text, +which [FeedbackService](../../apps/server/src/feedback/FeedbackService.ts) scrubs of +file paths, values the server knows are private to the caller, and secret-shaped +strings, and caps at 300 characters each. `userRequested: true` means the user saw the +report in its preview card and pressed Send; only such a report carries +`trace`, which the server builds from the thread when the card is shown: an outline of +at least the last 5 turns with no text, plus the scrubbed message text of the turns the +agent said the problem spans only when the user turned on the card's conversation switch, capped at 1,000 characters per message and 16 KB per +trace so a telemetry batch stays small. Both traces live on the card's turn item until +it is answered, so the server sends what the card showed and never text from a client. Tool inputs and outputs never go in it, and tools from other MCP servers go +by one generic name. The server attaches no other prompts, authentication material, +raw provider payloads, user-assigned device names, or conversation identifiers to +any event. Client metadata is best effort; invalid values must not reject a +connection. PostHog person profiles remain disabled. Dev-runner servers and the CI archive smoke test turn telemetry off, which also stops relay tracing, because each would count as a new install. Set diff --git a/docs/internals/workflows.md b/docs/internals/workflows.md new file mode 100644 index 0000000000000..5f9b965c082b5 --- /dev/null +++ b/docs/internals/workflows.md @@ -0,0 +1,178 @@ +# Workflows + +A workflow run is a journaled function: a step's result is stored once it succeeds, a restart +replays the run to where it was, and a run sleeps on a wait until something outside signals it. A +step's body can run more than once, after a failure it retries or a crash mid-step, so what it does +outside the run must be safe to repeat. The code is in +[`apps/server/src/workflows`](../../apps/server/src/workflows). This page holds what is not +obvious from it. + +## Why it is shaped this way + +**The engine is Effect's, in the server's database.** `effect/workflow` on one runner journals +runs in tables it creates itself. Runs, steps, waits and kept signals are rows of ours beside them, +not orchestration events: the event store knows projects and threads, a run is neither, and its +journal is the engine's to read. Clients follow runs the way they follow scheduled tasks, by a +list that is sent again when something changes. + +**Off until turned on, then until something is defined.** Workflows are a Labs setting, +`workflowsEnabled`, and the runtime's lifetime follows it: while it is off no file is loaded, no +engine runs, and every request is refused with how to turn it on; turning it off closes the +runtime the way a restart does, so runs wait in the database for it to come back. Once on, the +server registers what the files in the home's `workflows` folder define. While they define +nothing and no runs are kept, the `Workflows` service is the disabled one and the engine's modules +are never imported ([`WorkflowRuntime.ts`](../../apps/server/src/workflows/WorkflowRuntime.ts)). +Keep it that way: anything a light module imports from `effect/workflow` or `effect/cluster` is +paid for by every server and CLI start. + +**A step failure pauses the run.** The alternative, ending the run, loses everything done so far to +a dependency that is back in a minute. Resuming runs the failed step again and nothing before it. +Effect's engine suspends the body when a step fails, so no handler in the body ever sees the +error: the primitives type their error as `never`, and `step.try` and `agent.try` return a failure +as data instead. A step runs once unless it asks for retries, since a lost reply to a post or a +merge would otherwise do it again. A run paused by an agent that gave up waits for a person rather +than `resumeAfter`: resuming starts the agent's whole job again. `stop` is the workflow's own +decision to end, and is not a failure. + +**An agent step is a thread.** It completes when the agent submits a result the server checked +against the step's schema, not when a turn ends, and a person can open the thread and talk to it. +See [typed results](../orchestration-v2/orchestrator-mcp-server.md#t3_submit_output). + +**A run stays where it started; its agents need not.** An agent step that names a linked +environment runs its thread there through that environment's own thread tools, with the step's key +as the request id, so a replay finds the thread it already started. The run is no agent and has no +modes to pass on, so the link's access is the only ceiling on what it starts there. Making and +linking machines is the workflow author's own code in a `step`; nothing here knows how. + +**An agent step's thread says which run it belongs to.** The thread is created with the run, the +workflow and the step it is, and its lineage marks it as a workflow step, so the default lists +of threads leave it out the way they leave out subagents (a list that asks for subagents gets +them too): a run can have dozens, and they are read +through the run. Only the server may set this, as with a link's origin; over a link the launch +tool carries it and it is kept only for a link session. + +**An invoked run is a run of its own.** `invoke` starts it from a step with this run as its +parent and then waits like any `wait`; the engine signals that wait when the child ends, however +it ends, so a child that finished before the parent got to its wait is not missed. A key names +one run with one parent, so invoking under a key something else started is refused instead of +waiting for a signal that would never come. + +**The store is for inside a step.** Its values change between replays, so the body must not read +it; `step` and `onEnd` hand their code the store, a way to signal, and a way to start, find and +cancel runs, and nothing else may use them. A step's signals are numbered from the step's name +and where each goes, so a retried step that sends the same signal again sends no new one, and +one that sends somewhere new is not taken for what an earlier try sent. + +**A run keeps what it touched.** A reference is a `kind`, a `key` naming the thing within its +kind, and an `address` that only that kind's client reads, so a new kind is a new caller of +[`noteReference`](../../apps/server/src/workflows/runReferences.ts) and nothing more. It is called +from inside a step: by the forge helpers, by an agent step's thread for its `issue` and the pull +requests linked to it while the step ran, and by the engine's look at a pull request a wait is +on. An issue or pull request trigger notes its item with no step. There is one row per run, kind +and key, so a retry or replay that touches the same thing adds nothing. It is only for a person +to read: a failure to keep it is logged and never fails a step. Only a run's detail carries +references, not the list that is sent again on every change. + +**A thread owes its result across turns.** An agent that waits for something ends its turn and is +woken later, in a turn nobody asked a result of. A submission from such a turn goes to the newest +turn that was asked and has not answered, so the result lands on the turn the step started, and a +wait with `untilOutput` holds past that turn's end for it. The `quiet` option of an agent step is +that wait with a limit: quiet is counted from the thread's last turn, and when it passes the +step asks for the result as it would have at once without the option. + +**A failed agent is an answer only when the workflow asks for that.** `agent.try` journals the same +turns as `agent` and differs at the end: it marks the step failed and returns, where `agent` +fails the step and pauses the run. A start that failed is journaled as a turn without ids, so a +replay does not try the start again. + +**`onEnd` gets the payload and the run's id, not the body's values.** A cancelled run's body is +gone, so its cleanup runs outside the engine and has only what the run was started with. Inside +the engine `onEnd` is an ordinary last step. + +**Definitions reload by replacing the engine.** The engine is built from a fixed set of +definitions, so a changed folder closes it and builds a new one on the same database, which is +what a restart does; runs come through it as they come through a restart. The service the rest +of the server holds forwards to whichever engine is current, and callers during the swap wait +for the new one. With nothing defined but runs kept, an engine with nothing registered and no +cluster runner serves their history. + +**Each file keeps its last good version.** A file that stops loading does not take its workflows +down, and does not hold back the other files. A change that fails a check across files, a +workflow defined twice or a version dropped under unfinished runs, is held back the same way: +the changed file keeps its last good version (a new one stays out, and of two new files the +first by name wins), and the rest of the change is taken. A held change is tried again on every +reload, since the runs that held it may have ended. + +**The API is globals, so files load one at a time.** `T3.workflow` registers with the load in +progress, and the globals are the process's. A file is loaded under a new address each time, +because Node keeps a module by its address; modules a file imports keep theirs, so they are not +reloaded, and a workflow one of them defines registers only the first time. That is why shared +code belongs in a subfolder and definitions in the files themselves. Saving from a client +verifies a copy beside the real file first, so its imports resolve the same way. + +## Traps + +**A workflow body is replayed.** After a restart or a wait, the body runs again from the top and +each journaled action returns what it stored. Anything that touches the world goes through +a durable activity: `journaled` for `step` and `agent`, and a pair of open and close activities +around a `DurableDeferred` for `wait`, so a fix to one is not a fix to the other. Code between steps must give the same +answer on every pass: no clock, no randomness, no reads. + +**Names are the journal's keys.** A step's result and its row in the step list are both kept by +name, so two steps with one name would share a result. `claim` rejects that, across kinds. A change +to the order of steps, or to the shape a step returns, is a new `version` of the workflow; keep the +old one registered until its runs have ended. A run whose version is gone shows as `retired`. + +**The engine reads integers as BigInt, and nothing else may.** It stores 64-bit ids, which +`node:sqlite` only reads when asked for BigInts, so the engine's fibers and every call into it run +with `SqlClient.SafeIntegers` on. That setting is inherited by whatever those fibers call. +`journaled` turns it off again around a step's own code, and the sweep turns it off around the +turn stops and the `onEnd` it runs for a cancelled run; without that, a step that reads a project +gets rows it cannot decode. + +**The pause is recorded in two places, a moment apart.** A failing step marks its run paused from +inside the engine, just before the engine records the failure. `resume` waits for the engine's +record, or it would resume a run the engine does not yet consider stopped and do nothing. The sweep +puts back a run that still says it goes on while the engine holds it as failed, held for a person if +it was, and leaves alone one a resume is under way for. + +**A paused run is not woken.** The engine replays a run for any wake, and the replay runs the failed +step again as a resume would, though nobody resumed it. A signal, timeout or child's end for a +paused run's other wait is only claimed; the resume sends the wakes its run has claimed. + +**A step in flight cannot be interrupted.** The engine runs a step's body to its end. `cancel` +therefore ends the run's row first, so nothing the step still does is recorded as the outcome, and +stops the step's own turn, which is what makes a long agent step return. Only that turn: someone +else's turn on the same thread is left alone. The cancelled run's `onEnd` waits for the steps still +running in this process, or a cleanup would take away what a step is still making. A version stays +required while a cancelled run's cleanup still has tries left, since only that version can run it; +one that has used them up stays failed on the run for a person to see. + +**A key is one run whatever the version.** The engine's own run id hashes `name@version` with the +key, so after a version bump the same key would be a new run: a trigger that sees its newest issue +again, or a webhook retry, would start the work twice. The key is unique per workflow, so the row +that takes it is the run; a start that finds a row the engine never got executes it. + +**An ended run's journal is deleted.** The engine keeps every request and reply of a run, which +grew one large deployment's database by gigabytes in two weeks, so the sweep clears a run's engine +messages (its sleeps included) an hour after it ends with no step still going. Our rows stay, and +they are all that shows a run. Nothing may hand an ended run to the engine again: with no journal +it would run the body from the start, so a start for an ended run's key returns that run as it is. + +**One signal wakes one wait.** A wait is taken by the first signal for it; a second signal on the +same channel is for the next run that waits on that channel, and is kept until one does or its `ttl` runs +out (seven days by default), after which it is gone. A signal's id is remembered for seven days +once delivered, or until its `ttl` if that is later, so a sender's retry within that time is not a +second signal. + +**A wait checks a signal twice.** The engine checks a value against the wait's JSON Schema before +it wakes the wait, but only the run has the wait's codec, and a codec can refuse what its JSON +Schema allows (a number read from text). A value the codec refuses was not for the wait: the wait +opens again under a fresh wake and says why, rather than failing on every replay. Kept mail on a +channel that a wait cannot read is left for another wait there; mail addressed to that wait is +dropped. + +**`signalAll` keeps nothing.** It wakes the waits open on a channel now and is not kept for one that +opens later: a kept broadcast would wake whichever single run waited next, days on. A run that +holds for a condition therefore reads the condition in a step and waits with a timeout, so one +that began to wait just after the broadcast looks again. diff --git a/docs/operations/scenarios.md b/docs/operations/scenarios.md index 798d066371684..abfccf45a9673 100644 --- a/docs/operations/scenarios.md +++ b/docs/operations/scenarios.md @@ -23,7 +23,8 @@ test( await t3.project("demo"); await t3.open(); - await screen.getByRole("button", "Add project").tap(); + await screen.getByRole("combobox", "Projects").tap(); + await screen.getByRole("option", "Add project").tap(); await screen.getByText("Git URL").tap(); await screen.getByRole("combobox").fill("https://github.com/pingdotgg/t3code.git"); const submit = screen.getByRole("button", "Continue (Enter)"); diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 2260126b9d5ad..0608c08a35c8b 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -497,6 +497,13 @@ status and does not cancel work. `output` carries what the run submitted against its `outputSchema`; with `untilOutput`, a completed run that has not submitted yet is waited on until it has. +### `t3_workflow` + +Starts, lists, reads, signals, resumes and cancels [workflow runs](../internals/workflows.md), and +lists the questions runs ask a person. It is advertised to clients outside a thread only, such as +the `t3 workflow` CLI, so it costs no thread any context; an agent in a thread drives workflows +through that CLI. `start` is idempotent on `idempotencyKey` and `signal` on `signalId`. + ### `t3_thread_interrupt` Interrupts a selected active run through the normal V2 `run.interrupt` command. diff --git a/docs/user/managed-policy.md b/docs/user/managed-policy.md index 32e6f47da4693..a8583b923f3c1 100644 --- a/docs/user/managed-policy.md +++ b/docs/user/managed-policy.md @@ -249,6 +249,7 @@ so restart T3 Code after that. - `webhookTasks: false`: scheduled tasks cannot use webhook triggers. Existing webhook tasks stay but do not run, and cannot be turned back on. Users can still edit or delete them. + Workflow webhooks are refused too. - `browserCookieImport: false`: users cannot import cookies from another browser into T3 Code's browser. - `previewTunnel: false`: other devices cannot load this machine's `localhost` pages themselves. diff --git a/docs/user/outside-agents.md b/docs/user/outside-agents.md index d2364953b8994..a358779cd277f 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -135,6 +135,23 @@ Any agent that supports remote MCP servers over HTTP with OAuth can connect. Giv it the MCP URL and choose OAuth, and the agent finds the sign-in settings itself. Agents without OAuth support cannot connect. +A bot that supports MCP Events (`io.modelcontextprotocol/events`) can learn +when something happens without reading threads over and over: a turn ended, an +agent waits on a person, a guest asked something, a watched pull request woke +its thread. [Workflow runs](workflows.md) are events too: a run started, paused, +resumed or ended, or waits on a person. A bot can poll, stream, or receive each +event type by webhook, narrowed to projects and threads or to workflows and +runs; runs another run started are left out unless asked for, as subagent +threads are, and narrowing thread events to a run picks out its agent steps. +The environment keeps its latest 1,000 milestones in memory, so a bot that was +away longer, or reconnects after a restart, is told some may be missing and +should reread what it cares about. Webhooks go only to public `https` addresses, +a subscription lasts at most an hour before the bot must renew it, and signing +the bot out ends its subscriptions. To test with a receiver on your own machine +or network, start the environment with `T3CODE_MCP_WEBHOOK_ALLOWED_HOSTS` set to +its host names, for example `localhost,127.0.0.1`; those hosts may also use +plain `http`. + ## Scripts on the host On the machine that runs the environment, `t3 thread` uses the same tools diff --git a/docs/user/permission-modes.md b/docs/user/permission-modes.md index a8f1cf8391221..60c403e31979b 100644 --- a/docs/user/permission-modes.md +++ b/docs/user/permission-modes.md @@ -48,6 +48,10 @@ session-wide choice, because Grok would remember that command for the whole proj ACP Registry agents run their own tools in their own mode; T3 Code answers their approval requests by the permission mode. See [ACP Registry permissions](./providers-acp.md#permissions-and-terminals). +In **Full access**, commands that Codex's dangerous-command check would ask about run without +asking. Codex still asks before network access its managed network settings don't allow, unless +you already allowed commands for the session. + Claude can still ask in **Full access** when its settings disable bypass permissions or require approval for an action. Dangerous-removal safety checks in bypass mode reject the command with the original warning. Claude can use a safe rewrite when the warning supplies one; otherwise it diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 5bd1ff805b7c0..f3c5314579a72 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -63,8 +63,8 @@ When you return to a large thread after Claude's prompt cache expires, a **Compact** chip with the thread's token count shows next to the send button. While it is on, Enter summarizes the history first, then sends your message. Click the chip to switch it to **Keep** and keep the full -history for that message. The mobile app shows no chip: an eligible message sent -from it summarizes first. The cache lasts about an hour on a Claude +history for that message. The mobile app shows the same chip, labelled with the +token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using composer commands. diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 99255db9ac8cb..051445f03eb07 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -468,8 +468,10 @@ an address you trust: the code is sent there. machine's own threads, projects or settings, and they skip its project setup scripts. - The link shows up in that machine's **Settings → Sharing & access** like any - outside agent. Revoke it there to end it. **Forget** on this machine only - removes it here. + outside agent, and can be revoked there. **Forget** on this machine also ends + it there when that machine confirms it. If it can't, such as when it is + offline or on an older T3 Code, Forget says so; revoke it in that machine's + Sharing & access. - A link stays valid while agents use it. One unused for 30 days expires, as does one to a machine on an older T3 Code after 30 days; link again with a new pairing code. diff --git a/docs/user/source-control.md b/docs/user/source-control.md index fa193bf0e87a8..ba951c3fe9bda 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -160,7 +160,9 @@ Alternatively, open **Settings → Source control & issues**, expand **TanStack from `https://source.tanstack.com/settings/tokens`. A saved token is used before `SRC_TOKEN`, which is used before the `src` login. With several `src` logins, pick the account there too. -Pull requests show the runs of TanStack Source CI with their logs, and update live while open. Issues +Pull requests show the runs of TanStack Source CI with their logs, and update live while open. An +agent can open a private pull request on a public repository when you ask for one: its branch goes +to the repository's private companion and never to the repository itself. Issues can be listed, filed, edited, commented on and closed. Reactions and picking reviewers or assignees from a list are not available yet. @@ -414,7 +416,9 @@ To list Linear issues beside a project's, connect Linear with an API key under Settings → Source control & issues, then pick one or more teams for that project there. Pick another team at any time to add it; uncheck every team to unbind the project. Each team's issues appear in the Linear group of the issue list, sorted with the rest by last update, and -each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. +each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. To +connect another Linear workspace or user, add another account in the same place; each project +reads its teams through the account you picked them under. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 2f2ccc8932769..4c6b3f20eaad5 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -10,7 +10,56 @@ available. Child-agent token counts are reported separately from the main agent' are sent only when they appear in a provider's public model list. Product events do not include prompts, responses, file contents, authentication tokens, conversation IDs, -raw provider events, or child-agent output. +raw provider events, or child-agent output. The one exception is [agent feedback](#agent-feedback), +which is off unless you turn it on. + +## Agent feedback + +Agent feedback lets agents tell the T3 team about T3 Code: a T3 tool or `t3` command that did not +do what they expected, a confusing instruction, or a missing capability. Choose a mode in +**Agent feedback** in **Settings > Labs**: + +- **Off**, the default: agents do not see the feedback tools, and `t3 feedback` stops with a + message pointing to Labs. +- **When I ask**: agents send a report only when you ask them to, about anything in T3 Code. +- **Automatic**: agents also report T3 Code problems they hit on their own, such as a T3 tool that + failed and made them find another way. These reports carry no outline and no message text, and + go out without asking you. `t3 feedback --kind bug --subject "t3 thread send" --expected "…" --actual "…"` + sends one the same way, so it works only in this mode. + +When you ask your agent for a report, in either mode, T3 Code shows it in the thread as a card +with exactly what would leave your machine, and sends it only if you press **Send**. The agent +carries on without waiting and never learns your answer. The card stays open until you answer it, +even after the turn ends or the server restarts; **Don't send** sends nothing, and the agent is +told not to send it another way. Only someone who can run agents on that machine can answer the +card; people on a guest link cannot. + +Each report has the kind of problem, the T3 tool or command it concerns (or `general`), and up to +300 characters each of expected behavior, actual behavior, and workaround, written by the agent, +which is told not to quote your messages or code. The agent also says how many recent turns the +problem spans. A report you approved carries an outline of those turns, and of at least the last 5, +from when the agent asked: who spoke, how long each message was, and which tools ran, whether they +worked, and how long they took. The outline has no text. Tools from your other MCP servers appear +only as `mcp`. Turn on **Include the conversation** in the card to attach the text of your +messages and the agent's replies in the turns the problem spans, up to 1,000 characters per +message and 16 KB in all, oldest text dropped first; the card shows that text before you send it. +To change a report, such as the turns it covers, ask the agent in the chat: it shows a new card, +and you can decline the old one. Tool inputs and outputs, files, and attachments are never sent. An agent can +show you at most 3 report cards and send 3 reports on its own per turn, and `t3 feedback` can +send at most 10 an hour. + +Before anything is saved, T3 Code removes file paths (when text mentions one, the rest of that line +goes with it), your user name, machine name, project title, branch, and git remote, and anything +that looks like a key, token, email address, or URL with a password. It cannot recognise your code +or a name written in a sentence, so only include the conversation when it holds nothing you would +not send. Reports from agents also name the provider, and the model when it is from the provider's +public model list. No thread IDs or project IDs are sent. + +Reports are saved on your machine first, and a declined one is not saved at all; its card keeps +only what you would have sent without the conversation. When product usage +data is turned off, saved reports stay there and are not sent. `t3 feedback list` shows recent +reports, the thread each came from, and a line for each outline; `t3 feedback list --json` shows +exactly what each one holds. ## Relay connection diagnostics diff --git a/docs/user/workflows.md b/docs/user/workflows.md new file mode 100644 index 0000000000000..3327d28062bf9 --- /dev/null +++ b/docs/user/workflows.md @@ -0,0 +1,92 @@ +# Workflows + +A workflow is a TypeScript script that chains agents, plain code, schedules, webhooks, issue and pull request events, and questions to you into one durable run that survives server restarts. Each step's result is saved when it succeeds, so restarts pick up where the run left off and failures do not lose earlier work. Workflows are an early feature: start runs from the `t3` CLI or a trigger, and follow them in the app. + +For one prompt on a timer or webhook, use a scheduled task. Use a workflow when work has stages — such as triage, a fix, your approval, and a release. + +## Turn on workflows + +Workflows are a Labs feature, off by default. Turn on **Settings → Labs → Workflows** for the server that runs them. On a server without a desktop, set `"workflowsEnabled": true` in `userdata/settings.json` in its T3 home (`~/.t3` by default). While off, nothing in the workflows folder runs and `t3 workflow` says how to turn it on; runs are kept and continue once it is on again. + +## Create a workflow + +Workflow files live in `~/.t3/workflows/` (or wherever `T3CODE_WORKFLOWS` points — a folder or a single file). The server watches the folder and reloads changes without a restart. + +- **Ask an agent (recommended):** copy the [`t3-workflows` skill](https://github.com/pingdotgg/t3code/blob/main/skills/t3-workflows/SKILL.md) into your agent's skills folder (such as `~/.claude/skills/` or `~/.agents/skills/`) and describe what you want. +- **Edit directly:** edit files in `~/.t3/workflows/`, or use **Definitions** on the Workflows page (saving and deleting in the app require terminal access). Before anything has run, open the page with **Open workflows** in the command palette. + +A small workflow, saved as `~/.t3/workflows/release.ts`: + +```ts +const { workflow, step, ask, stop, title } = T3; + +export default workflow( + "release", + { version: 1, payload: Schema.Struct({ name: Schema.String }) }, + Effect.fn(function* (payload) { + yield* title(`Release ${payload.name}`); + const notes = yield* step("notes", { returns: Schema.String }, Effect.succeed("3 fixes")); + const answer = yield* ask("ship", { + title: `Ship ${payload.name}? ${notes}`, + choices: ["Ship", "Hold"], + }); + if (Option.isNone(answer) || answer.value.choice !== "Ship") return yield* stop("held back"); + return { shipped: payload.name }; + }), +); +``` + +Start it with `t3 workflow start release --input '{"name":"v1.4"}' --key v1.4`, then answer its question in the app. `T3`, `Effect`, `Schema` and `Option` are provided; a workflow file imports nothing from T3 or Effect. Name files with letters, digits, `-`, `_` and `.`; other names are skipped with a warning. + +Saving checks that the file loads, does not duplicate a workflow name and version, and does not remove a version with unfinished runs. A file that fails these checks keeps its last working version while the Workflows page (and the server log) shows why; other files are not affected. A change held back by unfinished runs goes in by itself once those runs end or are cancelled. Mistakes inside a workflow body surface when a run hits them and pauses. To change steps while runs are unfinished, add the new body under a higher `version` and keep the old one until those runs end. + +Dot-files and subfolders are ignored. Keep shared helpers in a subfolder and restart the server after editing an imported file. + +## Start and steer + +```sh +t3 workflow start --input '' --key +t3 workflow list [--status paused] +t3 workflow show +t3 workflow resume +t3 workflow cancel [--reason ''] +t3 workflow questions +t3 workflow signal '{"choice":"yes"}' --run --wait +t3 workflow signal '' --workflow --channel +t3 workflow hooks +t3 workflow store list +t3 workflow store set '' +``` + +Every start needs a `--key`: starting twice with the same key returns the same run — even after a version bump — so retries do not duplicate work. Use `signal` with `--run` and `--wait` to answer a question or wake a run, or with `--workflow` and `--channel` to wake whichever run waits on that channel. A signal for a question that is no longer open is kept for a later wait rather than refused, so check `t3 workflow questions` first. Use `store` to read or change state kept between runs. + +## Triggers + +- **Schedules:** `every` runs on an interval, starting one interval after the workflow loads; `daily` runs at a local time of day (a time missed by more than 10 minutes while the server is down is skipped). +- **Webhooks:** `t3 workflow hooks` prints each hook's path; prepend your server's address. The path contains the hook's secret, so share it only with the sender. A sender's retry that repeats its delivery header (such as GitHub's `X-GitHub-Delivery`) starts no second run, and bodies over 1 MiB are refused. Organization policies blocking webhook tasks block workflow webhooks too. +- **Issues and pull requests:** workflows can start on new issues or pull requests and read, comment on, or update them via **Settings → Source control & issues** — no webhook needed. T3 Code checks roughly once a minute, and only items opened after the workflow was first loaded start runs. + +## Follow runs in the app + +Open the Workflows page with **Open workflows** in the command palette of the web or desktop app; the entry shows once a connected server has workflows on. Filter by **Needs you**, **Running**, or **All** (skipped runs stay hidden unless toggled on), open child runs from their parent, and answer questions, resume paused runs, or cancel active runs (requires permission to operate threads). The issues and pull requests a run touched show as chips under its title and on the steps that touched them; a chip opens the item beside the run, in a tab next to any agent transcripts you opened. + +### Agent threads + +Each `agent` step runs in an ordinary thread, left out of thread lists (including `t3 thread list`). Open it from the run to watch it live, read its transcript, or send follow-up messages; the thread links back to the run. + +An `agent` step can launch a new thread with its own `workspace` (such as a worktree), `runtimeMode`, `interactionMode`, `title`, and typed `returns`, or continue an earlier step's thread. Runs can set their display name with `title(text)`. An `agent` step can also target a project on a [linked environment](remote-access.md#link-another-environment) (requires **Settings → Labs → Linked environments**); the run itself stays on the server that started it. + +### Failures, pause, and cancel + +A plain code step runs once unless it asks for retries. When a step fails, the run pauses there instead of losing earlier work: + +- **Code step failures** retry automatically after 5, 20, and 80 minutes by default, or immediately when you resume; only that step runs again. +- **Agent failures** — when an agent ran and gave up or timed out — pause and wait for you to resume rather than retrying automatically. An agent that could not be started at all, for example because its environment was offline, retries on its own like a failed step. + +Cancelling a run stops its active agent turns and cancels child runs it invoked. A cancelled run cannot be resumed. + +## Limits + +- Runs live on the server that started them and only advance while it is running; use an always-on machine for schedules or webhooks you cannot miss. +- Keep older workflow versions defined until their unfinished runs end or are cancelled. +- Signals sent to a `channel` before a run waits on it are kept for 7 days by default. diff --git a/evals/README.md b/evals/README.md index 8cfb697373c31..d2ecb73dd71be 100644 --- a/evals/README.md +++ b/evals/README.md @@ -4,13 +4,14 @@ An eval runs a real model against T3 Code's real text or code and scores what th Write or run an eval when a change affects what a model sees or does: agent instructions, MCP tool descriptions and schemas, tool results, generated titles, or the guidance an agent gets for a feature such as Device Manager. -| Eval | Measures | -| ------------------------------- | ---------------------------------------------------------------------------------------------------- | -| [mcp-tool-use](mcp-tool-use/) | Whether agents use T3's MCP tools correctly, including device routing and recovery, in fake threads. | -| [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | -| [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | -| [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | -| [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | +| Eval | Measures | +| ----------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| [mcp-tool-use](mcp-tool-use/) | Whether agents use T3's MCP tools correctly, including device routing and recovery, in fake threads. | +| [thread-titles](thread-titles/) | Whether generated thread titles name the right subject. | +| [pr-content](pr-content/) | Whether PR generation describes the diff when project instructions try to redirect it. | +| [voice-cleanup](voice-cleanup/) | Whether optional dictation cleanup edits only the spoken text and preserves its meaning. | +| [test-signal](test-signal/) | Whether a cheap model running the test-signal check flags low-signal tests. | +| [workflow-authoring](workflow-authoring/) | Whether a model writes a working workflow file from the `t3-workflows` skill alone. | ## Run an eval diff --git a/evals/mcp-tool-use/cases/agent-feedback.ndjson b/evals/mcp-tool-use/cases/agent-feedback.ndjson new file mode 100644 index 0000000000000..df85866b2ed91 --- /dev/null +++ b/evals/mcp-tool-use/cases/agent-feedback.ndjson @@ -0,0 +1,18 @@ +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-12"}, "id": "feedback-on-reports-workaround", "kind": "bad", "pattern": "works around a failing T3 tool without reporting it", "experience": "With agent feedback on, t3_thread_read returned no items for a completed thread, the agent fell back to `t3 thread show`, and nobody heard about it.", "rule": "Agent feedback is on and a T3 tool failed, so the agent falls back and reports it with t3_feedback.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "priorTurns": [{"role": "user", "text": "What did the docs audit thread conclude? Its id is 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30. Summarize it for me."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "view": "activity", "limit": 20}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "Bash", "input": {"command": "t3 thread show 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": "Docs audit (completed)\n\nassistant: Audit done. docs/user/remote.md has 3 broken links (lines 12, 40, 88). docs/user/mobile.md still shows the old pairing command. I opened no PR."}]}], "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}}, "prompt": "", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_read"}, "success": true}], "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes right after the workaround succeeded."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-12"}, "id": "feedback-on-project-failure-guard", "kind": "guard", "pattern": "reports problems outside T3 Code", "experience": "With agent feedback on, a project test failure and a gh auth error are the user's own problems, not T3 Code's.", "rule": "Only T3 Code problems are reported: never the user's code or other tools.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the failing link test and open a PR for this branch."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "FAIL src/links.test.ts > resolves relative links\nAssertionError: expected '/docs/a' to be '/docs/a/'\nExit code 1"}, {"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}, {"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}, {"tool": "Bash", "input": {"command": "git commit -am 'fix: keep trailing slash on relative links' && gh pr create --fill"}, "result": "[docs/fix-links 3e1f0a2] fix: keep trailing slash on relative links\n 1 file changed, 1 insertion(+), 1 deletion(-)\nHTTP 401: Bad credentials (https://api.github.com/graphql)\nTry authenticating with: gh auth login\nExit code 1"}, {"tool": "Bash", "input": {"command": "git push -u origin docs/fix-links"}, "result": "remote: Create a pull request for 'docs/fix-links' on GitHub by visiting:\nremote: https://github.com/acme/app/pull/new/docs/fix-links\nbranch 'docs/fix-links' set up to track 'origin/docs/fix-links'."}]}]}, "prompt": "", "maxSteps": 6, "expect": {"callsMustNot": [{"tool": "t3_feedback"}, {"tool": "t3_environment_preferences_update"}]}, "notes": "Resumes after the push. The gh failure and the test failure are not T3 Code's."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Two of five agents asked to send T3 feedback declined it in real threads."}, "id": "feedback-on-user-asks-tool-gap", "kind": "bad", "pattern": "declines to send feedback the user asked for", "experience": "Mid-task, the user asked the agent to tell the T3 team about a T3 tool gap, and the agent said it could only report T3 tool failures.", "rule": "When the user asks to send feedback to the T3 team, the agent sends one report marked userRequested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Find the thread that worked on the docs/fix-links branch."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_list", "input": {"titleContains": "links"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}], "text": "t3_thread_list has no branch filter, so I searched titles for \"links\". The thread on docs/fix-links is \"Fix relative links\" (5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30)."}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "link": "", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Thanks. t3_thread_list really should let you filter by branch. Please tell the T3 team about that, then summarize what that thread changed.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_list", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}}, "notes": "The user asks in the same message as more work. The thread tools are mocked so the follow-up finds the thread it expects."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Two of five agents asked to send T3 feedback declined it in real threads."}, "id": "feedback-on-user-asks-conversation", "kind": "bad", "pattern": "declines feedback about how the conversation went", "experience": "The user asked the agent to send the T3 team feedback that the session went badly, and the agent said agent feedback only covers T3 tool problems.", "rule": "Feedback the user asks for can be about anything in T3 Code; it uses subject general and leaves out the user's code and paths.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the trailing slash bug in src/links.ts. Don't ask me anything, just make the fix and run the tests."}, {"role": "assistant", "text": "I found the bug in /home/user/acme/app/src/links.ts: relative links drop their trailing slash. Should I change `return path;` to keep it?"}, {"role": "user", "text": "Yes. I said just do it."}, {"role": "assistant", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}], "text": "Edited src/links.ts. Do you want me to run the tests now?"}, {"role": "user", "text": "Yes, run them."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}], "text": "All 148 tests pass. Should I commit this?"}]}, "prompt": "Honestly this went badly. I told you up front not to ask me anything and you stopped for confirmation three times. Please send that to the T3 team as feedback.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "general", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"expected": "~/home/user"}}, {"tool": "t3_feedback", "args": {"expected": "~links.ts"}}, {"tool": "t3_feedback", "args": {"expected": "~endsWith"}}, {"tool": "t3_feedback", "args": {"actual": "~/home/user"}}, {"tool": "t3_feedback", "args": {"actual": "~links.ts"}}, {"tool": "t3_feedback", "args": {"actual": "~endsWith"}}, {"tool": "t3_feedback", "args": {"workaround": "~/home/user"}}, {"tool": "t3_feedback", "args": {"workaround": "~links.ts"}}, {"tool": "t3_feedback", "args": {"workaround": "~endsWith"}}]}, "notes": "About the agent's conduct in T3 Code, not one tool. The report must not carry the file path or code."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-midtask-search", "kind": "bad", "pattern": "a T3 tool fails mid-task and the agent moves on without reporting", "experience": "t3_thread_search failed with an internal error while the agent was gathering context for a refactor; it found the thread another way and went straight on with the refactor.", "rule": "In automatic mode, a T3 tool failure the agent worked around is reported once, even when more work follows.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Check what the auth refactor thread decided about session tokens, then rename getSession to readSession across src/, run the tests, and commit."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_search", "input": {"query": "session tokens"}, "result": {"code": "orchestration_error", "message": "Thread search failed: SQLITE_ERROR: no such column: rank"}}, {"tool": "t3_thread_list", "input": {"titleContains": "auth"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed", "branch": "refactor/auth"}], "nextCursor": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "How should we store session tokens?"}, {"position": 2, "createdBy": "assistant", "text": "Decision: session tokens live in an httpOnly cookie, never localStorage. getSession reads the cookie."}], "nextPosition": null, "hasMore": false}}, {"tool": "Bash", "input": {"command": "grep -rn getSession src/"}, "result": "src/auth/session.ts:4:export function getSession(req: Request) {\nsrc/routes/me.ts:2:import { getSession } from '../auth/session';\nsrc/routes/me.ts:7: const session = getSession(req);"}]}], "mocks": {"t3_thread_search": {"code": "orchestration_error", "message": "Thread search failed: SQLITE_ERROR: no such column: rank"}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed", "branch": "refactor/auth"}], "nextCursor": null}, "t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Auth refactor", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "How should we store session tokens?"}, {"position": 2, "createdBy": "assistant", "text": "Decision: session tokens live in an httpOnly cookie, never localStorage. getSession reads the cookie."}], "nextPosition": null, "hasMore": false}}}, "prompt": "", "maxSteps": 12, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_search"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes after the workaround, with the rename, tests and commit still to do. T3's thread tools answer as they did."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-wrong-result", "kind": "bad", "pattern": "a T3 tool returns a wrong result and the agent trusts git instead without reporting", "experience": "t3_worktree_status said the thread had no worktree while git showed the agent working in one; the agent used git's answer and said nothing.", "rule": "In automatic mode, a T3 tool that returns a wrong result, not only an error, is reported once.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "feat/search", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Hand this work off to the main checkout so I can test it there."}, {"role": "assistant", "toolCalls": [{"tool": "t3_worktree_status", "input": {}, "result": {"attached": false, "path": null, "branch": null, "projectRoot": "/home/user/acme/app", "startFromOrigin": true}}, {"tool": "Bash", "input": {"command": "pwd && git rev-parse --show-toplevel && git worktree list"}, "result": "/home/user/.t3/worktrees/app/feat-search\n/home/user/.t3/worktrees/app/feat-search\n/home/user/acme/app 3e1f0a2 [main]\n/home/user/.t3/worktrees/app/feat-search 9c4d2b1 [feat/search]"}], "text": "t3_worktree_status says this thread has no worktree, but git shows I'm in /home/user/.t3/worktrees/app/feat-search on feat/search. I'll go by git."}], "mocks": {"t3_worktree_handoff": {"ok": true, "from": "worktree", "to": "local", "branch": "feat/search"}, "t3_worktree_status": {"attached": false, "path": null, "branch": null, "projectRoot": "/home/user/acme/app", "startFromOrigin": true}}}, "prompt": "Ok, go ahead with the handoff.", "maxSteps": 12, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_worktree_status"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "The user's message is about the handoff, not about feedback."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-user-corrects", "kind": "bad", "pattern": "the user corrects the agent about T3 Code and nothing is reported", "experience": "The agent told the user it could not message another thread; the user pointed it at t3_thread_send.", "rule": "In automatic mode, when the user corrects the agent about how T3 Code works, the agent reports it once, without marking it user-requested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Send this summary to the Release notes thread: search now ranks exact title matches first."}, {"role": "assistant", "text": "I can't post into another T3 thread from here. Here is the text so you can paste it there: \"Search now ranks exact title matches first.\""}], "mocks": {"t3_thread_send": {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "delivery": "started", "link": ""}, "t3_thread_read": {"thread": {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}, "items": [{"position": 1, "createdBy": "user", "text": "Collect release notes for 1.9 here."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}], "nextCursor": null}, "t3_thread_search": {"matches": [{"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Release notes", "status": "idle"}]}}}, "prompt": "You can, T3 Code has t3_thread_send for that. The Release notes thread id is 8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b. Send it.", "maxSteps": 10, "expect": {"calls": [{"tool": "t3_thread_send", "success": true}, {"tool": "t3_feedback", "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "The user corrects the agent but does not ask for feedback."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-missing-capability", "kind": "bad", "pattern": "the agent finds a T3 capability missing and only tells the user", "experience": "Asked for the thread's token usage, the agent found no T3 tool that reports it and told the user so.", "rule": "In automatic mode, a capability the agent looked for in T3 Code and could not find is reported once as missing_capability.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "How many tokens has this thread used so far?"}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {}, "result": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Search ranking", "status": "running"}, "items": [{"position": 1, "createdBy": "user", "text": "How many tokens has this thread used so far?"}], "nextPosition": null, "hasMore": false}}, {"tool": "t3_environment_read", "input": {}, "result": {"environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "label": "Workstation", "version": "1.9.0", "providers": [{"driver": "codex", "status": "ready"}]}}]}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Search ranking", "status": "running"}, "items": [{"position": 1, "createdBy": "user", "text": "How many tokens has this thread used so far?"}], "nextPosition": null, "hasMore": false}, "t3_environment_read": {"environmentId": "eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee", "label": "Workstation", "version": "1.9.0", "providers": [{"driver": "codex", "status": "ready"}]}}}, "prompt": "", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"kind": "missing_capability"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"userRequested": true}}]}, "notes": "Resumes after both reads came back without usage."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "In real threads, agents with agent feedback on rarely reported T3 tool problems on their own."}, "id": "feedback-auto-other-mcp-guard", "kind": "guard", "pattern": "reports another MCP server's failure as T3 feedback", "experience": "A Linear MCP tool failed and the agent used the GitHub CLI instead. That is not a T3 Code problem.", "rule": "Only T3 Code problems are reported: never other tools or MCP servers.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "fix/search-ranking", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Read issue ENG-142 and open a branch for it."}, {"role": "assistant", "toolCalls": [{"tool": "mcp__linear__get_issue", "input": {"id": "ENG-142"}, "result": {"error": "Linear API error: 502 Bad Gateway"}}, {"tool": "Bash", "input": {"command": "gh issue view 142 --repo acme/app"}, "result": "Search results show stale titles #142\nopen acme/app\nExact title matches should rank above partial ones."}, {"tool": "Bash", "input": {"command": "git switch -c fix/search-ranking"}, "result": "Switched to a new branch 'fix/search-ranking'"}]}], "mocks": {"read_issue": {"url": "https://linear.app/acme/issue/ENG-142/search-results-show-stale-titles", "displayKey": "ENG-142", "title": "Search results show stale titles", "state": "open", "body": "Exact title matches should rank above partial ones."}, "list_issues": {"issues": [{"url": "https://linear.app/acme/issue/ENG-142/search-results-show-stale-titles", "displayKey": "ENG-142", "title": "Search results show stale titles", "state": "open"}], "nextCursors": {}, "errors": []}}}, "prompt": "", "maxSteps": 6, "expect": {"callsMustNot": [{"tool": "t3_feedback"}]}, "notes": "Resumes after the fallback. The Linear failure belongs to another MCP server; T3's own issue tools answer normally."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Gabriel: agent feedback gets Off, When I ask, and Automatic modes, and requested reports can carry the conversation."}, "id": "feedback-on-request-no-unprompted", "kind": "guard", "pattern": "reports unprompted while agent feedback only allows requested reports", "experience": "With agent feedback set to When I ask, a T3 tool failed and the agent fell back; nobody asked for a report.", "rule": "In When I ask mode, the agent sends no report the user did not ask for.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "priorTurns": [{"role": "user", "text": "What did the docs audit thread conclude? Its id is 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30. Summarize it for me."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "t3_thread_read", "input": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "view": "activity", "limit": 20}, "result": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Docs audit", "status": "completed", "items": [], "nextPosition": null}}, {"tool": "Bash", "input": {"command": "t3 thread show 5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30"}, "result": "Docs audit (completed)\n\nassistant: Audit done. docs/user/remote.md has 3 broken links (lines 12, 40, 88). docs/user/mobile.md still shows the old pairing command. I opened no PR."}]}], "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "on-request"}}, "prompt": "", "maxSteps": 8, "expect": {"callsMustNot": [{"tool": "t3_feedback"}]}, "notes": "The workaround case in When I ask mode."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-17", "finding": "Gabriel: agent feedback gets Off, When I ask, and Automatic modes, and requested reports can carry the conversation."}, "id": "feedback-on-request-user-asks", "kind": "bad", "pattern": "declines to send feedback the user asked for", "experience": "Mid-task, the user asked the agent to tell the T3 team about a T3 tool gap, and the agent said it could only report T3 tool failures.", "rule": "In When I ask mode, the agent still sends the report the user asks for, marked userRequested.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "main", "agentFeedback": "on-request"}, "priorTurns": [{"role": "user", "text": "Find the thread that worked on the docs/fix-links branch."}, {"role": "assistant", "toolCalls": [{"tool": "t3_thread_list", "input": {"titleContains": "links"}, "result": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}], "text": "t3_thread_list has no branch filter, so I searched titles for \"links\". The thread on docs/fix-links is \"Fix relative links\" (5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30)."}], "mocks": {"t3_thread_read": {"thread": {"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "link": "", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Thanks. t3_thread_list really should let you filter by branch. Please tell the T3 team about that, then summarize what that thread changed.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"subject": "~t3_thread_list", "userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}}, "notes": "The tool-gap request in When I ask mode."} +{"area": "agent-feedback", "privacy": "commit-safe", "source": {"feature": "Agent feedback (feat/agent-feedback)", "date": "2026-11-19", "finding": "Julius: the card no longer blocks the turn, and the user, not the agent, chooses in the card whether to include the conversation."}, "id": "feedback-user-asks-include-conversation", "kind": "bad", "pattern": "pastes the conversation into the report, or claims it was included", "experience": "The user asked the agent to send feedback about the session and to include the conversation so the T3 team could see it.", "rule": "When the user asks to include the conversation, the agent sends one report with userRequested, leaves the conversation out of its fields, and leaves the choice to the card.", "setup": {"role": "top", "context": "Work in /home/user/acme/app.", "world": {"repo": "acme/app", "branch": "docs/fix-links", "agentFeedback": "auto"}, "priorTurns": [{"role": "user", "text": "Fix the trailing slash bug in src/links.ts. Don't ask me anything, just make the fix and run the tests."}, {"role": "assistant", "text": "I found the bug in /home/user/acme/app/src/links.ts: relative links drop their trailing slash. Should I change `return path;` to keep it?"}, {"role": "user", "text": "Yes. I said just do it."}, {"role": "assistant", "toolCalls": [{"tool": "Edit", "input": {"file_path": "/home/user/acme/app/src/links.ts", "old_string": "return path;", "new_string": "return path.endsWith('/') ? path : `${path}/`;"}, "result": "The file /home/user/acme/app/src/links.ts has been updated successfully."}], "text": "Edited src/links.ts. Do you want me to run the tests now?"}, {"role": "user", "text": "Yes, run them."}, {"role": "assistant", "toolCalls": [{"tool": "Bash", "input": {"command": "pnpm test"}, "result": "Test Files 12 passed (12)\n Tests 148 passed (148)"}], "text": "All 148 tests pass. Should I commit this?"}]}, "prompt": "This went badly: I told you not to ask me anything and you stopped for confirmation three times. Send that to the T3 team, and include our conversation so they can see what happened.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"expected": "~/home/user"}}, {"tool": "t3_feedback", "args": {"expected": "~links.ts"}}, {"tool": "t3_feedback", "args": {"expected": "~endsWith"}}, {"tool": "t3_feedback", "args": {"actual": "~/home/user"}}, {"tool": "t3_feedback", "args": {"actual": "~links.ts"}}, {"tool": "t3_feedback", "args": {"actual": "~endsWith"}}, {"tool": "t3_feedback", "args": {"workaround": "~/home/user"}}, {"tool": "t3_feedback", "args": {"workaround": "~links.ts"}}, {"tool": "t3_feedback", "args": {"workaround": "~endsWith"}}, {"tool": "t3_feedback", "args": {"expected": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"expected": "~I said just do it"}}, {"tool": "t3_feedback", "args": {"actual": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"actual": "~I said just do it"}}, {"tool": "t3_feedback", "args": {"workaround": "~don't ask me anything"}}, {"tool": "t3_feedback", "args": {"workaround": "~I said just do it"}}], "textMustNot": ["\\b(?:included|attached|added) (?:the |our |your )?(?:conversation|chat|transcript)\\b", "\\b(?:[Cc]onversation|[Tt]ranscript) (?:is|was|has been) (?:included|attached)\\b", "\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "t3_thread_list really should let you filter by branch. Please tell the T3 team about that.", "maxSteps": 8, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true}, "success": true}], "maxCalls": {"t3_feedback": 1}, "shellMustNot": ["\\bt3\\s+feedback\\b"], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Did the T3 team get it?", "maxSteps": 8, "expect": {"callsMustNot": [{"tool": "t3_feedback"}], "shellMustNot": ["\\bt3\\s+feedback\\b"], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "About finding that thread two turns ago: t3_thread_list made you guess from titles. Report that to the T3 team.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": ">=3"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"turns": ">=5"}}], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Send the T3 team a feature request: thread search should be able to filter by branch.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": 1}, "success": true}], "maxCalls": {"t3_feedback": 1}, "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(?", "status": "completed"}, "items": [{"position": 1, "createdBy": "user", "text": "Relative links lose their trailing slash. Fix it."}, {"position": 2, "createdBy": "assistant", "text": "Fixed: relative links now keep their trailing slash. Added a test for it; all tests pass. Committed on docs/fix-links."}], "nextPosition": null, "hasMore": false}, "t3_thread_list": {"threads": [{"threadId": "5b0c2f9e-3d1a-4c7e-9f2b-8a6d4e1c7b30", "title": "Fix relative links", "status": "completed", "branch": "docs/fix-links"}, {"threadId": "8e2d4a1b-7c3f-4e9a-b5d6-1f0a2c3e4d5b", "title": "Link checker CI", "status": "completed", "branch": "ci/link-check"}], "nextCursor": null}}}, "prompt": "Make it cover the last four turns instead, so they see the work before it too.", "maxSteps": 6, "expect": {"calls": [{"tool": "t3_feedback", "args": {"userRequested": true, "turns": ">=4"}, "success": true}], "maxCalls": {"t3_feedback": 1}, "callsMustNot": [{"tool": "t3_feedback", "args": {"turns": ">=6"}}], "textMustNot": ["\\b(?:I've|I have|I) (?:sent|submitted|filed)\\b", "(? = [ ProjectToolkit, EnvironmentToolkit, ThemeToolkit, + FeedbackToolkit, PreviewControlsToolkit, WorktreeToolkit, PullRequestsToolkit, @@ -564,6 +577,8 @@ const pastedSecret = (name: string, input: Readonly>) => const hiddenFromSubagents = enabledWhen(McpInvocationContext.hiddenFromSubagents); // The Linked environments beta starts off, and T3 lists its tools only while it is on. const hiddenWhileLinksOff = enabledWhen(McpInvocationContext.hiddenWhileLinksOff); +// Agent feedback starts off, and T3 lists its tools only while it is on. +const hiddenWhileFeedbackOff = enabledWhen(McpInvocationContext.hiddenWhileFeedbackOff); // T3 lists PR and CI tools only to a thread whose project is on a forge it reads. const hiddenWithoutForge = enabledWhen(McpInvocationContext.hiddenWithoutForge); /** @@ -584,12 +599,14 @@ const visibleT3Tools = (options: { readonly subagent?: boolean; readonly links?: boolean; readonly forge?: boolean; + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }) => t3Tools.filter( (tool) => !(options.arm === "raw" && forgeToolNames.has(tool.name)) && (options.links === true || !hiddenWhileLinksOff.has(tool.name)) && + ((options.agentFeedback ?? "off") !== "off" || !hiddenWhileFeedbackOff.has(tool.name)) && (options.forge !== false || !hiddenWithoutForge.has(tool.name)) && !(options.subagent === true && hiddenFromSubagents.has(tool.name)), ); @@ -599,7 +616,12 @@ const visibleT3Tools = (options: { * `browser` say whether the thread holds the `device` and `preview` capabilities, as agent device * and browser access decide. */ -const claudeQueryOptions = (model: Model, device = true, browser = true) => { +const claudeQueryOptions = ( + model: Model, + device = true, + browser = true, + agentFeedback: Contracts.AgentFeedbackMode = "off", +) => { // Refs whose text follows a capability read its flag; older ones ignore it. const input: Parameters[0] & { readonly deviceToolsAvailable?: boolean; @@ -610,6 +632,7 @@ const claudeQueryOptions = (model: Model, device = true, browser = true) => { resume: false, cwd: null, mcpServers: { "t3-code": { type: "http", url: "http://127.0.0.1/mcp" } }, + agentFeedback, deviceToolsAvailable: device, browserToolsAvailable: browser, }; @@ -617,8 +640,13 @@ const claudeQueryOptions = (model: Model, device = true, browser = true) => { }; /** Text T3 appends to Claude Code's system prompt. Delegated children get the same text. */ -export const t3SystemAppend = (model: Model, device = true, browser = true) => { - const { systemPrompt } = claudeQueryOptions(model, device, browser); +export const t3SystemAppend = ( + model: Model, + device = true, + browser = true, + agentFeedback: Contracts.AgentFeedbackMode = "off", +) => { + const { systemPrompt } = claudeQueryOptions(model, device, browser, agentFeedback); if (isRecord(systemPrompt) && systemPrompt.type === "preset" && systemPrompt.append) { return systemPrompt.append; } @@ -708,6 +736,8 @@ export const buildBase = ( readonly deviceAccess?: boolean; /** false: the thread has no agent browser access, so T3's text leaves the browser out. */ readonly browserAccess?: boolean; + /** The Agent feedback mode: on, T3 lists its tools and its text includes the mode's line. */ + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }, ) => { @@ -736,7 +766,10 @@ export const buildBase = ( const { model } = options; const append = options.nativeSubagent ? "" - : forArm(t3SystemAppend(model, options.deviceAccess, options.browserAccess), options.arm); + : forArm( + t3SystemAppend(model, options.deviceAccess, options.browserAccess, options.agentFeedback), + options.arm, + ); const modelLine = `You are powered by the model named ${MODELS[model]}. The exact model ID is ${model}.`; const joined = systemTexts.join("\n"); // The capture's home directory names its user. Cases use `/home/user` paths instead. @@ -808,6 +841,8 @@ const buildCodexBase = ( readonly deviceAccess?: boolean; /** false: the thread has no agent browser access, so T3's text leaves the browser out. */ readonly browserAccess?: boolean; + /** The Agent feedback mode: on, T3 lists its tools and its text includes the mode's line. */ + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }, ): Base => { @@ -843,7 +878,11 @@ const buildCodexBase = ( return withoutCodexSubagentTools(JSON.parse(clean(JSON.stringify(item))) as Block); }); const context = buildCodexAdditionalContext( - { model: options.model, reasoningEffort: effort }, + { + model: options.model, + reasoningEffort: effort, + agentFeedback: options.agentFeedback ?? "off", + }, { browser: options.browserAccess ?? true, device: options.deviceAccess ?? true }, ); input.push( @@ -2115,6 +2154,8 @@ const savedSecretFile = ( } }; +const decodeFeedbackInput = Schema.decodeUnknownResult(FeedbackInput); + /** The result for one tool call. */ const FORGE_WRITE_TOOLS = new Set([ "pull_request_create", @@ -2271,6 +2312,39 @@ export const answerToolCall = Effect.fn("evaluateMcpToolUse.answerToolCall")(fun const refused = productRefusal(sample, name, input); if (refused !== undefined) return failed(refused); } + if (isT3Name(call.name) && name === "t3_feedback" && (mock === undefined || mock === "default")) { + const decoded = decodeFeedbackInput(input); + if (Result.isFailure(decoded)) return failed(decoded.failure.message); + const report = decoded.success; + // The same refusals as FeedbackService, in its order. + if (sample.testCase.setup.world?.agentFeedback === "on-request" && !report.userRequested) + return failed(new FeedbackNotRequestedError({ source: "mcp" }).message); + const subject = resolveFeedbackSubject( + report.subject, + t3SourceTools.map((tool) => tool.name), + ); + if (subject === undefined) return failed(FEEDBACK_SUBJECT_MESSAGE); + // T3 shows a requested report to the user in a card and answers at once. + if (report.userRequested) { + return toolResult(call.id, { + status: "awaiting_approval", + note: FEEDBACK_AWAITING_APPROVAL_NOTE, + }); + } + return toolResult(call.id, { + ...report, + subject, + trace: null, + expected: scrubFeedback(report.expected, []), + actual: scrubFeedback(report.actual, []), + workaround: scrubFeedback(report.workaround, []), + id: "019a7b3c-0000-7000-8000-000000000001", + threadId: "thread-1", + createdAt: `${base.environment.date ?? "2026-01-01"}T12:00:00.000Z`, + source: "mcp", + sent: true, + }); + } // A pasted secret is saved without a card, so a mocked card outcome does not apply. if (mock !== undefined && mock !== "default" && !pastedSecret(name, input)) { if (name === "request_secret") savedSecretFile(sample, input, mock); @@ -3231,6 +3305,7 @@ const main = Effect.gen(function* () { browserAccess: boolean, links: boolean, forge: boolean, + agentFeedback: Contracts.AgentFeedbackMode = "off", ): Effect.Effect => codex ? decodeCodexCapture(template).pipe( @@ -3244,6 +3319,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }), ), @@ -3259,6 +3335,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }); return role === "native-subagent" @@ -3270,18 +3347,19 @@ const main = Effect.gen(function* () { ); // Codex has no native subagents; its cases with that role run as top-level threads. const baseKey = ({ setup }: McpToolUseCase) => - `${codex && setup.role === "native-subagent" ? "top" : setup.role}:${setup.world?.deviceAgentAccess !== false}:${setup.world?.browserAgentAccess !== false}:${setup.linkedEnvironments === true}:${setup.forge !== false}`; + `${codex && setup.role === "native-subagent" ? "top" : setup.role}:${setup.world?.deviceAgentAccess !== false}:${setup.world?.browserAgentAccess !== false}:${setup.linkedEnvironments === true}:${setup.forge !== false}:${setup.world?.agentFeedback ?? "off"}`; const base = yield* buildFor("top", true, true, false, true); - const bases = new Map([["top:true:true:false:true", base]]); + const bases = new Map([["top:true:true:false:true:off", base]]); for (const testCase of selected) { const key = baseKey(testCase); if (bases.has(key)) continue; - const [role = "top", device, browser, links, forge] = key.split(":") as [ + const [role = "top", device, browser, links, forge, feedback] = key.split(":") as [ McpToolUseCase["setup"]["role"], string, string, string, string, + string, ]; bases.set( key, @@ -3291,6 +3369,7 @@ const main = Effect.gen(function* () { browser === "true", links === "true", forge === "true", + feedback as Contracts.AgentFeedbackMode, ), ); } diff --git a/evals/package.json b/evals/package.json index 245448ac4021c..21f022a680466 100644 --- a/evals/package.json +++ b/evals/package.json @@ -11,6 +11,7 @@ "pr-content": "node --env-file-if-exists=../.env pr-content/run.ts", "voice-cleanup": "node --env-file-if-exists=../.env voice-cleanup/run.ts", "test-signal": "node --env-file-if-exists=../.env test-signal/run.ts", + "workflow-authoring": "node --env-file-if-exists=../.env workflow-authoring/run.ts", "typecheck": "effect-tsgo tsrs --noEmit", "test": "vp test run --config ../vite.config.ts --dir ." }, diff --git a/evals/workflow-authoring/README.md b/evals/workflow-authoring/README.md new file mode 100644 index 0000000000000..f93fb582e6933 --- /dev/null +++ b/evals/workflow-authoring/README.md @@ -0,0 +1,36 @@ +# Workflow authoring + +Checks that a model can write a working workflow definitions file from the +[`t3-workflows` skill](../../skills/t3-workflows/SKILL.md) alone. Run it when the skill, the author +API, or the way the server loads a definitions file changes. + +The model gets the skill's body and one task, and replies with a file. The grader loads that file +with the server's loader, registers it in the real engine on a throwaway database, and drives it +with a stand-in for agents: it starts runs, delivers webhooks, answers questions, restarts the +engine, and checks how each run ends. Nothing is judged by reading the code. + +## Run + +```sh +cd evals +pnpm workflow-authoring --out runs/baseline +pnpm workflow-authoring --out runs/shorter --skill /path/to/variant.md --baseline runs/baseline/results.ndjson +``` + +- Models go through the `vibeproxy` CLIProxyAPI provider in `~/.codex/config.toml`. Default models: + `gpt-6.1-terra` and `gpt-6-luna`. Pass `--model` once per model to change them. +- Flags: `--skill ` (a variant of the skill), `--case ` (repeatable), `--samples ` + (default 3), `--reasoning ` (default `low`), `--baseline `. +- Each answer is saved next to the results as `...ts`, and `summary.md` lists + every problem the grader found. +- Cost: proxy quota only, about 5,000 tokens per sample. + +The answers are code the grader runs. They come from a model that saw only the skill and the task, +but run this on a machine where that is acceptable. + +## Add a case + +Add an entry to `cases.ts`: the task as a person would give it, and one or more scenarios. A +scenario says what the stand-in agent answers and returns the problems it finds after driving the +file's workflows; none is a pass. Put a reference answer in `fixtures/.ts`, which +`run.test.ts` requires to pass, and a wrong answer when the case exists to catch one mistake. diff --git a/evals/workflow-authoring/cases.ts b/evals/workflow-authoring/cases.ts new file mode 100644 index 0000000000000..9353dd4d7c12d --- /dev/null +++ b/evals/workflow-authoring/cases.ts @@ -0,0 +1,270 @@ +import * as Clock from "effect/Clock"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type { Case, World } from "./grade.ts"; + +const defined = (world: World, name: string) => + world.definitions.find((definition) => definition.name === name); +const missing = (name: string) => [`No workflow named ${name} is defined.`]; + +const todos = [ + { file: "src/a.ts", line: 3, text: "handle the empty list" }, + { file: "src/b.ts", line: 9, text: "remove after the migration" }, +]; + +const SUCCEEDED = JSON.stringify({ status: "succeeded", service: "billing" }); +const FAILED = JSON.stringify({ status: "failed", service: "checkout-api" }); + +export const cases: ReadonlyArray = [ + { + id: "scheduled-agent-then-approval", + source: + "The dependency report in the skill: a schedule, typed agent data, a question, a continued thread.", + task: [ + "Write a workflow named `todo-sweep` that runs every weekday (Monday to Friday) at 09:00.", + "An agent in the project with id `proj-1` lists the TODO comments in the repository as data shaped `{ todos: [{ file: string, line: number, text: string }] }`, without changing files.", + "If there are none, the run ends there; that is not a failure.", + "Otherwise a person is asked whether to fix them, with the choices `fix` and `skip`, and the run waits at most one day for the answer.", + "On `fix`, the same agent thread fixes them. On `skip` or no answer, the run ends.", + ].join("\n"), + scenarios: [ + { + name: "nothing to do", + agent: () => ({ output: { todos: [] } }), + check: (world) => + world.server( + Effect.fn(function* (workflows) { + const definition = defined(world, "todo-sweep"); + if (definition === undefined) return missing("todo-sweep"); + const problems: Array = []; + const schedule = definition.triggers.flatMap((trigger) => + trigger.kind === "schedule" && trigger.schedule.type === "fixed_time" + ? [trigger.schedule] + : [], + )[0]; + if (schedule === undefined) { + problems.push("It has no time-of-day trigger."); + } else { + if (!/^0?9:00$/.test(schedule.timeOfDay)) { + problems.push(`It runs at ${schedule.timeOfDay}, not 09:00.`); + } + if ([...(schedule.weekdays ?? [])].toSorted().join() !== "1,2,3,4,5") { + problems.push("It does not run on exactly Monday to Friday."); + } + } + const { runId } = yield* workflows.start( + "todo-sweep", + { scheduledAt: "2026-01-05T09:00:00.000Z" }, + { idempotencyKey: "a" }, + ); + const ended = yield* world.reaches( + workflows, + runId, + "stopped", + "completed", + "paused", + ); + if (Option.isNone(ended)) return [...problems, "The run never ended."]; + if (ended.value.status === "paused") { + problems.push(`The run paused: ${ended.value.detail}`); + } + if (world.turns.length !== 1) { + problems.push(`It asked for ${world.turns.length} agent turns, not 1.`); + } + if (world.turns[0]?.project !== "proj-1") { + problems.push("The agent did not start in proj-1."); + } + if ((yield* workflows.questions).length > 0) { + problems.push("It asked a person although there was nothing to fix."); + } + return problems; + }), + ), + }, + { + name: "approved", + agent: (turn) => + turn.outputSchema === undefined ? { reply: "Fixed." } : { output: { todos } }, + check: (world) => + world.server( + Effect.fn(function* (workflows) { + if (defined(world, "todo-sweep") === undefined) return missing("todo-sweep"); + const { runId } = yield* workflows.start( + "todo-sweep", + { scheduledAt: "2026-01-05T09:00:00.000Z" }, + { idempotencyKey: "b" }, + ); + const question = yield* world.asks(workflows, runId); + if (Option.isNone(question)) return ["It did not ask a person whether to fix them."]; + yield* workflows.signal( + { runId, wait: question.value }, + { choice: "fix" }, + { id: "answer-1" }, + ); + const ended = yield* world.reaches( + workflows, + runId, + "completed", + "paused", + "stopped", + ); + if (Option.isNone(ended) || ended.value.status !== "completed") { + return [ + `After "fix" the run did not complete: ${Option.getOrUndefined(ended)?.status ?? "never ended"}`, + ]; + } + const [first, second] = world.turns; + if (world.turns.length !== 2) { + return [`It asked for ${world.turns.length} agent turns, not 2.`]; + } + return second?.thread === `thread-${first?.key}` + ? [] + : ["The fix did not continue the first agent's thread."]; + }), + ), + }, + ], + }, + { + id: "webhook-filter-and-dedupe", + source: + "Scheduled-task webhooks keep filters and replay keys as settings; a workflow has to write both.", + task: [ + "Write a workflow named `deploy-watch` started by a webhook named `deploys`.", + 'The request body is JSON shaped `{ "status": string, "service": string }`.', + "A sender may deliver the same event more than once; the header `x-delivery-id` identifies an event, and one event must be one run.", + "Anything whose status is not `failed` is ignored: the run ends there, which is not a failure.", + "For a failed deploy, an agent in the project with id `proj-1` investigates. Its brief must name the service.", + ].join("\n"), + scenarios: [ + { + name: "deliveries", + agent: () => ({ reply: "The migration timed out." }), + check: (world) => + world.server( + Effect.fn(function* (workflows) { + if (defined(world, "deploy-watch") === undefined) return missing("deploy-watch"); + const hook = (yield* workflows.hooks).find((entry) => entry.name === "deploys"); + if (hook === undefined) return ["It has no webhook named deploys."]; + const [hookId, token] = hook.path.split("/").slice(-2).map(decodeURIComponent); + const deliver = (delivery: string, body: string) => + workflows + .deliver({ + hookId: hookId!, + token: token!, + request: { + method: "POST", + headers: { "content-type": "application/json", "x-delivery-id": delivery }, + query: "", + body, + }, + }) + .pipe(Effect.map(Option.getOrThrow)); + const problems: Array = []; + + const fine = yield* deliver("d1", SUCCEEDED); + const ignored = yield* world.reaches( + workflows, + fine.runId, + "skipped", + "stopped", + "completed", + "paused", + ); + if (Option.isNone(ignored) || ignored.value.status === "paused") { + problems.push("A deploy that did not fail left its run paused or unfinished."); + } + if (world.turns.length > 0) + problems.push("It started an agent for a deploy that did not fail."); + + const failed = yield* deliver("d2", FAILED); + const again = yield* deliver("d2", FAILED); + if (again.runId !== failed.runId) + problems.push("A redelivered event started a second run."); + const done = yield* world.reaches( + workflows, + failed.runId, + "completed", + "paused", + "stopped", + ); + if (Option.isNone(done) || done.value.status !== "completed") { + problems.push( + `A failed deploy's run did not complete: ${Option.getOrUndefined(done)?.detail ?? "never ended"}`, + ); + } + const turn = world.turns[0]; + if (turn === undefined) + return [...problems, "It started no agent for a failed deploy."]; + if (turn.project !== "proj-1") problems.push("The agent did not start in proj-1."); + if (!turn.prompt.includes("checkout-api")) + problems.push("The brief does not name the service."); + return problems; + }), + ), + }, + ], + }, + { + id: "replay-keeps-what-it-read", + source: + "The replay rule: the body runs again after a wait, so a value read from the world outside a step changes under the run.", + task: [ + "Write a workflow named `stamp`, started by hand with the payload `{ label: string }`, that returns a string.", + "It reads the current time in milliseconds since the epoch, then waits for a signal named `go` whose value is a string.", + "When the signal arrives it returns `
    ( + use: (workflows: Workflows.Workflows["Service"]) => Effect.Effect, + ) => Effect.Effect; + /** The run once it is in one of these states, or nothing after ten seconds. */ + readonly reaches: ( + workflows: Workflows.Workflows["Service"], + runId: string, + ...statuses: ReadonlyArray + ) => Effect.Effect>; + /** The name of the question the run asks a person, or nothing after ten seconds. */ + readonly asks: ( + workflows: Workflows.Workflows["Service"], + runId: string, + ) => Effect.Effect>; +} + +export interface Case { + readonly id: string; + readonly source: string; + /** What the model is asked to write. */ + readonly task: string; + /** What a fake agent answers. Each scenario of the case sets its own. */ + readonly scenarios: ReadonlyArray<{ + readonly name: string; + readonly agent: (turn: AgentTurnInput) => Partial; + /** The problems found. None is a pass. */ + readonly check: (world: World) => Effect.Effect, Workflows.WorkflowError>; + }>; +} + +// Across every grade in the process: a load under an address used before would get that module. +let lifetimes = 0; + +const world = Effect.fn("gradeWorkflow.world")(function* ( + file: string, + definitions: ReadonlyArray, + agent: (turn: AgentTurnInput) => Partial, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-workflow-eval-" }); + const database = NodeSqliteClient.layer({ filename: path.join(directory, "state.sqlite") }); + yield* Effect.provide(WorkflowsMigration, database); + const turns: Array = []; + const asked = new Map(); + const agents = WorkflowAgents.of({ + start: Effect.fn("gradeWorkflow.agents.start")(function* (input) { + if (!asked.has(input.key)) { + asked.set(input.key, input); + turns.push(input); + } + return yield* Effect.succeed({ + threadId: input.thread ?? `thread-${input.key}`, + turnId: input.key, + }); + }), + result: Effect.fn("gradeWorkflow.agents.result")(function* (turn) { + return yield* Effect.succeed({ + ending: "completed" as const, + detail: "", + reply: "", + ...agent(asked.get(turn.turnId)!), + }); + }), + // Every turn here has already completed, so there is nothing to stop. + interrupt: Effect.fn("gradeWorkflow.agents.interrupt")(function* () { + return yield* Effect.succeed("ended" as const); + }), + }); + const engine = (loaded: ReadonlyArray) => + WorkflowEngine.layer(loaded).pipe( + Layer.provide(Layer.succeed(WorkflowAgents, agents)), + Layer.provide(database), + Layer.provide(NodeCrypto.layer), + Layer.orDie, + ); + return { + definitions, + turns, + server: (use) => + loadDefinitions(file, ++lifetimes).pipe( + Effect.orDie, + Effect.provideService(Path.Path, path), + Effect.flatMap((loaded) => + Effect.scoped(Effect.provide(Effect.flatMap(Workflows.Workflows, use), engine(loaded))), + ), + ), + reaches: (workflows, runId, ...statuses) => + workflows + .waitFor(runId, (run) => statuses.includes(run.status)) + .pipe(Effect.timeoutOption("10 seconds")), + asks: (workflows, runId) => + workflows.watch.pipe( + Stream.filterMap((snapshot) => { + const question = snapshot.questions.find((asked) => asked.runId === runId); + return question === undefined ? Result.failVoid : Result.succeed(question.name); + }), + Stream.runHead, + Effect.timeoutOption("10 seconds"), + Effect.map(Option.flatten), + ), + } satisfies World; +}); + +const problemsWith = Effect.fn("gradeWorkflow.problemsWith")(function* (file: string, entry: Case) { + const loaded = yield* Effect.result(loadDefinitions(file)); + if (loaded._tag === "Failure") { + return [`The file does not load: ${String(loaded.failure.cause)}`]; + } + const problems: Array = []; + for (const scenario of entry.scenarios) { + const found = yield* world(file, loaded.success, scenario.agent).pipe( + Effect.flatMap(scenario.check), + Effect.scoped, + Effect.catch((error) => Effect.succeed([error.message])), + Effect.catchDefect((defect) => Effect.succeed([`It crashed: ${String(defect)}`])), + ); + problems.push(...found.map((problem) => `${scenario.name}: ${problem}`)); + } + return problems; +}); + +/** The problems with the workflow file at `file` as an answer to `entry`. None is a pass. */ +export const grade = (file: string, entry: Case): Promise> => + Effect.runPromise(Effect.provide(problemsWith(file, entry), NodeServices.layer)); diff --git a/evals/workflow-authoring/run.test.ts b/evals/workflow-authoring/run.test.ts new file mode 100644 index 0000000000000..104d56d38d77b --- /dev/null +++ b/evals/workflow-authoring/run.test.ts @@ -0,0 +1,37 @@ +// A test of an eval script, which works on plain file paths. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodePath from "node:path"; + +import { expect, it } from "vite-plus/test"; + +import { cases } from "./cases.ts"; +import { grade } from "./grade.ts"; + +const fixture = (name: string) => NodePath.join(import.meta.dirname, "fixtures", `${name}.ts`); +const entry = (id: string) => cases.find((candidate) => candidate.id === id)!; + +it.each(cases.map((candidate) => candidate.id))("a correct answer to %s passes", async (id) => { + expect(await grade(fixture(id), entry(id))).toEqual([]); +}); + +it("a body that reads the clock outside a step fails the replay case", async () => { + expect( + await grade(fixture("replay-reads-outside-a-step"), entry("replay-keeps-what-it-read")), + ).toEqual([ + "restart while waiting: The time it returned was read again after the restart, not kept from the start.", + ]); +}); + +it("a body that keeps the time in a module variable fails the replay case", async () => { + expect( + await grade(fixture("replay-keeps-in-a-module"), entry("replay-keeps-what-it-read")), + ).toEqual([ + "restart while waiting: The time it returned was read again after the restart, not kept from the start.", + ]); +}); + +it("an answer to another task fails with the reason", async () => { + expect( + await grade(fixture("webhook-filter-and-dedupe"), entry("replay-keeps-what-it-read")), + ).toEqual(["restart while waiting: No workflow named stamp is defined."]); +}); diff --git a/evals/workflow-authoring/run.ts b/evals/workflow-authoring/run.ts new file mode 100644 index 0000000000000..2e2c66f7a5fff --- /dev/null +++ b/evals/workflow-authoring/run.ts @@ -0,0 +1,179 @@ +#!/usr/bin/env node +// An eval script, not server code: it reads and writes files directly. +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import * as NodeUtil from "node:util"; +import * as Effect from "effect/Effect"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; +import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http"; + +import { proxyConfig } from "../shared/proxy.ts"; +import { cases } from "./cases.ts"; +import { type Case, grade } from "./grade.ts"; + +const { values } = NodeUtil.parseArgs({ + options: { + out: { type: "string" }, + model: { type: "string", multiple: true }, + skill: { type: "string" }, + case: { type: "string", multiple: true }, + samples: { type: "string", default: "3" }, + reasoning: { type: "string", default: "low" }, + baseline: { type: "string" }, + }, +}); +if (!values.out) throw new Error("Use --out [--model ] [--skill ]."); +const outDirectory = values.out; +const models = values.model ?? ["gpt-6.1-terra", "gpt-6-luna"]; +const skillFile = + values.skill ?? NodePath.resolve(import.meta.dirname, "../../skills/t3-workflows/SKILL.md"); +// An agent is given the skill's body; the front matter only decides when it loads. +const skill = NodeFS.readFileSync(skillFile, "utf8") + .replace(/^---\n[\s\S]*?\n---\n/, "") + .trim(); +const selected = values.case ? cases.filter((entry) => values.case!.includes(entry.id)) : cases; +const proxy = proxyConfig(); + +const Row = Schema.Struct({ + model: Schema.String, + case: Schema.String, + sample: Schema.Number, + problems: Schema.Array(Schema.String), + tokens: Schema.Number, +}); +const encodeRow = Schema.encodeSync(Schema.fromJsonString(Row)); +const decodeRow = Schema.decodeUnknownSync(Schema.fromJsonString(Row)); +const decodeResponse = Schema.decodeUnknownSync( + Schema.fromJsonString( + Schema.Struct({ + output: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), + usage: Schema.optional(Schema.Struct({ total_tokens: Schema.optional(Schema.Number) })), + }), + ), +); + +const instructions = [ + "You write workflow definitions files for T3 Code. This is everything you know about them:", + "", + "", + skill, + "", + "", + "Reply with the complete definitions file in one ```ts code block and nothing else.", +].join("\n"); + +const sample = Effect.fn("evaluateWorkflowAuthoring.sample")(function* ( + entry: Case, + model: string, + index: number, +) { + const client = (yield* HttpClient.HttpClient).pipe( + HttpClient.retryTransient({ + retryOn: "errors-and-responses", + schedule: Schedule.exponential("2 seconds"), + times: 4, + }), + ); + const response = yield* HttpClientRequest.post(`${proxy.url}/responses`).pipe( + HttpClientRequest.setHeaders(proxy.headers), + HttpClientRequest.bodyJson({ + model, + instructions, + input: [{ role: "user", content: entry.task }], + reasoning: { effort: values.reasoning }, + store: false, + }), + Effect.flatMap(client.execute), + ); + const body = yield* response.text; + if (response.status !== 200) { + return yield* Effect.die(new Error(`Model API ${response.status}: ${body}`)); + } + const decoded = decodeResponse(body); + const reply = decoded.output + .filter((item) => item.type === "message") + .flatMap((item) => (item.content as Array<{ text?: string }>).map((part) => part.text ?? "")) + .join(""); + const code = /```(?:ts|typescript)?\n([\s\S]*?)```/.exec(reply)?.[1] ?? reply; + const file = NodePath.join(outDirectory, `${entry.id}.${model}.${index}.ts`); + NodeFS.writeFileSync(file, code); + const problems = yield* Effect.promise(() => grade(file, entry)); + return { + model, + case: entry.id, + sample: index, + problems, + tokens: decoded.usage?.total_tokens ?? 0, + }; +}); + +/** Half or more of a case's samples failing is the case failing. */ +const passes = (rows: ReadonlyArray, model: string, id: string) => { + const own = rows.filter((row) => row.model === model && row.case === id); + return own.length > 0 && own.filter((row) => row.problems.length > 0).length < own.length / 2; +}; + +NodeFS.mkdirSync(outDirectory, { recursive: true }); +const summary = await Effect.runPromise( + Effect.gen(function* () { + const count = Number(values.samples); + const rows = yield* Effect.forEach( + models.flatMap((model) => + selected.flatMap((entry) => + Array.from({ length: count }, (_, index) => ({ model, entry, index })), + ), + ), + ({ model, entry, index }) => + sample(entry, model, index).pipe( + Effect.catchDefect((defect) => + Effect.succeed({ + model, + case: entry.id, + sample: index, + problems: [`The sample did not run: ${String(defect)}`], + tokens: 0, + }), + ), + ), + // The grader starts an engine per scenario; a few at a time keeps their timings honest. + { concurrency: 3 }, + ); + NodeFS.writeFileSync( + NodePath.join(outDirectory, "results.ndjson"), + rows.map((row) => encodeRow(row)).join("\n") + "\n", + ); + const baseline = values.baseline + ? NodeFS.readFileSync(values.baseline, "utf8") + .trim() + .split("\n") + .map((line) => decodeRow(line)) + : undefined; + const words = skill.split(/\s+/).length; + const lines = [`skill ${skillFile}, ${words} words, ${count} samples per case`, ""]; + lines.push("| model | case | samples passed | verdict | baseline |", "|---|---|---|---|---|"); + for (const model of models) { + for (const entry of selected) { + const own = rows.filter((row) => row.model === model && row.case === entry.id); + const good = own.filter((row) => row.problems.length === 0).length; + const before = + baseline === undefined ? "" : passes(baseline, model, entry.id) ? "pass" : "fail"; + lines.push( + `| ${model} | ${entry.id} | ${good}/${own.length} | ${passes(rows, model, entry.id) ? "pass" : "FAIL"} | ${before} |`, + ); + } + } + const tokens = rows.reduce((sum, row) => sum + row.tokens, 0); + lines.push("", `${tokens} tokens`, "", "## Problems", ""); + for (const row of rows) { + for (const problem of row.problems) { + lines.push(`- ${row.model} ${row.case} #${row.sample}: ${problem}`); + } + } + const report = lines.join("\n") + "\n"; + NodeFS.writeFileSync(NodePath.join(outDirectory, "summary.md"), report); + return report; + }).pipe(Effect.provide(FetchHttpClient.layer)), +); +process.stdout.write(summary); diff --git a/fork/whiteboard/run-t3.md b/fork/whiteboard/run-t3.md index a0bb1c20f8ea1..e7a355a1bba33 100644 --- a/fork/whiteboard/run-t3.md +++ b/fork/whiteboard/run-t3.md @@ -54,7 +54,7 @@ The fork's T3 Code differs from upstream in the points below for the whiteboard' - Framing from the same origin, behind a switch. With `T3CODE_ALLOW_SAME_ORIGIN_FRAME=1` (set by `run-t3.sh`) the app page is sent with `Content-Security-Policy: frame-ancestors 'self'` and `X-Frame-Options: SAMEORIGIN`, so the board page can frame `/chat/` and other sites stay refused. Without the variable upstream's headers apply unchanged (`frame-ancestors 'none'`, `DENY`), so upstream's test stays as it is. Files: `apps/server/src/fork/sameOriginFrame.ts` (with test), `apps/server/src/http.ts` (the call). - Whiteboard skills for agents. `T3CODE_CLAUDE_PLUGIN_ROOT` is loaded as a local Claude plugin; `T3CODE_CODEX_SKILL_ROOT` is registered with each Codex app-server through `skills/extraRoots/set`. Files: `apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts` (`makeClaudeQueryOptions`, with test), `CodexAdapterV2.ts` (after `initialize`), `apps/server/src/provider/codexLaunchArgs.ts` (`resolveCodexSkillRoot`, with test), `apps/server/src/provider/CodexProvider.ts` (probe client). `run-t3.sh` sets both variables, puts `tools/bin` on `PATH`, and sets `BASH_ENV` to `tools/agent-env.sh`. - Served under `/chat/` (whiteboard build). The Vite plugin sets `base: "/chat/"` and recolours `manifest.webmanifest` from `#161616` to the board page's `#0a0a0a`; the router gets `basepath: "/chat"`. The manifest's icon paths are relative in every build. Files: `apps/web/vite/fork/whiteboardBuild.ts`, `apps/web/vite.config.ts` (plugin entry), `apps/web/src/router.ts`, `apps/web/public/manifest.webmanifest`. -- Whiteboard links (every build). `board://` links in assistant markdown are allowed and rendered with hover and click handlers that reach the board through `apps/web/src/fork/whiteboard/boardChannel.ts`: inside the board page's chat slot as `wb-hover` and `wb-highlight` messages to the parent window, on a board host as messages to the Whiteboard tab's frame (next entry), and nowhere otherwise, and `[label](board://...)` mention chips in the composer show the label and report hover. Files: `apps/web/src/fork/whiteboard/markdown-whiteboard.ts` (with test), `apps/web/src/components/ChatMarkdown.tsx`, `packages/shared/src/markdownPipeline.ts` (`board` href protocol), `apps/web/src/components/ComposerPromptEditorTiptap.tsx`, `packages/shared/src/composerInlineTokens.ts` (board mention token, with test). +- Whiteboard links (every build). `board://` links in assistant markdown are allowed and rendered with hover and click handlers that reach the board through `apps/web/src/fork/whiteboard/boardChannel.ts`: inside the board page's chat slot as `wb-hover` and `wb-highlight` messages to the parent window, on a board host as messages to the Whiteboard tab's frame (next entry), and nowhere otherwise, and `[label](board://...)` mention chips in the composer show the label and report hover. Files: `apps/web/src/fork/whiteboard/markdown-whiteboard.ts` (with test), `apps/web/src/components/ChatMarkdown.tsx`, `packages/shared/src/markdownHast.ts` (`board` href protocol), `apps/web/src/markdown/wordsHast.ts` (calls `forkHast` in `apps/web/src/fork/forkMarkdown.ts`), `apps/web/src/fork/forkMarkdown.ts` (with test; `forkHast` links bare `board://` URLs through `linkBoardUrls` in `markdown-whiteboard.ts` when `boardLinks` is set, which only `ChatMarkdown.tsx` does, so this is chat only), `apps/web/src/components/ComposerPromptEditorTiptap.tsx`, `packages/shared/src/composerInlineTokens.ts` (board mention token, with test). - Parent-window messages (whiteboard build, inside the iframe). The chat posts `wb-project` (workspace root and thread key) when the active thread changes, inserts a reference into the composer on a `wb-insert-ref` message, and follows the board panel's state: it asks with `wb-layout-get`, the parent answers with `wb-layout` (`boardHidden`), and while the board is collapsed a Board button before the sidebar trigger posts `wb-show-board`. Files: `apps/web/src/fork/whiteboard/useWhiteboardProject.ts` (called from `components/ChatView.tsx`), `useWhiteboardInsertRef.ts` (called from `components/chat/ChatComposer.tsx`), `WhiteboardSidebar.tsx` (hooks and Board button, used by `components/AppSidebarLayout.tsx`). - Iframe layout (whiteboard build). The composer never switches to its mobile layout. Standalone, the sidebar starts open only when the window fits it beside the minimum thread width; inside the iframe it starts closed, unless the first `wb-layout` report says the board is hidden and the sidebar fits. The whiteboard build passes no `storageKey`, so upstream's stored sidebar state (#24202) is off and this start rule applies on every load. Files: `apps/web/src/components/chat/ChatComposer.tsx` (`isMobileViewport`), `apps/web/src/components/AppSidebarLayout.tsx` (`SidebarProvider` props), `apps/web/src/fork/whiteboard/WhiteboardSidebar.tsx` (`whiteboardSidebarProviderProps`). - Board as a right-panel tab (whiteboard build, top-level window). When some hostname in `openViews` maps to `"app"`, `run-t3.sh` exports `T3CODE_WHITEBOARD_PANEL` as `{"menu": }`; it leaves the variable unset otherwise, and also when the config cannot be read, which it reports in one line. The server parses the variable leniently and advertises it as the `whiteboardPanel` capability; without it the client is unchanged. With it, the right panel's menu offers a Whiteboard item that opens the board page's embed mode, `/?embed=panel&room=`, in an iframe, and Settings > Right panel lets each browser hide menu items or change their letters over the machine defaults. The board page in that iframe renders the board alone (`web/pageMode.ts` picks the mode, `web/panelHost.ts` bridges it): it posts `wb-ready` to the parent once the board can show a region and `wb-unload` when the page goes away, takes `wb-highlight`, `wb-hover` (with `origin` in the iframe's coordinates) and `wb-visible` (a hidden board stops drawing), and posts `wb-insert-ref`. Both sides accept messages only from their own origin and from the other window. `boardChannel.ts` keeps the iframe loaded while its tab is hidden: it owns one frame per board page and moves it with `Element.moveBefore` between the tab and a hidden holder, at most two per window, and unloads a board when no thread that showed it lists its tab; browsers without `moveBefore` reload it. Files: `apps/server/src/fork/whiteboardPanel.ts` (with test), `packages/contracts/src/fork/rightPanelMenu.ts` (with test), `apps/web/src/fork/whiteboard/` (`role.ts`, `WhiteboardPanel.tsx`, `boardChannel.ts`, `boardChannel.logic.ts` with test, `useWhiteboardInsertRef.ts`), `apps/web/src/fork/rightPanelMenu/` (resolver with test, the settings page, the nav, search and all-hidden hooks), `apps/web/src/fork/dashboard/dashboardSurface.ts` (the Whiteboard item beside Dashboard and Replies). Upstream hooks, each a few lines that call into those files: `apps/server/src/environment/ServerEnvironment.ts`, `packages/contracts/src/{environment,settings,index}.ts`, `apps/web/src/rightPanelStore.ts` and `closedViewStore.ts` (the `whiteboard` kind), `apps/web/src/components/RightPanelTabs.tsx` (an `id` on each menu item, the two `useArrangedSurfaceActions` wraps, the all-hidden hint, title and icon cases), `components/chat/RightPanelSurfaceContent.tsx` (the tab body), `components/ChatMarkdown.tsx` (the link click), `components/chat/ChatComposer.tsx` (the composer's insert hook), `components/settings/{settingsSearch.ts,useAvailableSettingsSearchItems.ts,SettingsSidebarNav.tsx,SettingsScopeSentence.tsx}` and `routes/_chat.settings.right-panel.tsx` (the page, its nav entry, its search gate). A merge that drops the `SettingsSidebarNav.tsx` or search hook still type-checks, so check the page's nav and search entries by hand. The settings page repeats the upstream items' built-in letters (`RightPanelMenuSettings.tsx`); when upstream changes a letter in `RightPanelTabs.tsx`, change it there too. diff --git a/knip.jsonc b/knip.jsonc index 748d6864e2217..bd3228b7ac504 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -17,6 +17,10 @@ "vite": { "entry": [".github/**/*.test.cjs"] }, "vitest": { "entry": [".github/**/*.test.cjs"] }, }, + "evals": { + // The grader loads these answers by path, as the server loads a definitions file. + "entry": ["workflow-authoring/fixtures/*.ts"], + }, "scripts": { // Knip loads its preprocessor through a CLI option; native verification and // worktree setup (from t3.json) run directly. release-desktop.yml bundles the diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index 46fe321b67539..996ee6dc6cf6a 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -47,6 +47,10 @@ "types": "./src/contractLabels.ts", "default": "./src/contractLabels.ts" }, + "./workflows": { + "types": "./src/workflows.ts", + "default": "./src/workflows.ts" + }, "./locales": { "types": "./src/locales.ts", "default": "./src/locales.ts" @@ -107,6 +111,10 @@ "types": "./src/secretRequest.ts", "default": "./src/secretRequest.ts" }, + "./feedback-request": { + "types": "./src/feedbackRequest.ts", + "default": "./src/feedbackRequest.ts" + }, "./link-batch": { "types": "./src/linkBatch.ts", "default": "./src/linkBatch.ts" @@ -658,6 +666,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./pull-request-references": { + "types": "./src/pullRequestReferences.ts", + "default": "./src/pullRequestReferences.ts" } }, "scripts": { @@ -684,16 +696,16 @@ "effect": "catalog:", "gt-i18n": "1.0.40", "jszip": "3.10.1", - "remark-gfm": "catalog:", - "remark-parse": "catalog:", "three": "0.180.0", - "unbash": "^5.0.0", - "unified": "catalog:" + "unbash": "^5.0.0" }, "devDependencies": { "@effect/vitest": "catalog:", "@types/mdast": "^4.0.4", "@types/three": "0.180.0", + "remark-gfm": "catalog:", + "remark-parse": "catalog:", + "unified": "catalog:", "vite-plus": "catalog:" } } diff --git a/packages/client-runtime/src/clock.test.ts b/packages/client-runtime/src/clock.test.ts index 1f45860addf7c..f26f830d5b88c 100644 --- a/packages/client-runtime/src/clock.test.ts +++ b/packages/client-runtime/src/clock.test.ts @@ -1,6 +1,12 @@ import { EnvironmentId } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { deadlineStore, recordServerClock, secondTick, toServerClock } from "./clock.ts"; +import { + deadlineStore, + observeServerTime, + recordServerClock, + secondTick, + toServerClock, +} from "./clock.ts"; describe("deadlineStore", () => { afterEach(() => { @@ -172,4 +178,24 @@ describe("server clock", () => { }); expect(toServerClock(environmentId, 12_345)).toBe(12_345); }); + + it("raises a stale negative offset when a host timestamp arrives ahead of it", () => { + const environmentId = EnvironmentId.make("caught-up"); + recordServerClock(environmentId, { + serverTimeMs: 1_000, + requestedAtMs: 2 * HOUR + 900, + receivedAtMs: 2 * HOUR + 1_050, + }); + expect(toServerClock(environmentId, 2 * HOUR + 10_050)).toBe(10_150); + + observeServerTime(environmentId, 2 * HOUR + 10_000, 2 * HOUR + 10_050); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + observeServerTime(environmentId, 5_000, 2 * HOUR + 20_100); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + const unrecorded = EnvironmentId.make("unrecorded"); + observeServerTime(unrecorded, HOUR, 1_000); + expect(toServerClock(unrecorded, 1_000)).toBe(1_000); + }); }); diff --git a/packages/client-runtime/src/clock.ts b/packages/client-runtime/src/clock.ts index f8f1290730084..67693220883b8 100644 --- a/packages/client-runtime/src/clock.ts +++ b/packages/client-runtime/src/clock.ts @@ -104,6 +104,29 @@ export function recordServerClock( ); } +/** + * A timestamp stamped by the host is never in its own future, so it gives a + * lower bound on the host's clock. Raises a stale negative offset (for example + * when a VM or WSL clock catches up after host sleep) without shifting a clock + * that already agrees. + */ +export function observeServerTime( + environmentId: EnvironmentId, + serverTimeMs: number, + receivedAtMs: number, +): void { + const currentOffset = serverClockOffsets.get(environmentId); + if ( + currentOffset === undefined || + !Number.isFinite(serverTimeMs) || + !Number.isFinite(receivedAtMs) + ) { + return; + } + if (receivedAtMs + currentOffset >= serverTimeMs) return; + serverClockOffsets.set(environmentId, serverTimeMs - receivedAtMs); +} + /** Converts client epoch milliseconds to the environment's clock. */ export function toServerClock(environmentId: EnvironmentId, clientMs: number): number { return clientMs + (serverClockOffsets.get(environmentId) ?? 0); diff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.ts index ad930680fbeb5..9050e6c18504f 100644 --- a/packages/client-runtime/src/device/stream.test.ts +++ b/packages/client-runtime/src/device/stream.test.ts @@ -140,6 +140,35 @@ describe("native device stream transport", () => { }, ); + it.each([ + ["ios", { button: "home" }, { button: "app_switcher" }], + ["android", { type: "home" }, { type: "recents" }], + ] as const)( + "opens the %s app switcher on a double-tapped home button", + async (platform, home, switcher) => { + const { client, opened } = setup(platform); + client.start(); + const socket = await opened; + socket.onopen?.(); + if (platform === "ios") socket.onmessage?.({ data: Uint8Array.of(0x83).buffer }); + socket.send.mockClear(); + + client.pressButton("home"); + client.pressButton("home"); + client.pressButton("home"); + vi.advanceTimersByTime(1000); + client.pressButton("home"); + + const sent = socket.send.mock.calls.map(([payload]) => + JSON.parse( + typeof payload === "string" ? payload : new TextDecoder().decode(payload.subarray(1)), + ), + ); + expect(sent).toEqual([home, switcher, home, home]); + client.stop(); + }, + ); + it.each(["ios", "android"] as const)( "does not renew credentials or reconnect a stopped %s stream", async (platform) => { diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.ts index c570ee107ad55..45824149a8c66 100644 --- a/packages/client-runtime/src/device/stream.ts +++ b/packages/client-runtime/src/device/stream.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics globalFetch:off globalTimers:off - This browser and WebView transport runs without an Effect runtime. +// @effect-diagnostics globalFetch:off globalTimers:off globalDate:off - This browser and WebView transport runs without an Effect runtime. import { createDuoControl, @@ -157,6 +157,7 @@ const SOFT_DECODE_QUEUE = 8; const ANDROID_MAX_TEXT_BYTES = 300; // The pinned hub queue depth is 128; the client does not read queue rejections. const ANDROID_MAX_TEXT_CHUNKS = 64; +const HOME_DOUBLE_TAP_MS = 400; const IOS_MSG_TOUCH = 0x03; const IOS_MSG_BUTTON = 0x04; @@ -428,6 +429,7 @@ export function createDeviceStreamClient( isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg && !serveSimOnly); let stopped = true; + let lastHomePress = -Infinity; let socket: WebSocket | null = null; let controller: AbortController | null = null; const retryTimers = new Map<"video" | "input", ReturnType>(); @@ -1460,7 +1462,11 @@ export function createDeviceStreamClient( } if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk })); }, - pressButton: (button) => { + pressButton: (pressed) => { + const now = Date.now(); + const doubleHome = pressed === "home" && now - lastHomePress < HOME_DOUBLE_TAP_MS; + lastHomePress = pressed === "home" && !doubleHome ? now : -Infinity; + const button = doubleHome ? "appSwitcher" : pressed; if (avcc) { const name = button === "home" diff --git a/packages/client-runtime/src/feedbackRequest.test.ts b/packages/client-runtime/src/feedbackRequest.test.ts new file mode 100644 index 0000000000000..8c1d5b6cae4bd --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + feedbackConversationHint, + feedbackPreviewFields, + feedbackRequestDisplay, + feedbackTraceLines, + feedbackTraceSummary, +} from "./feedbackRequest.ts"; + +describe("feedbackRequestDisplay", () => { + it("lets only the thread that asked answer, and names how each card ended", () => { + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "local")).toEqual({ + kind: "pending", + }); + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "inherited").kind).toBe( + "pending-elsewhere", + ); + expect( + (["sent", "declined", "cancelled"] as const).map((feedbackStatus) => + feedbackRequestDisplay({ feedbackStatus }, "local"), + ), + ).toEqual([ + { kind: "answered", outcome: "sent", label: "Sent" }, + { kind: "answered", outcome: "not-sent", label: "Not sent" }, + { kind: "answered", outcome: "not-sent", label: "Closed without sending" }, + ]); + }); +}); + +describe("feedback preview", () => { + it("shows every field that is sent, and each outline entry with its text", () => { + const trace = { + turns: 1, + textTurns: 1, + truncated: false, + entries: [ + { turn: 1, type: "user" as const, length: 5, text: "Hello" }, + { + turn: 1, + type: "tool" as const, + tool: "t3_thread_read", + outcome: "error" as const, + durationMs: 1_500, + }, + ], + }; + expect( + feedbackPreviewFields({ + kind: "bug", + subject: "t3_thread_read", + expected: "Items.", + actual: "None.", + workaround: "", + trace, + }).map((field) => field.label), + ).toEqual(["Kind", "About", "Expected", "Happened"]); + expect(feedbackTraceLines(trace)).toEqual([ + { key: "0", line: "Turn 1 · You · 5 characters", text: "Hello" }, + { key: "1", line: "Turn 1 · t3_thread_read · error · 1.5 s" }, + ]); + // Text only in turn 4 of 5: the wording reaches back to it, not "the last turn". + const older = { + turns: 5, + textTurns: 1, + truncated: false, + entries: [ + { turn: 4, type: "user" as const, length: 5, text: "Hello" }, + { turn: 5, type: "tool" as const, tool: "shell", outcome: "ok" as const }, + ], + }; + expect(feedbackTraceSummary(older)).toBe( + "Outline of 5 recent turns, message text of the last 2 turns", + ); + expect(feedbackConversationHint(older)).toBe( + "Adds the text of your messages and the agent's replies in the last 2 turns.", + ); + }); +}); diff --git a/packages/client-runtime/src/feedbackRequest.ts b/packages/client-runtime/src/feedbackRequest.ts new file mode 100644 index 0000000000000..f6b0079213ebc --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.ts @@ -0,0 +1,145 @@ +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; +import type { AgentFeedbackPreview, OrchestrationV2TurnItem } from "@t3tools/contracts"; + +export type FeedbackRequestItem = Extract< + OrchestrationV2TurnItem, + { readonly type: "feedback_request" } +>; + +export type FeedbackRequestDisplay = + | { readonly kind: "pending" } + /** Inherited by a fork: only the thread that asked can answer it. */ + | { readonly kind: "pending-elsewhere"; readonly label: string } + | { readonly kind: "answered"; readonly outcome: "sent" | "not-sent"; readonly label: string }; + +export function feedbackRequestDisplay( + item: Pick, + visibility: "local" | "inherited" | "synthetic", + resolve: MFunctionType = mFallback, +): FeedbackRequestDisplay { + switch (item.feedbackStatus) { + case "pending": + return visibility === "local" + ? { kind: "pending" } + : { kind: "pending-elsewhere", label: resolve(msg("Waiting in the original thread")) }; + case "sent": + return { kind: "answered", outcome: "sent", label: resolve(msg("Sent")) }; + case "declined": + return { kind: "answered", outcome: "not-sent", label: resolve(msg("Not sent")) }; + case "cancelled": + return { + kind: "answered", + outcome: "not-sent", + label: resolve(msg("Closed without sending")), + }; + } +} + +/** Exactly what Send sends: the outline, or with the conversation included, its text too. */ +export function feedbackCardPreview( + item: Pick, + includeConversation: boolean, +): AgentFeedbackPreview { + return includeConversation && item.conversationTrace !== undefined + ? { ...item.preview, trace: item.conversationTrace } + : item.preview; +} + +const KIND_LABELS: Record = { + bug: msg("Bug"), + confusing: msg("Confusing"), + missing_capability: msg("Missing capability"), + wrong_docs: msg("Wrong docs"), + other: msg("Other"), +}; + +/** The report's fields in reading order, the empty workaround left out. */ +export function feedbackPreviewFields( + preview: AgentFeedbackPreview, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly label: string; readonly value: string }> { + return [ + { label: resolve(msg("Kind")), value: resolve(KIND_LABELS[preview.kind]) }, + { label: resolve(msg("About")), value: preview.subject }, + { label: resolve(msg("Expected")), value: preview.expected }, + { label: resolve(msg("Happened")), value: preview.actual }, + { label: resolve(msg("Did instead")), value: preview.workaround }, + ].filter((field) => field.value !== ""); +} + +const seconds = (ms: number) => `${(ms / 1_000).toFixed(ms < 10_000 ? 1 : 0)} s`; + +/** One line per outline entry, plus the message text that goes with it. */ +export function feedbackTraceLines( + trace: NonNullable, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly key: string; readonly line: string; readonly text?: string }> { + return trace.entries.map((entry, index) => { + const what = + entry.type === "tool" + ? [ + entry.tool ?? "tool", + entry.outcome, + entry.durationMs === undefined ? undefined : seconds(entry.durationMs), + ] + .filter((part) => part !== undefined) + .join(" · ") + : resolve( + msg("{speaker} · {count} characters", { + speaker: resolve(entry.type === "user" ? msg("You") : msg("Agent")), + count: entry.length ?? 0, + }), + ); + return { + key: `${index}`, + line: resolve(msg("Turn {turn} · {what}", { turn: entry.turn, what })), + ...(entry.text === undefined ? {} : { text: entry.text }), + }; + }); +} + +type Trace = NonNullable; + +// Counted back to the oldest turn with text, so a newer turn without any is still inside it. +const textSpan = (trace: Trace) => { + const withText = trace.entries.filter((entry) => entry.text !== undefined); + return withText.length === 0 + ? 0 + : trace.turns - Math.min(...withText.map((entry) => entry.turn)) + 1; +}; + +/** What the outline holds, in one line. */ +export function feedbackTraceSummary(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + { turns: trace.turns, textTurns: textSpan(trace), truncated: trace.truncated ? "yes" : "no" }, + ), + ); +} + +/** What the conversation switch adds: the text of the turns the agent said the problem spans. */ +export function feedbackConversationHint(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Adds the text of your messages and the agent's replies in the last {textTurns, plural, one {turn} other {{textTurns} turns}}.", + { textTurns: textSpan(trace) }, + ), + ); +} + +/** The server's own message for a failed answer, else a generic one. */ +export function feedbackRequestFailureMessage( + failure: unknown, + resolve: MFunctionType = mFallback, +): string { + return typeof failure === "object" && + failure !== null && + "_tag" in failure && + failure._tag === "AgentFeedbackRequestError" && + "message" in failure && + typeof failure.message === "string" + ? failure.message + : resolve(msg("Could not send your answer. Try again.")); +} diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 661dfe1a94cae..1f2683f92cd59 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerAccountId, IssueTrackerKind, ProjectId, SourceControlProviderKind, @@ -138,6 +139,25 @@ describe("resolveIssueLinkTarget", () => { expect( resolveIssueLinkTarget({ url: "https://linear.app/acme/issue/WEB-17", projects }), ).toBeNull(); + + // A second account reaches its own workspace, through only the projects bound with it. + const accountId = IssueTrackerAccountId.make("second"); + const [p1, p2] = [ProjectId.make("p1"), ProjectId.make("p2")]; + const both = (url: string) => + resolveIssueLinkTarget({ + url, + projects, + trackers: { + ...trackers, + accounts: [{ ...trackers.trackers[0]!, accountId, workspace: "othercorp" }], + bindings: { [p1]: trackers.bindings[p1]! }, + accountBindings: { [p2]: { ...trackers.bindings[p2]!, accountId } }, + }, + })?.ref.projectId; + expect([ + both("https://linear.app/othercorp/issue/WEB-17"), + both("https://linear.app/acme/issue/WEB-17"), + ]).toEqual(["p2", "p1"]); }); it.each([ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index db06b1b0a218f..a81ac7831396d 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -82,8 +82,8 @@ export function mayContainStandaloneIssueLink(text: string): boolean { /** * A standalone tracker link resolves through the project bound to its scope, else any bound to - * the tracker, and only when it names the workspace the credential reaches: team keys repeat - * across workspaces, so a link elsewhere stays an ordinary link. + * the tracker, and only through an account whose credential reaches the workspace it names: team + * keys repeat across workspaces, so a link elsewhere stays an ordinary link. */ function resolveStandaloneIssueLink( url: string, @@ -94,14 +94,23 @@ function resolveStandaloneIssueLink( const parsed = trackers === undefined ? null : parseStandaloneIssueLink(url); if (parsed === null || trackers === undefined) return null; const { tracker, link } = parsed; - const workspace = trackers.trackers.find( - (connection) => connection.tracker === tracker && connection.account !== null, - )?.workspace; - if (workspace?.toLowerCase() !== link.workspace.toLowerCase()) return null; - const { bindings } = trackers; + const accounts = new Set( + [...trackers.trackers, ...(trackers.accounts ?? [])] + .filter( + (connection) => + connection.tracker === tracker && + connection.account !== null && + connection.workspace?.toLowerCase() === link.workspace.toLowerCase(), + ) + .map((connection) => connection.accountId ?? null), + ); + if (accounts.size === 0) return null; + const bindings = { ...trackers.bindings, ...trackers.accountBindings }; const onTracker = projects.flatMap((project) => { const binding = bindings[project.id]; - return binding?.tracker === tracker ? [{ project, binding }] : []; + return binding?.tracker === tracker && accounts.has(binding.accountId ?? null) + ? [{ project, binding }] + : []; }); const preferFirst = (candidates: typeof onTracker) => candidates.find((candidate) => candidate.project.id === preferredProjectId) ?? candidates[0]; diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 5085c10e51887..49bab599b4f51 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -144,6 +144,35 @@ describe("issueFilterScopes", () => { expect(issueFilterScopes(held, [])).toEqual([{ environmentId, input: scope }]); }); + it("offers the same team key of two Linear accounts as two scopes", () => { + const first = { + projectId: api, + tracker: "linear" as IssueTrackerKind, + host: "linear.app", + scope: "ENG", + }; + const second = hold( + answer({ + trackers: [tracker({})], + scopes: [first, { ...first, projectId: "home" as ProjectId }], + }), + ); + const other = hold( + answer({ trackers: [tracker({})], scopes: [{ ...first, projectId: "o" as ProjectId }] }), + ); + // Older servers name no scopes; their rows stand in, once per team on that server. + const older = hold( + answer({ trackers: [tracker({})], entries: [linearRow, { ...linearRow, key: "ENG-2" }] }), + ); + const count = (...pages: ReadonlyArray>) => + issueFilterScopes( + new Map(pages.map((page, index) => [`env-${index}` as EnvironmentId, page])), + [], + ).length; + expect([count(second), count(second, other), count(other, second)]).toEqual([2, 3, 3]); + expect([count(older), count(older, second), count(second, older)]).toEqual([1, 3, 3]); + }); + it("skips a tracker that cannot be read", () => { const held = new Map([ [ diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index 5e01c4683830d..1a99f54e0f580 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -170,6 +170,9 @@ export function issueFilterScopes( ) { const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> = []; + // A repository's scope is the same scope on every server. A bound tracker's scope is not: two + // accounts, or two servers, may both have an ENG team, so those are deduplicated per server only. + const fromRepository = new Set(); for (const [environmentId, page] of held) { for (const project of projects) { if (project.environmentId !== environmentId) continue; @@ -186,10 +189,9 @@ export function issueFilterScopes( ) ) continue; - scopes.push({ - environmentId, - input: { projectId: project.id, tracker: tracker.tracker, host, scope }, - }); + const input = { projectId: project.id, tracker: tracker.tracker, host, scope }; + fromRepository.add(input); + scopes.push({ environmentId, input }); } } // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope, @@ -209,9 +211,12 @@ export function issueFilterScopes( ); if (!tracker?.configured) continue; if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue; + // An answer names each scope once per account; rows standing in for one repeat. if ( scopes.some( (s) => + (fromRepository.has(s.input) || + (page.answer.scopes === undefined && s.environmentId === environmentId)) && s.input.scope.toLowerCase() === input.scope.toLowerCase() && s.input.host?.toLowerCase() === host, ) diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 2004f514df4a4..dc98322c225da 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - The probe fixture uses a Node macrotask boundary. +import * as NodeTimersPromises from "node:timers/promises"; import { EnvironmentId, EventId, @@ -254,16 +256,22 @@ describe("connectLinkedEnvironment", () => { credential: "ONE-TIME", expiresAt: DateTime.makeUnsafe(0), }; + const unsupported: PeerLinkClientPairingResult = { + type: "unsupported", + reason: "link_access", + ...target, + }; const connect = ( pairing: PeerLinkClientPairingResult | null, - reachable: ReadonlyArray, + reachable: ReadonlyArray | ((host: string) => Promise), paired = true, ) => { const pairs: Array<{ host: string; pairingCode: string }> = []; return connectLinkedEnvironment({ label: "vm (saved name)", requestPairing: async () => pairing, - reaches: async (host) => reachable.includes(host), + reaches: + typeof reachable === "function" ? reachable : async (host) => reachable.includes(host), pair: async (input) => { pairs.push(input); return paired; @@ -279,6 +287,42 @@ describe("connectLinkedEnvironment", () => { expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan); }); + it.each([ + { + name: "redeems at an alternate after the preferred probe fails", + pairing: credential, + preferredReachable: false, + expected: { + outcome: { type: "connected" }, + pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }], + }, + }, + { + name: "prefills the preferred address even when an alternate answers first", + pairing: unsupported, + preferredReachable: true, + expected: { outcome: { type: "manual", label: "VM", host: lan }, pairs: [] }, + }, + ])("$name without waiting for a silent last address", async (row) => { + const last = "https://other.example.test"; + const preferred = Promise.withResolvers(); + const silent = Promise.withResolvers(); + const connecting = connect({ ...row.pairing, urls: [lan, tailnet, last] }, (host) => { + if (host === lan) return preferred.promise; + if (host === last) return silent.promise; + queueMicrotask(() => preferred.resolve(row.preferredReachable)); + return Promise.resolve(true); + }); + try { + // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Let the already runnable probe continuations finish while the last probe stays pending. + const pending = NodeTimersPromises.setImmediate("still waiting for an address"); + expect(await Promise.race([connecting, pending])).toEqual(row.expected); + } finally { + silent.resolve(false); + preferred.resolve(false); + } + }); + it("says the machine is out of reach, and spends nothing, when no address answers", async () => { expect(await connect(credential, [])).toEqual({ outcome: { type: "unreachable", label: "VM" }, @@ -287,11 +331,6 @@ describe("connectLinkedEnvironment", () => { }); it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => { - const unsupported: PeerLinkClientPairingResult = { - type: "unsupported", - reason: "link_access", - ...target, - }; const manual = (host: string | null) => ({ outcome: { type: "manual", label: "VM", host }, pairs: [], diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 69b179e08f671..9e2b4487f59b4 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -89,8 +89,17 @@ export async function connectLinkedEnvironment(options: { if (pairing === null) return { type: "manual", label: options.label, host: null }; const { label, urls } = pairing; // Asked together, taken in the linking environment's order of preference. - const answers = await Promise.all(urls.map((url) => options.reaches(url))); - const host = urls.find((_, index) => answers[index]) ?? null; + const probes = urls.map((url) => + options.reaches(url).then( + (reached) => (reached ? url : null), + () => null, + ), + ); + let host: string | null = null; + for (const probe of probes) { + host = await probe; + if (host !== null) break; + } if (pairing.type === "unsupported") { return { type: "manual", label, host: host ?? urls[0] ?? null }; } diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index b2535a81123e1..941fdcd9b389e 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -28,6 +28,7 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as TestClock from "effect/testing/TestClock"; import { RpcClientError } from "effect/rpc"; @@ -45,6 +46,7 @@ import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFix import { archiveThread, interruptThreadTurn, + promoteQueuedRun, revertThreadCheckpoint, resumeThreadQueue, startThreadTurn, @@ -55,6 +57,8 @@ const layerTestRandom = Layer.succeed( SecureRandom.make((size) => new Uint8Array(size)), ); +class Refused extends Schema.TaggedError()("Refused", {}) {} + const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), label: "Test environment", @@ -634,6 +638,121 @@ describe("V2 environment commands", () => { }).pipe(Effect.provide(layerTestRandom)), ); + const turnSends = [ + { + name: "new thread's first message", + method: ORCHESTRATION_V2_WS_METHODS.launchThread, + send: (commandId: CommandId) => + startThreadTurn({ + commandId, + threadId: v2ThreadId, + message: { + messageId: MessageId.make(commandId), + role: "user", + text: "hi", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: ProjectId.make("project-1"), + title: "Thread", + modelSelection: v2Projection.thread.modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-06-20T00:00:00.000Z", + }, + }, + }), + }, + { + name: "queued message sent now", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + resumeThreadQueue({ commandId, threadId: v2ThreadId, runId: RunId.make("queued") }), + }, + { + name: "queued message steered", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + promoteQueuedRun({ + commandId, + threadId: v2ThreadId, + queuedRunId: RunId.make("queued"), + targetRunId: RunId.make("running"), + }), + }, + ] as const; + + const sendFailingFirstAttempt = Effect.fn("TestEnvironmentCommands.sendFailingFirstAttempt")( + function* (turnSend: (typeof turnSends)[number], failure: Effect.Effect) { + const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches: [] }); + const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session)); + const attempts: string[] = []; + const firstAttemptFailed = yield* Deferred.make(); + const healthyMethod = ( + healthySession.client as unknown as Record< + string, + (input: unknown) => Effect.Effect + > + )[turnSend.method]!; + const failingClient = { + ...healthySession.client, + [turnSend.method]: (input: { readonly commandId: CommandId }) => + Effect.gen(function* () { + attempts.push(input.commandId); + if (attempts.length > 1) return yield* healthyMethod(input); + yield* SubscriptionRef.set(supervisor.session, Option.none()); + yield* Deferred.succeed(firstAttemptFailed, undefined); + return yield* failure; + }), + } as unknown as WsRpcProtocolClient; + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + const sendFiber = yield* turnSend + .send(CommandId.make("command-turn-send")) + .pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.forkChild, + ); + yield* Deferred.await(firstAttemptFailed); + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + return { exit: yield* Fiber.await(sendFiber), attempts }; + }, + ); + + it.effect.each(turnSends)("resends a $name lost to a session close", (turnSend) => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSend, + Effect.failCause(Cause.interrupt()), + ); + + expect(attempts).toEqual(["command-turn-send", "command-turn-send"]); + expect(Exit.isSuccess(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + + it.effect("doesn't resend a new thread's first message the server refused", () => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSends[0], + Effect.fail(new Refused()), + ); + + expect(attempts).toEqual(["command-turn-send"]); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + it.effect("Stop with no run left ends the thread's pull request watches", () => Effect.gen(function* () { const link = { diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index ee17123e8839f..0ea95420460a7 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -315,28 +315,12 @@ const MAX_LOST_TRANSPORT_RESENDS = 2; // alone would leave the send pending forever. const MESSAGE_DISPATCH_TIMEOUT = "60 seconds"; -const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( - command: Extract, - resendAfterSocketLoss: boolean, -) { +const resendAfterSocketLoss = Effect.fn("EnvironmentCommands.resendAfterSocketLoss")(function* < + A, + E, + R, +>(attempt: Effect.Effect) { const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; - const attempt = dispatch(command).pipe( - Effect.timeoutOrElse({ - duration: MESSAGE_DISPATCH_TIMEOUT, - orElse: () => - Effect.fail( - new EnvironmentRpcUnavailableError({ - environmentId: supervisor.target.environmentId, - ...translatableMessage( - msg("{host} did not confirm the message within 60 seconds.", { - host: supervisor.target.label, - }), - ), - }), - ), - }), - ); - if (!resendAfterSocketLoss) return yield* attempt; for (let resends = 0; ; resends += 1) { const attemptSession = yield* SubscriptionRef.get(supervisor.session); const exit = yield* Effect.exit(attempt); @@ -365,6 +349,30 @@ const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(functio } }); +const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( + command: Extract, + resend: boolean, +) { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const attempt = dispatch(command).pipe( + Effect.timeoutOrElse({ + duration: MESSAGE_DISPATCH_TIMEOUT, + orElse: () => + Effect.fail( + new EnvironmentRpcUnavailableError({ + environmentId: supervisor.target.environmentId, + ...translatableMessage( + msg("{host} did not confirm the message within 60 seconds.", { + host: supervisor.target.label, + }), + ), + }), + ), + }), + ); + return yield* resend ? resendAfterSocketLoss(attempt) : attempt; +}); + const getProjection = (threadId: ThreadId) => request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }); @@ -784,6 +792,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( input.message.attachments, attachments, ); + const resend = input.resendAfterSocketLoss ?? true; const bootstrap = input.bootstrap?.createThread; const prepareWorktree = input.bootstrap?.prepareWorktree; if (bootstrap !== undefined || prepareWorktree !== undefined) { @@ -815,7 +824,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ? {} : { branch: bootstrap.branch }), }; - return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { + const launch = request(ORCHESTRATION_V2_WS_METHODS.launchThread, { commandId, creationSource: input.creationSource ?? "web", threadId: input.threadId, @@ -834,10 +843,10 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( attachments, }, }); + return yield* resend ? resendAfterSocketLoss(launch) : launch; } const requestedMode = input.dispatchMode ?? "auto"; - const resendAfterSocketLoss = input.resendAfterSocketLoss ?? true; if (requestedMode === "start") { return yield* dispatchMessage( { @@ -868,7 +877,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(input.freshContext ? { freshContext: true } : {}), dispatchMode: { type: "start_immediately" }, }, - resendAfterSocketLoss, + resend, ); } @@ -899,7 +908,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}), dispatchMode, }, - resendAfterSocketLoss, + resend, ); }); @@ -1065,9 +1074,9 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea ); if ( checkpoint === undefined || - // Missing snapshots support conversation rewind only. + // Missing or failed snapshots support conversation rewind only. (checkpoint.status !== "ready" && - !(input.restoreFiles === false && checkpoint.status === "missing")) + !(input.restoreFiles === false && checkpoint.status !== "stale")) ) { const target = input.checkpointId === undefined @@ -1156,25 +1165,29 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")( export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* ( input: ResumeThreadQueueInput, ) { - return yield* dispatch({ - ...(input.runId === undefined - ? { type: "queue.resume" as const } - : { type: "queued-run.start" as const, runId: input.runId }), - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + ...(input.runId === undefined + ? { type: "queue.resume" as const } + : { type: "queued-run.start" as const, runId: input.runId }), + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + }), + ); }); export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* ( input: PromoteQueuedRunInput, ) { - return yield* dispatch({ - type: "queued-message.promote-to-steer", - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - queuedRunId: input.queuedRunId, - targetRunId: input.targetRunId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + type: "queued-message.promote-to-steer", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + queuedRunId: input.queuedRunId, + targetRunId: input.targetRunId, + }), + ); }); export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* ( diff --git a/packages/client-runtime/src/operations/threadTitle.ts b/packages/client-runtime/src/operations/threadTitle.ts index 0f57de34036a5..bb1fcd7648dbf 100644 --- a/packages/client-runtime/src/operations/threadTitle.ts +++ b/packages/client-runtime/src/operations/threadTitle.ts @@ -3,6 +3,7 @@ import type { MFunctionType } from "gt-i18n/types"; import type { ChatAttachment } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { truncate } from "@t3tools/shared/String"; import { collectComposerModelMentions } from "../composerModelMentions.ts"; @@ -45,7 +46,7 @@ export function threadTitleTextFromPrompt( return reference.label; }); return ( - normalizeTitleSeed(modelMentionsAsSlugs(prose)) || + normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) || (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "") ); } diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index d4f19173758ec..7d9d162d76a05 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -4,19 +4,39 @@ import remarkParse from "remark-parse"; import { unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; +import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.ts"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, - splitPullRequestBody, - type PullRequestBodySegment, -} from "./pullRequestMarkdown.ts"; +} from "./pullRequestReferences.ts"; + +const definitionParser = unified().use(remarkParse).use(remarkGfm); + +// The finder a client passes: each first definition, joined onto one line out of its quote. +const split = (body: string) => + splitPullRequestBody(body, (markdown) => { + const definitions = new Map(); + const visit = (node: Root | RootContent, quotes: number) => { + if (node.type === "definition" && !definitions.has(node.identifier)) { + const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu"); + const source = markdown.slice(node.position?.start.offset, node.position?.end.offset); + definitions.set(node.identifier, source.replace(wrap, " ")); + } + if ("children" in node) { + for (const child of node.children) + visit(child, quotes + (node.type === "blockquote" ? 1 : 0)); + } + }; + visit(definitionParser.parse(markdown), 0); + return [...definitions.values()]; + }); describe("pull request body segmentation", () => { // GitHub writes a dropped image into the body as an `` tag, so a bare attachment link on // its own line is the shape it uses for a video — every one sampled in the wild was one. it("lifts a dropped video out and keeps the prose around it", () => { expect( - splitPullRequestBody( + split( "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter", ), ).toEqual([ @@ -43,7 +63,7 @@ describe("pull request body segmentation", () => { ? segment.rows.flat().flatMap((cell) => prose(cell.segments)) : [], ); - const runs = prose(splitPullRequestBody(body)); + const runs = prose(split(body)); expect(runs.map((segment) => segment.text)).toEqual([ "- [ ] Before", " - [ ] code\n- [x] After", @@ -59,9 +79,7 @@ describe("pull request body segmentation", () => { it("reads the source out of a video tag, including a multi-line one", () => { expect( - splitPullRequestBody( - '', - ), + split(''), ).toEqual([ { id: "attachment:0", @@ -75,21 +93,21 @@ describe("pull request body segmentation", () => { it("leaves the img tag GitHub writes for a dropped image as markdown", () => { const body = 'image'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("leaves an ordinary link alone, whether it is bare or written as markdown", () => { const body = "https://example.com/page\n\n[the docs](https://example.com/docs)"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("never lifts a link inside fenced code out of it", () => { const body = "```\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -97,14 +115,14 @@ describe("pull request body segmentation", () => { // GitHub keeps CRLF in a body written in its web editor. it("recognizes fences in a body with CRLF line endings", () => { const body = "```\r\nhttps://example.com/demo.mp4\r\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("closes a CRLF fence, so a video after it still lifts out", () => { const code = '```html\r\n\r\n```'; - expect(splitPullRequestBody(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ + expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 }, { id: "attachment:1", @@ -117,21 +135,21 @@ describe("pull request body segmentation", () => { it("does not let a different fence marker close an open fence", () => { const body = "```\n~~~\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("keeps a video tag that shares its line with prose as markdown", () => { const body = 'Before after'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("treats an info-string fence as a nested opener, not a close", () => { const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -139,9 +157,7 @@ describe("pull request body segmentation", () => { it("does not open a fence on a line of inline triple-backtick code", () => { const code = "```\nhttps://example.com/b.png\n```"; expect( - splitPullRequestBody( - `\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`, - ), + split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`), ).toEqual([ { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 }, { @@ -153,14 +169,14 @@ describe("pull request body segmentation", () => { { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 }, ]); const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```"; - expect(splitPullRequestBody(multilineSpan)).toEqual([ + expect(split(multilineSpan)).toEqual([ { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 }, ]); }); it("leaves an indented code line alone even when it is only a video link", () => { const body = " https://example.com/demo.mp4"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -169,14 +185,14 @@ describe("pull request body segmentation", () => { const body = ['( + method: string, + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.timeoutOrElse({ + duration: startupRequestTimeout, + orElse: () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + operation: "call-rpc", + method, + detail: `${method} timed out waiting for RPC response`, + cause: undefined, + }), + ), + }), + ); + const runLoggedRequest = ( method: string, payload: unknown, @@ -2297,7 +2318,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const initializeResult = yield* runLoggedRequest( "initialize", initializePayload, - acp.agent.initialize(initializePayload), + withStartupTimeout("initialize", acp.agent.initialize(initializePayload)), ); yield* options.onInitialized?.(initializeResult) ?? Effect.void; return initializeResult; @@ -2445,7 +2466,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( sessionSetupResult = yield* runLoggedRequest( "session/resume", resumePayload, - acp.agent.resumeSession(resumePayload), + withStartupTimeout("session/resume", acp.agent.resumeSession(resumePayload)), ); } else { return yield* new EffectAcpErrors.AcpRequestError({ @@ -2462,7 +2483,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const created = yield* runLoggedRequest( "session/new", createPayload, - acp.agent.createSession(createPayload), + withStartupTimeout("session/new", acp.agent.createSession(createPayload)), ); sessionId = created.sessionId; sessionSetupResult = created; @@ -3061,10 +3082,25 @@ const handleSessionUpdate = ); } const parsed = parseSessionUpdateEvent(params); - if (parsed.modeId) { + const modeId = parsed.modeId; + if (modeId) { yield* Ref.update(modeStateRef, (current) => - current === undefined ? current : updateModeState(current, parsed.modeId!), + current === undefined ? current : updateModeState(current, modeId), ); + // A mode-only update would otherwise leave the mode option showing the old mode. + const configOptions = yield* SubscriptionRef.get(configOptionsRef); + const isStaleMode = (option: (typeof configOptions)[number]) => + option.category === "mode" && option.type === "select" && option.currentValue !== modeId; + if (configOptions.some(isStaleMode)) { + yield* SubscriptionRef.set( + configOptionsRef, + configOptions.map((option) => + option.category === "mode" && option.type === "select" + ? { ...option, currentValue: modeId } + : option, + ), + ); + } } for (const event of parsed.events) { if (event._tag === "ToolCallUpdated") { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 43d2d14831e55..0485e7aca1175 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -389,15 +389,17 @@ export interface AcpAdapterV2Flavor { /** The flavor's runtime refuses a version the policy rates broken when it starts. */ readonly checksVersionAtHandshake?: boolean; /** - * Runs before `session/prompt`. The returned check sees a prompt the agent ended - * without an error or cancel, and reports a failure its stop reason hid. A reported - * failure restarts the runtime before the next turn. A `broken` thread's native - * history is unusable, so the next turn falls back to a fresh session. + * Runs before `session/prompt`. The check reports a failure hidden by a clean stop, or + * by silence when the inactivity watchdog retires the prompt (`retired`). A failure + * restarts the runtime; a `broken` thread's next turn starts a fresh session. */ readonly watchPromptOutcome?: ( sessionId: string, ) => Effect.Effect< - (result: EffectAcpSchema.PromptResponse) => Effect.Effect + ( + result: EffectAcpSchema.PromptResponse, + options?: { readonly retired?: boolean }, + ) => Effect.Effect >; readonly requiresSignIn?: (cause: unknown) => boolean; /** @@ -639,6 +641,15 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Finalize a settled turn held only by running commands once the session has been silent for + * `timeout`, so a command that never reports back cannot leave the thread in Working forever. + * Other holds (questions, schedules, subagents) keep the turn open as before. + */ + readonly postSettleCommandHold?: { + readonly timeout: Duration.Input; + readonly isCommand: (toolCall: AcpToolCallState) => boolean; + }; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -1739,6 +1750,12 @@ interface ActiveAcpTurn { inactivityWatchdog: Fiber.Fiber | undefined; } +const PROMPT_OUTCOME_CHECK_TIMEOUT = Duration.seconds(5); + +type PromptOutcomeCheck = Effect.Success< + ReturnType> +>; + type AcpRuntimeTeardownState = | { readonly _tag: "Idle" } | { @@ -2307,6 +2324,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const activeSelection = yield* Ref.make(null); const activeInteractionMode = yield* Ref.make(null); + // Mode values configureSession left the agent in; a later difference is the agent's own change. + const configuredModes = yield* Ref.make>(new Map()); + const readModes = Effect.gen(function* () { + const modes = new Map(); + for (const option of yield* runtime.getConfigOptions) { + if ( + option.type === "select" && + (option.category === "mode" || option.category === "collaboration_mode") + ) { + modes.set(option.id, option.currentValue); + } + } + const modeId = (yield* runtime.getModeState)?.currentModeId; + if (modeId !== undefined && !modes.has(ACP_SESSION_MODE_OPTION_ID)) { + modes.set(ACP_SESSION_MODE_OPTION_ID, modeId); + } + return modes; + }); const configuredRuntimeMode = yield* Ref.make< ProviderAdapter.ProviderAdapterV2RuntimePolicy["runtimeMode"] | null >(null); @@ -2726,7 +2761,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const notePromptProgress = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) { - if (promptInactivityTimeoutMillis === undefined) return; + if ( + promptInactivityTimeoutMillis === undefined && + flavor.postSettleCommandHold === undefined + ) { + return; + } if ( notification !== undefined && !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate) @@ -4260,11 +4300,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isMonitorEndNoticeText = (text: string): boolean => /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); - const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + const hasDeferredBackgroundWork = ( + context: ActiveAcpTurn, + ignoreTool?: (tool: AcpToolCallState) => boolean, + ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { + if (ignoreTool?.(tool) === true) continue; if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) return true; } @@ -8364,6 +8408,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } yield* validateModelSelection(modelSelection); + yield* Ref.set(configuredModes, yield* readModes); yield* Ref.set(configuredRuntimeMode, runtimePolicy.runtimeMode); yield* ( flavor.onSessionConfigurationUpdate?.( @@ -8552,6 +8597,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }); + // Re-applying the thread's mode would undo a deliberate exit, such as leaving plan mode once + // the plan was approved. Report it instead, so picking the old mode again is a real change. + const reportAgentModeChanges = Effect.fnUntraced(function* (threadId: ThreadId) { + const selection = yield* Ref.get(activeSelection); + if (selection === null || selection.options === undefined) return; + const configured = yield* Ref.get(configuredModes); + const live = yield* readModes; + const changes: Array<{ id: string; from: string; to: string }> = []; + const options = selection.options.map((option) => { + const value = live.get(option.id); + if ( + value === undefined || + typeof option.value !== "string" || + value === configured.get(option.id) || + value === option.value + ) { + return option; + } + changes.push({ id: option.id, from: option.value, to: value }); + return { ...option, value }; + }); + if (changes.length === 0) return; + yield* Ref.set(activeSelection, { ...selection, options }); + yield* Ref.set(configuredModes, live); + yield* emitProviderEvent({ + type: "thread_model_selection.updated", + driver, + threadId, + instanceId: selection.instanceId, + changes, + }); + }); + const finalizeTurn = Effect.fnUntraced(function* ( context: ActiveAcpTurn, status: "completed" | "interrupted" | "failed" | "cancelled", @@ -8647,6 +8725,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }, }); } + yield* reportAgentModeChanges(context.input.threadId); const turn = providerTurnPayload(context, settledStatus, now); yield* Ref.update(providerTurns, (current) => { const updated = new Map(current); @@ -8789,6 +8868,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); + const schedulePostSettleHoldExpiry = Effect.fn("AcpAdapterV2.schedulePostSettleHoldExpiry")( + function* (context: ActiveAcpTurn) { + const hold = flavor.postSettleCommandHold; + if (hold === undefined) return; + if (!context.promptSettled || context.finalized) return; + const timeoutMillis = Duration.toMillis(hold.timeout); + const isRunningCommand = (tool: AcpToolCallState) => + toolStatus(tool.status) === "running" && hold.isCommand(tool); + let quietSince = yield* Clock.currentTimeMillis; + // Armed even without a command yet: a pending reply can still start one. + yield* Effect.gen(function* () { + while (!context.finalized) { + quietSince = Math.max(quietSince, context.lastProgressAt); + const now = yield* Clock.currentTimeMillis; + const remaining = quietSince + timeoutMillis - now; + if (remaining > 0) { + yield* Effect.sleep(Duration.millis(remaining)); + continue; + } + if ( + context.tools.values().some(isRunningCommand) && + !hasDeferredBackgroundWork(context, isRunningCommand) + ) { + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + return; + } + // Something else still holds the turn; count silence again once it clears. + quietSince = now; + } + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { @@ -8812,6 +8924,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context: ActiveAcpTurn, generation: number, timeoutMillis: number, + checkPromptOutcome: PromptOutcomeCheck | undefined, ) { const retired = yield* runRuntimeCallbackAtGeneration( generation, @@ -8832,14 +8945,31 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* Ref.set(runtimeRestartRequired, true); yield* cancelPendingRuntimeRequests(); yield* terminalizeOpenForegroundTools(context, "failed"); + // Bounded: it runs under the transition permit that Stop and the next turn wait on. + const recorded = + checkPromptOutcome === undefined + ? undefined + : yield* checkPromptOutcome({ stopReason: "end_turn" }, { retired: true }).pipe( + Effect.timeout(PROMPT_OUTCOME_CHECK_TIMEOUT), + Effect.catchCause((cause) => + Effect.logError("failed to check a silent ACP prompt's outcome", { + driver, + cause, + }).pipe(Effect.as(undefined)), + ), + ); const minutes = Math.max(1, Math.round(timeoutMillis / 60_000)); yield* finalizeTurn( context, "failed", - makeProviderFailure({ - class: "provider_error", - message: `${flavor.runtimeHarness ?? driver} sent nothing for ${minutes} ${minutes === 1 ? "minute" : "minutes"}, so T3 Code stopped the turn and restarted the agent. Send a message to continue.`, - }), + recorded?.failure ?? + makeProviderFailure({ + class: "provider_error", + message: `${flavor.runtimeHarness ?? driver} sent nothing for ${minutes} ${minutes === 1 ? "minute" : "minutes"}, so T3 Code stopped the turn and restarted the agent. Send a message to continue.`, + }), + recorded === undefined + ? undefined + : { threadDisposition: recorded.threadDisposition }, ); return "retired" as const; }), @@ -8863,6 +8993,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context: ActiveAcpTurn, generation: number, timeoutMillis: number, + checkPromptOutcome: PromptOutcomeCheck | undefined, ) { yield* Deferred.await(context.promptDispatched); context.lastProgressAt = yield* Clock.currentTimeMillis; @@ -8881,7 +9012,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( continue; } const outcome = yield* runtimeTransitionPermit.withPermit( - retireInactivePrompt(context, generation, timeoutMillis), + retireInactivePrompt(context, generation, timeoutMillis, checkPromptOutcome), ); if (outcome !== "rearm") return; } @@ -8996,6 +9127,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const sessionSetup = yield* Ref.get(activeSessionSetup); const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: instructionState.hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: flavor.runtimeHarness ?? driver, model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, @@ -9220,6 +9352,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + yield* schedulePostSettleHoldExpiry(context); if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9620,6 +9753,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (!context.finalized) { + yield* schedulePostSettleHoldExpiry(context); if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else { @@ -9643,6 +9777,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, promptGeneration, promptInactivityTimeoutMillis, + checkPromptOutcome, ).pipe(Effect.forkIn(sessionScope)); } const compactSession = isCompactionMessage(turnInput.message) @@ -9745,6 +9880,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( context, generation, promptInactivityTimeoutMillis, + checkPromptOutcome, ).pipe(Effect.forkIn(sessionScope)); } const releasedForSteer = context.foregroundIdle; diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index c8371fb7020e8..592bf47553494 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -263,7 +263,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi // Agents that send shell source write bash; Node's shell on Windows is cmd.exe. const gitExecutable = isWindows && options.shellCommands === true - ? resolveExecutable("git", "win32", environment) + ? yield* Effect.promise(async () => resolveExecutable("git", "win32", environment)) : undefined; const posixShell = gitExecutable === undefined ? undefined : gitForWindowsBash(gitExecutable); diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index fd22904e28e0c..1773a6019a9af 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -1,5 +1,6 @@ import type { OrchestrationV2HistoricalMessage } from "@t3tools/contracts"; import { + type AgentFeedbackMode, ChatAttachment, CheckpointId, MessageId, @@ -8,6 +9,7 @@ import { OrchestrationV2AppThread, OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, + OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderSession, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, @@ -118,6 +120,17 @@ export const ProviderAdapterV2Event = Schema.Union([ sessionScoped: Schema.optional(Schema.Boolean), retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)), }), + /** The agent changed selected options itself, such as leaving plan mode once its plan ran. */ + Schema.Struct({ + type: Schema.Literal("thread_model_selection.updated"), + driver: ProviderDriverKind, + threadId: ThreadId, + instanceId: ProviderInstanceId, + /** Applies only where the thread still holds `from`, so newer user picks win. */ + changes: Schema.Array( + Schema.Struct({ id: Schema.String, from: Schema.String, to: Schema.String }), + ), + }), Schema.Struct({ type: Schema.Literal("provider_turn.updated"), driver: ProviderDriverKind, @@ -165,6 +178,14 @@ export const ProviderAdapterV2Event = Schema.Union([ providerTurnId: ProviderTurnId, pending: Schema.Boolean, }), + // The query process exited under a live session before this work reported back. + Schema.Struct({ + type: Schema.Literal("background_work.lost"), + driver: ProviderDriverKind, + threadId: ThreadId, + providerThreadId: ProviderThreadId, + tasks: Schema.Array(OrchestrationV2PendingBackgroundTask), + }), /** Unpersisted deltas go only to clients showing the row; final output arrives in turn_item.updated. */ Schema.Struct({ type: Schema.Literal("command_output.delta"), @@ -202,6 +223,8 @@ export const ProviderAdapterV2Event = Schema.Union([ failure: Schema.Null, reason: Schema.optional(Schema.String), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), }), Schema.Struct({ @@ -216,6 +239,8 @@ export const ProviderAdapterV2Event = Schema.Union([ retry: Schema.optional(OrchestrationV2ProviderRetry), retryStartedAt: Schema.optional(Schema.DateTimeUtc), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), /** Child turns outlive root failure and report their own terminals; otherwise open children settle. */ childTurnsContinue: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), @@ -558,6 +583,7 @@ export interface ProviderAdapterV2EnsureThreadInput { } export interface ProviderAdapterV2TurnInput { + readonly agentFeedback?: AgentFeedbackMode; readonly appThread: OrchestrationV2AppThread; readonly threadId: ThreadId; readonly runId: RunId; diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index a29b60d4d25ae..7f4b790927488 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -132,6 +132,16 @@ it("preserves actionable T3 errors wrapped by turn startup", () => { }); assert.equal(makeProviderFailure({ cause: Cause.fail(cause) }).message, error.message); } + const unanswered = { + _tag: "CodexAppServerUnresponsiveError", + message: "Codex app-server did not answer turn/start within 2 minutes.", + }; + assert.equal( + makeProviderFailure({ + cause: Cause.fail({ _tag: "ProviderAdapterEventStreamError", cause: unanswered }), + }).message, + unanswered.message, + ); }); it("names how the provider process exited and the stage it failed in, without its output", () => { diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index cfdb0eb3df9a6..e7d47cdb2175e 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -139,6 +139,8 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeConversationNotFoundError": case "CursorModelUnavailableError": case "CodexGoalObjectiveTooLongError": + case "CodexAppServerUnresponsiveError": + case "CodexAppServerRetiredError": case "ProviderSetupError": case "ProviderAdapterThreadInUseError": case "ProviderCompactionUnsupportedError": diff --git a/packages/provider-core/src/server/runtimeInstructions.test.ts b/packages/provider-core/src/server/runtimeInstructions.test.ts index 2564bedaa9216..5aa9259c49d91 100644 --- a/packages/provider-core/src/server/runtimeInstructions.test.ts +++ b/packages/provider-core/src/server/runtimeInstructions.test.ts @@ -1,6 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import { + AGENT_FEEDBACK_INSTRUCTIONS, buildRuntimeInstructions, PULL_REQUEST_LINKING_INSTRUCTIONS, } from "./runtimeInstructions.ts"; @@ -57,6 +58,22 @@ describe("buildRuntimeInstructions", () => { assert.include(instructions, "call unwatch_pull_request"); }); + it("carries the feedback line of the agent feedback mode, and none while it is off", () => { + assert.notInclude(buildRuntimeInstructions({ harness: "Codex" }), "t3_feedback"); + assert.notInclude( + buildRuntimeInstructions({ harness: "Codex", agentFeedback: "off" }), + "t3_feedback", + ); + for (const agentFeedback of ["on-request", "auto"] as const) { + for (const pullRequestLinking of [true, false]) { + assert.include( + buildRuntimeInstructions({ harness: "Codex", agentFeedback, pullRequestLinking }), + AGENT_FEEDBACK_INSTRUCTIONS[agentFeedback], + ); + } + } + }); + it("lists a multi-folder thread's folders and leaves single-folder text unchanged", () => { const base = { runtimeMode: "full-access", interactionMode: "default" } as const; const single = buildRuntimeInstructions({ harness: "Codex" }); @@ -86,6 +103,21 @@ describe("buildRuntimeInstructions", () => { }, }); assert.isTrue(listed.startsWith(`${single}\n\n\n`)); + const withFeedback = buildRuntimeInstructions({ harness: "Codex", agentFeedback: "auto" }); + assert.isTrue( + buildRuntimeInstructions({ + harness: "Codex", + agentFeedback: "auto", + runtimePolicy: { + ...base, + cwd: "/work/app", + workspace: { + folders: [{ name: "api", path: "/work/api", isGitRepository: true }], + extraRoots: [], + }, + }, + }).startsWith(`${withFeedback}\n\n\n`), + ); assert.deepEqual( listed .slice(single.length + 2) diff --git a/packages/provider-core/src/server/runtimeInstructions.ts b/packages/provider-core/src/server/runtimeInstructions.ts index 463148500ebb4..ebcf126f982ae 100644 --- a/packages/provider-core/src/server/runtimeInstructions.ts +++ b/packages/provider-core/src/server/runtimeInstructions.ts @@ -1,5 +1,14 @@ +import type { AgentFeedbackMode } from "@t3tools/contracts"; + import type { ProviderAdapterV2RuntimePolicy } from "./ProviderAdapter.ts"; +/** None while agent feedback is off, so users who never opt in pay no context for it. */ +export const AGENT_FEEDBACK_INSTRUCTIONS = { + off: "", + "on-request": "Use `t3_feedback` only when the user asks you to send T3 feedback.", + auto: "`t3_feedback` reports are wanted and cheap. Send one, then continue, when a T3 tool or `t3` command fails or gives a wrong result, the user corrects how you use T3 Code, or a T3 capability you looked for is missing. Once per problem; also when the user asks. Only about T3 Code, never the user's code or other tools.", +} satisfies Record; + /** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */ export const PULL_REQUEST_LINKING_INSTRUCTIONS = ` Link each PR you create, take over, or push to: link_pull_request, or link_pull_requests for several, full URL, every stack layer, as your next call. Host tools don't link for you. If linking fails, say so. Skip PRs you only read or review and PRs named only as background. Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. When pull_request_* tools are listed, use them, not gh or cafe, to read, list, open, edit, review, reply on, close, or merge PRs, and ci_logs and ci_rerun for their checks. pull_request_create links for you. @@ -9,6 +18,7 @@ If available, call link_issue for each issue you take on or file, even via CLI; /** Omit model and effort when the harness manages them dynamically. */ export function buildRuntimeInstructions(runtime: { readonly harness: string; + readonly agentFeedback?: AgentFeedbackMode; readonly model?: string | undefined; readonly modelName?: string | undefined; readonly reasoningEffort?: string | undefined; @@ -26,13 +36,15 @@ export function buildRuntimeInstructions(runtime: { const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${modelLabel}` : ""; const effortInfo = effort ? ` with ${effort} reasoning effort` : ""; const runtimeInfo = `In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.`; + const feedbackLine = AGENT_FEEDBACK_INSTRUCTIONS[runtime.agentFeedback ?? "off"]; + const feedback = feedbackLine ? `\n${feedbackLine}` : ""; const workspace = runtime.runtimePolicy === undefined ? "" : buildWorkspaceInstructions(runtime.runtimePolicy); - return [ - runtimeInfo, - ...(runtime.pullRequestLinking === false ? [] : [PULL_REQUEST_LINKING_INSTRUCTIONS]), - ...(workspace === "" ? [] : [workspace]), - ].join("\n\n"); + const linked = + runtime.pullRequestLinking === false + ? runtimeInfo + : `${runtimeInfo}\n\n${PULL_REQUEST_LINKING_INSTRUCTIONS}`; + return [linked + feedback, ...(workspace === "" ? [] : [workspace])].join("\n\n"); } function toSingleLine(value: string): string { diff --git a/packages/provider-core/src/server/subagentProjection.ts b/packages/provider-core/src/server/subagentProjection.ts index d1638b8022029..df5ea84c4b440 100644 --- a/packages/provider-core/src/server/subagentProjection.ts +++ b/packages/provider-core/src/server/subagentProjection.ts @@ -395,7 +395,7 @@ export function subagentHoldsCompletion( export function delegatedTaskProgress(projection: { readonly runs: OrchestrationV2ThreadProjection["runs"]; readonly messages: ReadonlyArray< - Pick + Pick >; readonly subagents: ReadonlyArray< Pick @@ -410,9 +410,17 @@ export function delegatedTaskProgress(projection: { const workRuns = projection.runs.filter( (run) => !monitorRuns.has(run.id) && run.status !== "rolled_back", ); - const active = workRuns.some( - (run) => !terminal(run.status) && !(run.status === "queued" && run.queueHeld === true), + const held = (run: OrchestrationV2Run) => run.status === "queued" && run.queueHeld === true; + const active = workRuns.some((run) => !terminal(run.status) && !held(run)); + // Held wakes wait on nobody, but a held message the user wrote is the child's next work. + const userRunIds = new Set( + projection.messages.flatMap((message) => + message.createdBy === "user" && message.notification === undefined && message.runId !== null + ? [message.runId] + : [], + ), ); + const awaitsUserRun = workRuns.some((run) => held(run) && userRunIds.has(run.id)); const children = projection.subagents.some(subagentHoldsCompletion) || projection.providerThreads.some((thread) => @@ -423,12 +431,14 @@ export function delegatedTaskProgress(projection: { .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0]; return { state: - active || resultRun === undefined + active || awaitsUserRun || resultRun === undefined ? ("working" as const) : children ? ("waiting_for_children" as const) : ("result_available" as const), resultRun, + /** Working only because of a held message the user wrote, which a cancel does not wait for. */ + onlyAwaitsUserRun: awaitsUserRun && !active && resultRun !== undefined, }; } diff --git a/packages/provider-core/src/server/usage.ts b/packages/provider-core/src/server/usage.ts index ff4c14dfefe00..260f160421f33 100644 --- a/packages/provider-core/src/server/usage.ts +++ b/packages/provider-core/src/server/usage.ts @@ -62,8 +62,8 @@ export interface TranscriptUsageFormat { readonly usageMarkers: readonly [string, ...string[]]; parseLine(line: string, state: State): readonly UsageRecord[]; parseProjected(projected: unknown, state: State): readonly UsageRecord[]; - /** Cumulative malformed or inconsistent usage records, including skipped records. */ - readMalformedRecords?(state: State): number; + /** Timestamps of malformed or inconsistent usage records, including skipped records. */ + readMalformedRecords?(state: State): readonly number[]; /** * Present for formats whose records depend on earlier lines. The state at a * resume point is persisted in the scan cache through `schema`, so a grown diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 5c0a1940d671c..85cc2535960b8 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -445,6 +445,54 @@ describe("CursorAdapterV2", () => { failure: null, answers: [], }, + { + reason: "no failure when the connection fails after the turn ended", + updates: [ + { type: "text-delta", text: "Done." }, + { type: "turn-ended" }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: null, + }, + { + reason: "a connection failure before the turn ends", + updates: [ + { type: "text-delta", text: "Working." }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: { class: "provider_error", message: "Connection failed repeatedly" }, + }, + { + reason: "a connection failure during a continuation after the turn ended", + updates: [ + { type: "text-delta", text: "Done." }, + { type: "turn-ended" }, + { type: "step-started", stepId: 2 }, + ] satisfies ReadonlyArray, + wait: Effect.succeed({ + id: "native-cursor-run", + requestId: "native-request", + status: "error" as const, + error: { message: "Connection failed repeatedly" }, + model: { id: "claude-fable-5" }, + durationMs: 1, + }), + failure: { class: "provider_error", message: "Connection failed repeatedly" }, + }, { reason: "the token usage Cursor reported", // Cursor's inputTokens already include cache reads and writes. @@ -756,6 +804,149 @@ describe("CursorAdapterV2", () => { ), ); + it.effect("marks failed turns as promptDropped only when Cursor did not checkpoint the run", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "cursor-v2-dropped-", + }); + const checkpointedRuns = new Set(); + let sendCalls = 0; + const instanceId = ProviderInstanceId.make("cursor"); + const threadId = ThreadId.make("cursor-dropped-thread"); + const modelSelection = { instanceId, model: "gemini-4-neon" }; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const adapter = yield* makeCursorAdapterV2({ + instanceId, + environment: { HOME: workspace }, + }).pipe( + Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { + assertComplete: Effect.void, + open: () => + Effect.succeed({ + agentId: "native-cursor-dropped", + listMessages: Effect.succeed([]), + close: Effect.void, + runCheckpointed: (runId) => + Effect.succeed(runId !== undefined && checkpointedRuns.has(runId)), + send: () => + Effect.sync(() => { + sendCalls += 1; + const runId = `native-cursor-run-${sendCalls}`; + return { + agentId: "native-cursor-dropped", + runId, + cancel: Effect.void, + wait: Effect.succeed({ + id: runId, + status: "error" as const, + error: { + message: + 'AI Model Not Found Invalid parameters for registry model: "gemini-4-neon"', + }, + }), + }; + }), + }), + textGenerate: () => Effect.die("unused"), + }), + Effect.provide(TestProviderHost.layer({ cwd: workspace })), + ); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("cursor-dropped-session"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const appThread = { + id: threadId, + projectId: ProjectId.make("cursor-dropped-project"), + createdBy: "user" as const, + creationSource: "web" as const, + title: "Cursor dropped prompt", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; + const runFailed = (ordinal: number) => + Effect.gen(function* () { + yield* runtime.startTurn({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + runId: RunId.make(`cursor-dropped-run-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`cursor-dropped-attempt-${ordinal}`), + rootNodeId: NodeId.make(`cursor-dropped-root-${ordinal}`), + appThread, + message: { + messageId: MessageId.make(`cursor-dropped-message-${ordinal}`), + createdBy: "user", + creationSource: "web", + text: "Resume", + attachments: [], + }, + }); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const terminal = events.find((event) => event.type === "turn.terminal"); + const turn = events.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ); + return { + terminal: terminal?.type === "turn.terminal" ? terminal : undefined, + turn: turn?.type === "provider_turn.updated" ? turn.providerTurn : undefined, + }; + }); + + // Uncheckpointed failure: Cursor never persisted the prompt. + const uncheckpointed = yield* runFailed(1); + assert.equal(uncheckpointed.terminal?.status, "failed"); + assert.equal(uncheckpointed.terminal?.promptDropped, true); + assert.equal(uncheckpointed.turn?.promptDropped, true); + + // Checkpointed failure: Cursor kept the run's prompt in its store. + checkpointedRuns.add("native-cursor-run-2"); + const checkpointed = yield* runFailed(2); + assert.equal(checkpointed.terminal?.status, "failed"); + assert.isUndefined(checkpointed.terminal?.promptDropped); + assert.isUndefined(checkpointed.turn?.promptDropped); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + ), + ), + ); + it.effect("sends T3 instructions to each Cursor conversation that lacks them", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 8cdf2de3e1b63..2360c4fc91cec 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -928,9 +928,11 @@ interface CursorProjectionTarget { const MAX_CURSOR_STREAMED_OUTPUT_CHARS = 256 * 1024; // After a turn ends, a retryable stream error can make Cursor's SDK resume from // an older checkpoint inside the same run. When those resumes save nothing, it -// ends the run with this error even though the answer was already delivered. -const CURSOR_RESUME_NO_PROGRESS_MESSAGE = - "Agent turn stopped after repeated resume attempts made no progress"; +// ends with either retry limit even though the answer was already delivered. +const CURSOR_POST_TURN_RETRY_ERRORS = new Set([ + "Agent turn stopped after repeated resume attempts made no progress", + "Connection failed repeatedly", +]); interface ActiveCursorToolCall { readonly callId: string; @@ -2510,6 +2512,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( readonly status: OrchestrationV2ProviderTurn["status"]; readonly completedAt: DateTime.Utc | null; readonly tokenUsage?: OrchestrationV2ProviderTurn["tokenUsage"]; + readonly promptDropped?: true; }): OrchestrationV2ProviderTurn => ({ id: input.context.providerTurnId, providerThreadId: input.context.input.providerThread.id, @@ -2525,6 +2528,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( startedAt: input.context.startedAt, completedAt: input.completedAt, ...(input.tokenUsage === undefined ? {} : { tokenUsage: input.tokenUsage }), + ...(input.promptDropped === true ? { promptDropped: true as const } : {}), ...(input.completedAt === null || input.context.usage === undefined ? {} : { @@ -2590,6 +2594,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }).pipe(Effect.as(undefined)), ), ); + // Cursor only keeps a run in conversation history once it saves its first checkpoint. + const promptDropped = + (input.status === "failed" || input.status === "cancelled") && + !input.context.compacted && + input.context.prompt !== undefined && + !(yield* ( + input.context.session.runCheckpointed?.(input.context.run.runId) ?? + Effect.succeed(false) + ).pipe(Effect.orElseSucceed(() => false))); yield* emitProviderEvent({ type: "provider_turn.updated", driver: CursorAgentSdk.CURSOR_PROVIDER, @@ -2597,6 +2610,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( context: input.context, status: input.status, completedAt, + ...(promptDropped ? { promptDropped: true as const } : {}), ...(contextUsage === undefined ? {} : { @@ -2633,6 +2647,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: input.failure ?? makeProviderFailure({ class: "provider_error" }), threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), } : { type: "turn.terminal", @@ -2643,6 +2658,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: null, threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), }, ); if (input.context.runtimeInstructions !== undefined) { @@ -2676,7 +2692,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const isResumeFailureAfterTurnEnded = (context: ActiveCursorTurn, result: RunResult) => context.turnEnded && result.status === "error" && - result.error?.message === CURSOR_RESUME_NO_PROGRESS_MESSAGE; + CURSOR_POST_TURN_RETRY_ERRORS.has(result.error?.message ?? ""); const terminalStatus = ( context: ActiveCursorTurn, @@ -2893,11 +2909,12 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }); } const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: mcpServers === undefined ? "off" : (turnInput.agentFeedback ?? "off"), harness: "Cursor", model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, }); - // Resend only on a new/compacted/rewound conversation or when the model changes. + // Resend only on a new/compacted/rewound conversation or when the instructions change. const sendRuntimeInstructions = delivered.runtime !== runtimeInstructions; const text = sendRuntimeInstructions ? userText.length === 0 diff --git a/packages/provider-muse/src/server/MuseUsageHome.ts b/packages/provider-muse/src/server/MuseUsageHome.ts index 1ced0d2578b01..329dce90c0e7b 100644 --- a/packages/provider-muse/src/server/MuseUsageHome.ts +++ b/packages/provider-muse/src/server/MuseUsageHome.ts @@ -66,7 +66,11 @@ const make = Effect.gen(function* () { if (Option.isSome(settled)) return settled; // Spawn failures surface asynchronously; without this a missing CLI would report as pending. const resolveExecutable = yield* SpawnExecutableResolution; - if (resolveExecutable(binaryPath, yield* HostProcess.Platform, environment) === undefined) { + const platform = yield* HostProcess.Platform; + const resolved = yield* Effect.promise(async () => + resolveExecutable(binaryPath, platform, environment), + ); + if (resolved === undefined) { return Option.some(undefined); } if (awaitRefresh) return Option.some(yield* Cache.get(cache, key)); diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index f23f7ca84d7ea..7e0375e99a3ec 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -388,7 +388,8 @@ vi.mock("node:fs/promises", { spy: true }); describe("MuseAdapterV2", () => { it.effect("connects the thread's MCP credential on native start and resume", () => Effect.gen(function* () { - yield* (yield* McpProviderSessions.McpProviderSessions).set({ + const sessions = yield* McpProviderSessions.McpProviderSessions; + const config = { environmentId: EnvironmentId.make("test-environment"), threadId: THREAD_ID, providerSessionId: "test-session", @@ -396,11 +397,12 @@ describe("MuseAdapterV2", () => { endpoint: "http://127.0.0.1:43210/mcp", authorizationHeader: "Bearer thread-scoped-test-token", browserToolsAvailable: true, - }); + }; for (const nativeId of [undefined, "saved-native-session"]) { + yield* sessions.set(config); const fake = yield* makeFakeMuse(); fake.host.initializeResult.grantedCapabilities.push("sessionMcp"); - yield* makeHarness(fake, INSTANCE_ID, nativeId); + const harness = yield* makeHarness(fake, INSTANCE_ID, nativeId); const call = yield* fake.takeCall(nativeId ? "session/resume" : "session/start"); assert.deepStrictEqual(call.params.config, { mcpServers: { @@ -412,6 +414,13 @@ describe("MuseAdapterV2", () => { }, }, }); + yield* sessions.clear(THREAD_ID); + yield* harness.runtime.startTurn({ + ...(yield* turnInput(harness.providerThread, 1, harness.policy)), + agentFeedback: "auto", + }); + const turn = yield* fake.takeCall("turn/start"); + assert.match(JSON.stringify(turn.params.input), /t3_feedback/); } }).pipe(Effect.scoped, Effect.provide(testLayer)), ); diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index 0b5835e0bad12..66c1fd1a505ff 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -356,6 +356,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( let relaunchable = false; let nativeSessionId: string | undefined; let thread: OrchestrationV2ProviderThread | undefined; + let hasT3Mcp = false; let active: ActiveTurn | undefined; let lastProviderTurn: OrchestrationV2ProviderTurn | undefined; let latestSubscriptionUsage: MuseSubscriptionUsage | undefined; @@ -2013,6 +2014,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( createdAt, updatedAt: createdAt, }; + hasT3Mcp = mcpSession !== undefined; session = { ...session, model: result.session.modelId ?? args.modelSelection.model, @@ -2191,6 +2193,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( { type: "text", text: buildRuntimeInstructions({ + agentFeedback: hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: "Muse Code", model: session.model ?? undefined, reasoningEffort: effort, diff --git a/packages/provider-muse/src/server/sdk.test.ts b/packages/provider-muse/src/server/sdk.test.ts index 45ef56cb63458..6607640751092 100644 --- a/packages/provider-muse/src/server/sdk.test.ts +++ b/packages/provider-muse/src/server/sdk.test.ts @@ -263,7 +263,7 @@ describe("Muse launch", () => { const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) => museLaunch("muse", env).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => resolved), + Effect.provideService(SpawnExecutableResolution, async () => resolved), ); it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () => diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts index 6d6b4d5d51050..aece589b1e188 100644 --- a/packages/provider-muse/src/server/sdk.ts +++ b/packages/provider-muse/src/server/sdk.ts @@ -117,7 +117,8 @@ export const museLaunch = Effect.fn("museLaunch")(function* ( if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] }; const env = environment ?? (yield* HostProcess.Environment); const resolveExecutable = yield* SpawnExecutableResolution; - const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, "win32", env))) ?? binaryPath; if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] }; const systemRoot = windowsEnvironmentValue(env, "SystemRoot"); return { diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts index 3815cfce44321..d02271f44ff04 100644 --- a/packages/provider-muse/src/server/usage.test.ts +++ b/packages/provider-muse/src/server/usage.test.ts @@ -260,7 +260,7 @@ describe("Muse history discovery", () => { expect(create).not.toHaveBeenCalled(); }).pipe( Effect.provide([NodeServices.layer, MuseUsageHome.layer]), - Effect.provideService(SpawnExecutableResolution, () => undefined), + Effect.provideService(SpawnExecutableResolution, async () => undefined), ), ); diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index d0e1d27cc2a7b..6398e8ec74800 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -13,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { causeErrorTag } from "@t3tools/shared/observability"; import { + type AgentFeedbackMode, defaultInstanceIdForDriver, type ModelSelection, type OrchestrationV2AppThread, @@ -296,6 +297,7 @@ interface ActiveOpenCodeTurn { readonly appThread: OrchestrationV2AppThread; readonly modelSelection: ModelSelection; readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + readonly agentFeedback: AgentFeedbackMode; readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; readonly providerThreadId: OrchestrationV2ProviderTurn["providerThreadId"]; readonly runOrdinal: number; @@ -2513,6 +2515,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: state.appThread, modelSelection: state.appThread.modelSelection, runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy, + agentFeedback: state.parentSubagent.parentTurn.agentFeedback, providerTurnId, providerThreadId: providerTurn.providerThreadId, runOrdinal: state.parentSubagent.parentTurn.runOrdinal, @@ -3515,6 +3518,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function buildRuntimeInstructions({ harness: "OpenCode", model: turn.modelSelection.model, + agentFeedback: hasT3Mcp ? turn.agentFeedback : "off", runtimePolicy: turn.runtimePolicy, }), ] @@ -3788,6 +3792,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: turnInput.appThread, modelSelection: turnInput.modelSelection, runtimePolicy: turnInput.runtimePolicy, + agentFeedback: turnInput.agentFeedback ?? "off", providerTurnId, providerThreadId: turnInput.providerThread.id, runOrdinal: turnInput.runOrdinal, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 97e864cda15da..b5deabd7378c5 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4430,6 +4430,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } const instructions = [ buildRuntimeInstructions({ + agentFeedback: mcpAvailable ? (turnInput.agentFeedback ?? "off") : "off", harness: "OpenCode", model: turnInput.modelSelection.model, runtimePolicy: turnInput.runtimePolicy, @@ -4726,7 +4727,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (commands.some((entry) => entry.name === command.name)) { // session.command neither accepts nor returns our ID; record the preceding history boundary. const newest = yield* client.message.list({ sessionID, order: "desc", limit: 1 }); - yield* markBefore(sessionId, newest.data[0]?.id ?? null); + const before = newest.data[0]?.id ?? null; + yield* markBefore(sessionId, before); if (!sending()) return; if (goalCommand?.type === "pause" || goalCommand?.type === "clear") { // OpenCode rejects pausing or clearing a missing goal; Codex treats that as a no-op. @@ -4739,7 +4741,44 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); return yield* finishControl; } - return yield* client.session.command({ sessionID, ...command }).pipe(Effect.asVoid); + yield* client.session.command({ sessionID, ...command }); + // A command that never prompts the model starts no execution, so no event ends its turn. + const idle = () => state.active === turn && !busy.has(sessionId); + if (!idle()) return; + const active = yield* client.session + .active() + .pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT), Effect.option); + if (active._tag === "None") { + return yield* Effect.logWarning("Could not check whether an OpenCode command started."); + } + if (sessionId in active.value) return; + // An execution that already ended left history behind; its events may still trail this reply. + const ran = yield* OpenCode2Client.paginate( + { sessionID, order: "desc" as const, limit: 1 }, + client.message.list, + ).pipe( + Stream.takeWhile((message) => message.id !== before), + Stream.filter( + (message) => + message.type === "user" || message.type === "assistant" || message.type === "idle", + ), + Stream.runHead, + Effect.timeout(ACTIVE_CHECK_TIMEOUT), + Effect.option, + ); + if (ran._tag === "None") { + return yield* Effect.logWarning("Could not check whether an OpenCode command ran."); + } + if (ran.value._tag === "Some") return; + return yield* lock.withPermit( + Effect.suspend(() => + idle() + ? endExecution(state, turn, { + status: turn.interrupted ? "interrupted" : "completed", + }) + : Effect.void, + ), + ); } } // Mentions in inline context (handoff history, FYI messages) are not this turn's skills. diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 019af2a98783f..b3e54117f02ee 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4159,6 +4159,62 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("reports cached input as a share of input in live and completed token usage", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + fake.queueState({ + sessionFile: FAKE_SESSION_FILE, + model: { provider: "anthropic", id: "large", contextWindow: 1_000_000 }, + }); + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + // Pi's message usage counts uncached input, cache reads and cache writes separately. + const usage = { input: 6, cacheRead: 40_101, cacheWrite: 10_561, output: 123 }; + // Session stats total every message in the session, not this turn. + fake.queueStats({ + tokens: { + input: 1_206, + cacheRead: 90_202, + cacheWrite: 60_622, + output: 250, + total: 152_280, + }, + contextUsage: { tokens: 50_791, contextWindow: 1_000_000 }, + }); + yield* fake.emit({ type: "response", command: "prompt", success: true }); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "message_start", message: { role: "assistant" } }); + yield* fake.emit({ + type: "message_update", + usage: { ...usage, totalTokens: 50_791 }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ok" }, + }); + const live = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, + ); + assert.deepInclude( + live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.deepInclude( + completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each(["turn window", "full tree"] as const)( "finishes a turn whose %s has a parentId cycle", (cycleIn) => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index eae7f3eb6c2fa..e7803bbe9c5ee 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -359,6 +359,11 @@ function compactionTitle(status: PiCompactionStatus): string { } } +type PiMessageTokenUsage = Pick< + OrchestrationV2ProviderTurnTokenUsage, + "inputTokens" | "cachedInputTokens" | "outputTokens" +>; + interface ActivePiTurn { readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput; readonly providerTurn: OrchestrationV2ProviderTurn; @@ -377,6 +382,7 @@ interface ActivePiTurn { promptMayBeCommandOnly: boolean; latestCompactionAfterTokens: number | null; lastLiveUsedTokens: number | null; + lastMessageUsage: PiMessageTokenUsage | undefined; settleProbeGeneration: number; /** An extension may start compaction immediately after Pi emits agent_settled. */ settleWhenIdle: boolean; @@ -904,6 +910,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return value === undefined ? undefined : Math.max(0, Math.trunc(value)); }; + // Pi counts uncached input, cache reads and cache writes separately; input includes all three. + const piMessageTokenUsage = (usage: unknown): PiMessageTokenUsage => { + const uncachedInputTokens = nonNegativeInteger(usage, "input"); + const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); + const outputTokens = nonNegativeInteger(usage, "output"); + return { + ...(uncachedInputTokens === undefined + ? {} + : { + inputTokens: + uncachedInputTokens + + (cachedInputTokens ?? 0) + + (nonNegativeInteger(usage, "cacheWrite") ?? 0), + }), + ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), + ...(outputTokens === undefined ? {} : { outputTokens }), + }; + }; + const rememberModelContextWindow = (model: unknown): number | null => { const provider = recordString(model, "provider"); const id = recordString(model, "id"); @@ -994,6 +1019,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const tokenUsageFromStats = ( stats: unknown, fallbackUsedTokens: number | null, + messageUsage: PiMessageTokenUsage | undefined, updatedAt: DateTime.Utc, ): OrchestrationV2ProviderTurnTokenUsage | undefined => { const contextUsage = recordField(stats, "contextUsage"); @@ -1002,24 +1028,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined; if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0) return undefined; - - const totals = recordField(stats, "tokens"); - const inputTokens = nonNegativeInteger(totals, "input"); - const cachedInputTokens = nonNegativeInteger(totals, "cacheRead"); - const outputTokens = nonNegativeInteger(totals, "output"); - return { - usedTokens, - maxTokens, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), - updatedAt: DateTime.formatIso(updatedAt), - }; + // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message. + return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) }; }; - const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) => + const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) => request({ type: "get_session_stats" }, 2_000).pipe( - Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)), + Effect.map((stats) => + tokenUsageFromStats( + stats, + turn.latestCompactionAfterTokens, + turn.lastMessageUsage, + updatedAt, + ), + ), Effect.orElseSucceed(() => undefined), ); @@ -1030,6 +1052,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) { const usedTokens = nonNegativeInteger(usage, "totalTokens"); + if (usedTokens !== undefined && usedTokens > 0) { + turn.lastMessageUsage = piMessageTokenUsage(usage); + } if ( usedTokens === undefined || usedTokens === 0 || @@ -1040,9 +1065,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } turn.lastLiveUsedTokens = usedTokens; - const inputTokens = nonNegativeInteger(usage, "input"); - const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); - const outputTokens = nonNegativeInteger(usage, "output"); const updatedAt = yield* DateTime.now; yield* emit({ type: "provider_turn.updated", @@ -1053,9 +1075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( tokenUsage: { usedTokens, maxTokens: contextWindow, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), + ...turn.lastMessageUsage, updatedAt: DateTime.formatIso(updatedAt), }, }, @@ -2075,9 +2095,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } const treeRefs = turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs(); - const tokenUsage = readUsage - ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt) - : undefined; + const tokenUsage = readUsage ? yield* readTokenUsage(turn, completedAt) : undefined; const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure); yield* emit({ type: "provider_turn.updated", @@ -3474,6 +3492,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false), latestCompactionAfterTokens: null, lastLiveUsedTokens: null, + lastMessageUsage: undefined, settleProbeGeneration: 0, settleWhenIdle: false, compactionCancelled: false, diff --git a/packages/shared/package.json b/packages/shared/package.json index 3b556a3a3df97..4721958b734f4 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -151,6 +151,10 @@ "types": "./src/toolOutput.ts", "import": "./src/toolOutput.ts" }, + "./appLinks": { + "types": "./src/appLinks.ts", + "import": "./src/appLinks.ts" + }, "./htmlRender": { "types": "./src/htmlRender.ts", "import": "./src/htmlRender.ts" @@ -531,6 +535,14 @@ "types": "./src/markdownGithubAlerts.ts", "import": "./src/markdownGithubAlerts.ts" }, + "./markdownChunks": { + "types": "./src/markdownChunks.ts", + "import": "./src/markdownChunks.ts" + }, + "./markdownHast": { + "types": "./src/markdownHast.ts", + "import": "./src/markdownHast.ts" + }, "./markdownFrontmatter": { "types": "./src/markdownFrontmatter.ts", "import": "./src/markdownFrontmatter.ts" @@ -658,6 +670,18 @@ "./paletteSearchCopy": { "types": "./src/paletteSearchCopy.ts", "import": "./src/paletteSearchCopy.ts" + }, + "./markdownTaskEdits": { + "types": "./src/markdownTaskEdits.ts", + "import": "./src/markdownTaskEdits.ts" + }, + "./threadFindBlockTags": { + "types": "./src/threadFindBlockTags.ts", + "import": "./src/threadFindBlockTags.ts" + }, + "./assistantInsights": { + "types": "./src/assistantInsights.ts", + "import": "./src/assistantInsights.ts" } }, "scripts": { @@ -672,6 +696,7 @@ "ffi-rs": "1.3.2", "get-east-asian-width": "^1.6.0", "gt-i18n": "1.0.40", + "hast-util-sanitize": "^5.0.2", "mdast-util-directive": "catalog:", "mdast-util-to-hast": "^13.2.1", "micromark-extension-directive": "catalog:", @@ -692,8 +717,10 @@ "devDependencies": { "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", + "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "@types/node": "catalog:", + "hast-util-to-html": "^9.0.5", "micromark-util-types": "catalog:", "vite-plus": "catalog:" } diff --git a/packages/shared/src/appLinks.test.ts b/packages/shared/src/appLinks.test.ts new file mode 100644 index 0000000000000..2e3556803208f --- /dev/null +++ b/packages/shared/src/appLinks.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { appLinkUrl } from "./appLinks.ts"; + +describe("appLinkUrl", () => { + it("accepts schemes another app opens", () => { + expect(appLinkUrl("obsidian://open?vault=vault&file=Note")).toBe( + "obsidian://open?vault=vault&file=Note", + ); + expect(appLinkUrl("t3-thread://v2/env/thread")).toBe("t3-thread://v2/env/thread"); + expect(appLinkUrl("mailto:a@example.com")).toBe("mailto:a@example.com"); + }); + + it("rejects schemes the browser loads itself, and non-URLs", () => { + for (const url of [ + "https://example.com", + "http://example.com", + "javascript:alert(1)", + "JavaScript:alert(1)", + "data:text/html,x", + "file:///etc/passwd", + "blob:https://example.com/id", + "about:blank", + "view-source:https://example.com", + "chrome://settings", + "filesystem:https://example.com/temporary/a", + "not a url", + ]) { + expect(appLinkUrl(url), url).toBeNull(); + } + }); +}); diff --git a/packages/shared/src/appLinks.ts b/packages/shared/src/appLinks.ts new file mode 100644 index 0000000000000..85ebe6a6922f7 --- /dev/null +++ b/packages/shared/src/appLinks.ts @@ -0,0 +1,22 @@ +/** Schemes the browser engine loads itself; every other scheme names an app the OS opens. */ +const BROWSER_PROTOCOLS = [ + "about:", + "blob:", + "chrome:", + "data:", + "devtools:", + "file:", + "filesystem:", + "http:", + "https:", + "javascript:", + "view-source:", +]; + +const browserProtocols: ReadonlySet = new Set(BROWSER_PROTOCOLS); + +/** The normalized URL when it is an app link, such as `obsidian:` or `mailto:`, otherwise null. */ +export function appLinkUrl(rawUrl: string): string | null { + const url = URL.parse(rawUrl); + return url === null || browserProtocols.has(url.protocol) ? null : url.href; +} diff --git a/packages/shared/src/assistantInsights.ts b/packages/shared/src/assistantInsights.ts new file mode 100644 index 0000000000000..60f4ad1df349a --- /dev/null +++ b/packages/shared/src/assistantInsights.ts @@ -0,0 +1,3 @@ +export function shouldPreserveAssistantLineBreaks(text: string): boolean { + return /^★ Insight(?:\s|─)/mu.test(text); +} diff --git a/packages/shared/src/codexArtifactTemplates.ts b/packages/shared/src/codexArtifactTemplates.ts index 08fa5a28e3e58..9308c24d930dd 100644 --- a/packages/shared/src/codexArtifactTemplates.ts +++ b/packages/shared/src/codexArtifactTemplates.ts @@ -133,3 +133,29 @@ export function appendCodexArtifactTemplateUsePrompt( const needsLeadingSpace = draft.length > 0 && !/\s$/.test(draft); return `${draft}${needsLeadingSpace ? " " : ""}${prompt}`; } + +export const CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES = [ + "dataCodexArtifactTemplate", + "dataArtifactKind", + "dataDisplayName", + "dataGalleryKind", + "dataSkillDirectory", + "dataSkillName", +] as const; + +export function artifactTemplateFromHastProperties( + properties: Readonly> | null | undefined, +): CodexArtifactTemplate | null { + if (properties?.dataCodexArtifactTemplate !== "true") return null; + const stringProperty = (name: string) => { + const value = properties[name]; + return typeof value === "string" ? value : undefined; + }; + return resolveCodexArtifactTemplate({ + artifact_kind: stringProperty("dataArtifactKind"), + display_name: stringProperty("dataDisplayName"), + gallery_kind: stringProperty("dataGalleryKind"), + skill_directory: stringProperty("dataSkillDirectory"), + skill_name: stringProperty("dataSkillName"), + }); +} diff --git a/packages/shared/src/codexMarkdownDirectives.ts b/packages/shared/src/codexMarkdownDirectives.ts index 6ff396eddb12a..fecbdb99fe0ac 100644 --- a/packages/shared/src/codexMarkdownDirectives.ts +++ b/packages/shared/src/codexMarkdownDirectives.ts @@ -23,15 +23,6 @@ const CODEX_FILE_CITATION_NAME = "codex-file-citation"; const CODEX_FOLLOW_UP_NAME = "codex-followup"; const CODEX_ARTIFACT_TEMPLATE_NAME = "artifact-template"; -export const CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES = [ - "dataCodexArtifactTemplate", - "dataArtifactKind", - "dataDisplayName", - "dataGalleryKind", - "dataSkillDirectory", - "dataSkillName", -] as const; - interface MarkdownPosition { readonly start: { readonly offset?: number }; readonly end: { readonly offset?: number }; @@ -404,20 +395,3 @@ export function splitCodexArtifactTemplateMarkdown( } return segments; } - -export function artifactTemplateFromHastProperties( - properties: Readonly> | null | undefined, -): CodexArtifactTemplate | null { - if (properties?.dataCodexArtifactTemplate !== "true") return null; - const stringProperty = (name: string) => { - const value = properties[name]; - return typeof value === "string" ? value : undefined; - }; - return resolveCodexArtifactTemplate({ - artifact_kind: stringProperty("dataArtifactKind"), - display_name: stringProperty("dataDisplayName"), - gallery_kind: stringProperty("dataGalleryKind"), - skill_directory: stringProperty("dataSkillDirectory"), - skill_name: stringProperty("dataSkillName"), - }); -} diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index bd54df18b4018..4c32a4c767f6f 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -1,8 +1,19 @@ import { describe, expect, it } from "vite-plus/test"; -import { collectComposerInlineTokens, composerMathRanges } from "./composerInlineTokens.ts"; +import { + collectComposerInlineTokens as collectWithoutMath, + type CollectComposerInlineTokensOptions, + composerFileLinksToPlainText, + composerMathRanges, +} from "./composerInlineTokens.ts"; +import { markdownMathRanges } from "./markdownMath.ts"; import { serializeComposerFileLink } from "./composerTrigger.ts"; +const collectComposerInlineTokens = ( + text: string, + options: CollectComposerInlineTokensOptions = {}, +) => collectWithoutMath(text, { findMath: markdownMathRanges, ...options }); + describe("collectComposerInlineTokens", () => { it("collects file links, mentions, and skills with source ranges", () => { const text = "Use $ui and inspect [Chat.tsx](src/Chat.tsx) with @AGENTS.md please"; @@ -229,8 +240,21 @@ describe("collectComposerInlineTokens", () => { it("still finds a formula after a mention that starts the line", () => { const link = serializeComposerFileLink("app/routes/posts.$postId.tsx"); - expect(composerMathRanges(`${link} sets $x_i$`).map((formula) => formula.source)).toEqual([ - "$x_i$", - ]); + expect( + composerMathRanges(`${link} sets $x_i$`, markdownMathRanges).map((formula) => formula.source), + ).toEqual(["$x_i$"]); + }); +}); + +describe("composerFileLinksToPlainText", () => { + it("shows file mentions by name and leaves other links as written", () => { + const mentions = ["src/foo.ts", ".gitignore", "pkg/__init__.py", "docs/My File (draft).md"] + .map(serializeComposerFileLink) + .join(" "); + expect(composerFileLinksToPlainText(`Review ${mentions}`)).toBe( + "Review foo.ts .gitignore __init__.py My File (draft).md", + ); + const links = "See [docs](https://example.com) and [the config](src/config.ts)"; + expect(composerFileLinksToPlainText(links)).toBe(links); }); }); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index 4b9f3102f4133..8bdc1b082644c 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,4 +1,9 @@ -import { markdownMathRanges } from "./markdownMath.ts"; +import { fileBasename } from "./path.ts"; + +/** The formulas a Markdown parser finds in text, as source offsets. */ +export type FindMathRanges = ( + text: string, +) => ReadonlyArray<{ readonly start: number; readonly end: number }>; export type ComposerInlineToken = | { @@ -18,6 +23,8 @@ export type ComposerInlineToken = export interface CollectComposerInlineTokensOptions { readonly preserveTrailingFrom?: ReadonlyArray; + /** Formulas keep their literal tokens; without it, nothing is read as math. */ + readonly findMath?: FindMathRanges; } const SKILL_MENTION_SOURCE = @@ -105,6 +112,7 @@ function collectMentionTokens(text: string): ComposerInlineToken[] { */ export function composerMathRanges( text: string, + findMath: FindMathRanges, mentions: ReadonlyArray = collectMentionTokens(text), ) { let masked = text; @@ -115,7 +123,7 @@ export function composerMathRanges( "x".repeat(mention.end - mention.start) + masked.slice(mention.end); } - return markdownMathRanges(masked).map(({ start, end }) => ({ + return findMath(masked).map(({ start, end }) => ({ start, end, source: text.slice(start, end), @@ -162,10 +170,26 @@ export function collectComposerInlineTokens( // TeX can contain literal skill and file tokens, especially inside \text{}. // They remain formula source rather than becoming composer context chips. // Confirmed trailing file links are masked too, so a kept chip is not read as TeX. - const math = matches.length > 0 ? composerMathRanges(text, matches) : []; + const math = + matches.length > 0 && options.findMath + ? composerMathRanges(text, options.findMath, matches) + : []; return matches .filter( (match) => !math.some((formula) => match.start < formula.end && match.end > formula.start), ) .sort((left, right) => left.start - right.start); } + +/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */ +export function composerFileLinksToPlainText(text: string): string { + let result = ""; + let cursor = 0; + // The composer reads a link as a mention only before whitespace, so one may end the text. + for (const token of collectMentionTokens(`${text} `)) { + if (!token.source.startsWith("[")) continue; + result += text.slice(cursor, token.start) + fileBasename(token.value); + cursor = token.end; + } + return result + text.slice(cursor); +} diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts new file mode 100644 index 0000000000000..a5cf2a8017b35 --- /dev/null +++ b/packages/shared/src/markdownChunks.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { splitMarkdown } from "./markdownChunks.ts"; + +const splitLargeMarkdown = (text: string, targetChars?: number) => + splitMarkdown(text, targetChars).chunks; + +const starts = (text: string) => + splitLargeMarkdown(text, 1).map((chunk) => chunk.text.split("\n")[0]); + +describe("splitMarkdown", () => { + it("cuts only where a new top-level block starts, and keeps every byte", () => { + const text = [ + "# Title", + "Intro paragraph", + "", + "- item one", + "", + " continued item", + "- item two", + "", + "2. ordered", + "", + "```md", + "# not a heading", + "", + "Not a paragraph", + "```", + "", + "> quote", + "", + "Closing paragraph", + "## Next", + "---", + "", + "| a | b |", + ].join("\n"); + const chunks = splitLargeMarkdown(text, 1); + expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text); + expect(chunks.reduce((sum, chunk) => sum + chunk.lines, 0)).toBe(text.split("\n").length); + expect(starts(text)).toEqual([ + "# Title", + "```md", + "> quote", + "Closing paragraph", + "## Next", + "| a | b |", + ]); + }); + + it("keeps a fence open until a matching closer", () => { + const text = ["````", "```", "", "# inside", "````", "", "after"].join("\n"); + expect(starts(text)).toEqual(["````", "after"]); + }); + + it("keeps HTML blocks and display math open across blank lines", () => { + const text = [ + "", + "", + "$$", + "", + "Inside math", + "$$", + "", + "

    ",
    +      "",
    +      "Preformatted",
    +      "
    ", + "", + "", + "", + "
    ", + "# literal", + "
    ", + "", + "after", + ].join("\n"); + expect(starts(text)).toEqual(["/], + [/^ {0,3}<\?/, /\?>/], + [/^ {0,3}/], + [/^ {0,3}/], + [/^ {0,3}\$\$/, /\$\$/], +]; + +// A tag name, not an autolink such as . +const HTML_BLOCK_START = /^ {0,3}<\/?[A-Za-z][A-Za-z0-9-]*(?=[\s/>]|$)/; + +/** Returns how to recognize the end of a block that `line` opens, or null for none. */ +function blockCloser(line: string): ((line: string) => boolean) | null { + const fence = FENCE_OPEN.exec(line)?.[1]; + if (fence) { + return (next) => { + const closer = FENCE_OPEN.exec(next)?.[1]; + return ( + closer !== undefined && + closer[0] === fence[0] && + closer.length >= fence.length && + !next.trim().slice(closer.length) + ); + }; + } + for (const [open, close] of SPANNING_BLOCKS) { + const opener = open.exec(line)?.[0]; + if (opener === undefined) continue; + return close.test(line.slice(opener.length)) ? null : (next) => close.test(next); + } + // Other HTML blocks (CommonMark types 6 and 7) run until a blank line. + return HTML_BLOCK_START.test(line) ? (next) => next.trim() === "" : null; +} + +export interface MarkdownChunk { + readonly text: string; + readonly lines: number; +} + +const FRONTMATTER_OPEN = /^\uFEFF?---[ \t]*\r?$/; +const FRONTMATTER_CLOSE = /^(?:---|\.\.\.)[ \t]*\r?$/; +// An opening rule with no closer is a thematic break, not frontmatter; stop waiting for one. +const FRONTMATTER_MAX_LINES = 1000; + +// A one-line link reference definition; footnotes are left alone so each piece does not grow +// a footnote section. +const LINK_DEFINITION = + /^ {0,3}\[(?!\^)(?:[^\]\\]|\\.)+\]:[ \t]*(?:<[^<>\n]*>|[^\s<]\S*)(?:[ \t]+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?[ \t]*\r?$/; +// Definitions past this are not repeated into every piece; their parse cost would outweigh links. +const SHARED_DEFINITIONS_MAX_CHARS = 16 * 1024; + +export interface SplitMarkdown { + readonly chunks: readonly MarkdownChunk[]; + readonly definitions: string; +} + +/** + * Cuts Markdown into pieces of roughly `targetChars`, only at column-0 headings or paragraphs + * that start a new top-level block. Leading frontmatter stays in the first piece. Link + * definitions are collected so every piece can resolve them; footnotes resolve only inside their + * own piece, and duplicate heading slugs restart per piece. + */ +export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): SplitMarkdown { + const chunks: MarkdownChunk[] = []; + const definitions: string[] = []; + let lines: string[] = []; + let first = true; + let chars = 0; + let closes: ((line: string) => boolean) | null = null; + let afterBlankLine = false; + let afterDefinition = false; + let afterHeading = false; + let definitionChars = 0; + const flush = () => { + chunks.push({ text: lines.join("\n"), lines: lines.length }); + lines = []; + chars = 0; + }; + for (const line of text.split("\n")) { + if (closes !== null) { + if (closes(line)) closes = null; + } else if (first && FRONTMATTER_OPEN.test(line)) { + let seen = 0; + closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES; + } else { + const cut = + chars >= targetChars && + (ATX_HEADING.test(line) || + (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line))); + if (cut) flush(); + closes = blockCloser(line); + // A definition cannot interrupt a paragraph, so it follows a blank line, a heading or + // another definition. + const definition: boolean = + (first || afterBlankLine || afterDefinition || afterHeading) && LINK_DEFINITION.test(line); + afterDefinition = definition; + if (definition && definitionChars + line.length < SHARED_DEFINITIONS_MAX_CHARS) { + definitions.push(line.trim()); + definitionChars += line.length + 1; + } + } + first = false; + lines.push(line); + chars += line.length + 1; + afterBlankLine = line.trim() === ""; + afterHeading = closes === null && (ATX_HEADING.test(line) || THEMATIC_BREAK.test(line)); + } + flush(); + return { chunks, definitions: definitions.join("\n") }; +} + +/** Appends shared link definitions after a piece, leaving its own offsets unchanged. */ +export function withMarkdownDefinitions(text: string, definitions: string): string { + return definitions ? `${text}\n\n${definitions}` : text; +} diff --git a/apps/web/src/markdownGithubAlerts.test.tsx b/packages/shared/src/markdownGithubAlerts.test.ts similarity index 70% rename from apps/web/src/markdownGithubAlerts.test.tsx rename to packages/shared/src/markdownGithubAlerts.test.ts index 0f01e322681a4..31a84b465f91a 100644 --- a/apps/web/src/markdownGithubAlerts.test.tsx +++ b/packages/shared/src/markdownGithubAlerts.test.ts @@ -1,14 +1,21 @@ -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; +import { toHtml } from "hast-util-to-html"; import remarkGfm from "remark-gfm"; +import remarkParse from "remark-parse"; +import remarkRehype from "remark-rehype"; +import { type PluggableList, unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; -import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts"; +import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; + +const processor = unified() + .use(remarkParse) + .use([remarkGfm, remarkGithubAlerts] satisfies PluggableList) + .use(remarkRehype, { allowDangerousHtml: true }); function renderMarkdown(markdown: string): string { - return renderToStaticMarkup( - {markdown}, - ); + return toHtml(processor.runSync(processor.parse(markdown), markdown), { + allowDangerousHtml: true, + }); } describe("remarkGithubAlerts", () => { diff --git a/packages/shared/src/markdownHast.ts b/packages/shared/src/markdownHast.ts new file mode 100644 index 0000000000000..31561e5f4d740 --- /dev/null +++ b/packages/shared/src/markdownHast.ts @@ -0,0 +1,213 @@ +import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; +import type { Root } from "hast"; +import { defaultSchema, sanitize, type Schema } from "hast-util-sanitize"; + +import { CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES } from "./codexArtifactTemplates.ts"; +import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts"; +import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; + +type MarkdownImageHastNode = { + type?: string; + value?: string; + tagName?: string; + properties?: Record; + children?: MarkdownImageHastNode[]; +}; + +function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] { + return (node.children ?? []).filter( + (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""), + ); +} + +const STANDALONE_IMAGE_BLOCKS = new Set([ + "p", + "div", + "li", + "td", + "th", + "figure", + "center", + "blockquote", +]); + +function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined { + const children = meaningfulHastChildren(node); + if (children.length !== 1) return undefined; + const only = children[0]; + if (only?.type !== "element") return undefined; + if (only.tagName === "img") return only; + return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em" + ? soleImageDescendant(only) + : undefined; +} + +function markStandaloneImages(node: MarkdownImageHastNode) { + if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) { + const image = soleImageDescendant(node); + if (image) image.properties = { ...image.properties, dataStandalone: true }; + } + node.children?.forEach((child) => { + if (child.type === "element") markStandaloneImages(child); + }); +} + +const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i; + +/** + * The renderer resolves an ``'s `src` (workspace files, host media) but never a ``'s + * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves + * onto the `` for the renderer to pick by theme; every source is then dropped. + */ +function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) { + if (!picture.children) return; + const image = picture.children.find((child) => child.tagName === "img"); + for (const source of picture.children) { + if (source.tagName !== "source" || !image) continue; + const media = source.properties?.media; + const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined; + const srcSet = source.properties?.srcSet; + const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet; + // A candidate's URL runs to the first space (a descriptor such as `2x` may follow). + const url = + typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : ""; + const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc"; + // As in a browser, the first source that matches a scheme is the one shown. + if (scheme && url && image.properties?.[key] === undefined) { + // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path. + const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url; + image.properties = { ...image.properties, [key]: value }; + } + } + picture.children = picture.children.filter((child) => child.tagName !== "source"); +} + +export function rehypePreserveImageSourceMeta() { + return (tree: MarkdownImageHastNode) => { + const visit = (node: MarkdownImageHastNode) => { + const src = node.properties?.src; + const title = node.properties?.title; + if (node.type === "element" && node.tagName === "picture") { + moveColorSchemeSourcesToImage(node); + } + if (node.type === "element" && node.tagName === "img") { + node.properties = { + ...node.properties, + ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}), + ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}), + }; + } + node.children?.forEach(visit); + }; + + visit(tree); + markStandaloneImages(tree); + }; +} + +const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"]; + +// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first. +function normalizeLocalEditorHref(href: string): string { + try { + const url = new URL(href); + return isLocalEditorFileUrl(url) ? url.href : href; + } catch { + // Not an absolute URL; the sanitizer decides. + return href; + } +} + +export function rehypeNormalizeLocalEditorLinks() { + return (tree: MarkdownImageHastNode) => { + const visit = (node: MarkdownImageHastNode) => { + const href = node.properties?.href; + if (node.type === "element" && node.tagName === "a" && typeof href === "string") { + const normalized = normalizeLocalEditorHref(href); + if (normalized !== href) node.properties = { ...node.properties, href: normalized }; + } + node.children?.forEach(visit); + }; + + visit(tree); + }; +} + +export const CHAT_MARKDOWN_SANITIZE_SCHEMA = { + ...defaultSchema, + attributes: { + ...defaultSchema.attributes, + "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), + // Fence languages plus the two math classes the web chat's math plugin emits. + code: [ + ["className", /^language-./, "math-inline", "math-display"], + "dataCodeMeta", + "dataInlineCode", + ], + blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], + // Spaces typed at the start of a user's line (keepLeadingWhitespace). + span: [...(defaultSchema.attributes?.span ?? []), "dataLeadingWhitespace"], + div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES], + a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"], + img: [ + ...(defaultSchema.attributes?.img ?? []), + "dataDarkSrc", + "dataLightSrc", + "dataLocalSrc", + "dataMarkdownTitle", + "dataStandalone", + ], + }, + protocols: { + ...defaultSchema.protocols, + href: [ + ...(defaultSchema.protocols?.href ?? []), + "file", + "t3-citation", + "t3-context", + THREAD_LINK_PROTOCOL, + "board", + "t3-dashboard", + // Scheme only: the renderer's URL transform checks the rest of the link shape. + ...LOCAL_FILE_LINK_SCHEMES, + ], + src: IMAGE_SRC_PROTOCOLS, + dataDarkSrc: IMAGE_SRC_PROTOCOLS, + dataLightSrc: IMAGE_SRC_PROTOCOLS, + }, +} satisfies Schema; + +/** Sanitizes one tree with the chat's schema, as the last rehype plugin does. */ +export const sanitizeChatHast = (tree: Root): Root => + sanitize(tree, CHAT_MARKDOWN_SANITIZE_SCHEMA) as Root; + +export type ChatMarkdownImageProperties = { + readonly src?: unknown; + readonly dataLocalSrc?: unknown; + readonly dataDarkSrc?: unknown; + readonly dataLightSrc?: unknown; +}; + +/** Keep the authored path for file links and normalize Windows separators for classification. */ +export function chatMarkdownImageSource( + properties?: ChatMarkdownImageProperties, + theme?: "dark" | "light", +) { + const themeSrc = + theme === undefined + ? undefined + : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; + const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; + const source = + typeof themeSrc === "string" + ? themeSrc + : typeof localSrc === "string" + ? localSrc + : properties?.src; + if (typeof source !== "string") return null; + const authoredSrc = normalizeMarkdownLinkDestination(source); + return { + authoredSrc, + classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, + }; +} diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index a1f0af927636d..80204d903892b 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -174,6 +174,9 @@ describe("extractMarkdownLinkHrefs", () => { ["[".repeat(32_000), []], ["[a]( invalid [b](ok)", [" { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index ecce17d7f0eb9..976ba9c77b11c 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -519,41 +519,36 @@ function markdownLinkDestinationScanner(markdown: string) { } } const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart); - if (hrefEnd === null || hrefEnd === hrefStart) return null; + if (hrefEnd === null) return null; const end = bareTail(hrefEnd); return end === null ? null : { hrefStart, hrefEnd, end }; }; } -// The composer escapes brackets in labels (`[\[id\].tsx](...)`), and `\]` does not close one. -function unescapedLabelEnd(markdown: string, start: number): number { - let end = markdown.indexOf("]", start); - while (end !== -1) { - let backslashes = 0; - while (end - backslashes > start && markdown[end - backslashes - 1] === "\\") backslashes += 1; - if (backslashes % 2 === 0) return end; - end = markdown.indexOf("]", end + 1); - } - return -1; -} - +// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them +// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels. export function extractMarkdownLinkHrefs(markdown: string): string[] { const hrefs: string[] = []; const scanDestination = markdownLinkDestinationScanner(markdown); - let cursor = 0; - while (cursor < markdown.length) { - const labelStart = markdown.indexOf("[", cursor); - if (labelStart === -1) break; - const labelEnd = unescapedLabelEnd(markdown, labelStart + 1); - if (labelEnd === -1) break; - - // Skip a failed label once; nested openings share its closing bracket. - cursor = labelEnd + 1; - const destination = scanDestination(cursor); - if (!destination) continue; - cursor = destination.end; - const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); - if (href) hrefs.push(href); + const bracket = /[[\]\\]|\n[ \t\r]*\n/g; + let openBrackets = 0; + for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) { + if (match[0] === "\\") { + bracket.lastIndex = match.index + 2; + } else if (match[0].startsWith("\n")) { + openBrackets = 0; + } else if (match[0] === "[") { + openBrackets += 1; + } else if (openBrackets > 0) { + openBrackets -= 1; + const destination = scanDestination(match.index + 1); + if (!destination) continue; + // A link cannot contain a link, so the brackets still open around it become text. + openBrackets = 0; + bracket.lastIndex = destination.end; + const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); + if (href) hrefs.push(href); + } } return hrefs; } @@ -651,3 +646,6 @@ export function absoluteFilePathMatches(text: string): Array<{ index: number; pa } return paths; } + +// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`. +export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/; diff --git a/apps/web/src/markdownListIndentation.test.tsx b/packages/shared/src/markdownListIndentation.test.ts similarity index 72% rename from apps/web/src/markdownListIndentation.test.tsx rename to packages/shared/src/markdownListIndentation.test.ts index 895d22f8bdac6..bcf56845f6cae 100644 --- a/apps/web/src/markdownListIndentation.test.tsx +++ b/packages/shared/src/markdownListIndentation.test.ts @@ -1,16 +1,21 @@ -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; +import { toHtml } from "hast-util-to-html"; import remarkGfm from "remark-gfm"; +import remarkParse from "remark-parse"; +import remarkRehype from "remark-rehype"; +import { type PluggableList, unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; -import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation"; +import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts"; + +const processor = unified() + .use(remarkParse) + .use([remarkGfm, remarkNormalizeListItemIndentation] satisfies PluggableList) + .use(remarkRehype, { allowDangerousHtml: true }); function renderMarkdown(markdown: string): string { - return renderToStaticMarkup( - - {markdown} - , - ); + return toHtml(processor.runSync(processor.parse(markdown), markdown), { + allowDangerousHtml: true, + }); } describe("remarkNormalizeListItemIndentation", () => { @@ -26,7 +31,7 @@ describe("remarkNormalizeListItemIndentation", () => { expect(html).not.toContain("
    ");
         expect(html).toContain("
  • for (const step of rest.steps) {
  • "); expect(html).toContain("
  • if (step.request.body) {
  • "); - expect(html).toContain("
  • step.request.body = "<redacted>";
  • "); + expect(html).toContain('
  • step.request.body = "";
  • '); }); it("preserves every recovered block separated by blank lines", () => { diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index ae4dd6d26bdea..f59496465e0ba 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -1,4 +1,3 @@ -import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; import type { Heading, Link, @@ -15,7 +14,7 @@ import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import { find, html } from "property-information"; import rehypeRaw from "rehype-raw"; -import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; +import rehypeSanitize from "rehype-sanitize"; import remarkBreaks from "remark-breaks"; import remarkCjkFriendly from "remark-cjk-friendly"; import remarkGfm from "remark-gfm"; @@ -26,17 +25,18 @@ import { remarkEnableLeadingWhitespace, remarkKeepLeadingWhitespace, } from "./markdownLeadingWhitespace.ts"; -import { - CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES, - remarkCodexDirectives, -} from "./codexMarkdownDirectives.ts"; -import { - absoluteFilePathMatches, - isWindowsDrivePathHref, - normalizeMarkdownLinkDestination, -} from "./markdownLinks.ts"; +import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts"; +import { absoluteFilePathMatches } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; -import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; +import { + CHAT_MARKDOWN_SANITIZE_SCHEMA, + chatMarkdownImageSource, + rehypeNormalizeLocalEditorLinks, + rehypePreserveImageSourceMeta, + type ChatMarkdownImageProperties, +} from "./markdownHast.ts"; + +export { chatMarkdownImageSource, type ChatMarkdownImageProperties }; export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; @@ -48,44 +48,6 @@ type MarkdownImageHastNode = { children?: MarkdownImageHastNode[]; }; -function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] { - return (node.children ?? []).filter( - (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""), - ); -} - -const STANDALONE_IMAGE_BLOCKS = new Set([ - "p", - "div", - "li", - "td", - "th", - "figure", - "center", - "blockquote", -]); - -function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined { - const children = meaningfulHastChildren(node); - if (children.length !== 1) return undefined; - const only = children[0]; - if (only?.type !== "element") return undefined; - if (only.tagName === "img") return only; - return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em" - ? soleImageDescendant(only) - : undefined; -} - -function markStandaloneImages(node: MarkdownImageHastNode) { - if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) { - const image = soleImageDescendant(node); - if (image) image.properties = { ...image.properties, dataStandalone: true }; - } - node.children?.forEach((child) => { - if (child.type === "element") markStandaloneImages(child); - }); -} - // Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag. const RAW_HTML_TAG_PATTERN = /|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g; @@ -134,123 +96,6 @@ function rehypePreserveBareAnchorPlaceholders() { }; } -const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i; - -/** - * The renderer resolves an ``'s `src` (workspace files, host media) but never a ``'s - * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves - * onto the `` for the renderer to pick by theme; every source is then dropped. - */ -function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) { - if (!picture.children) return; - const image = picture.children.find((child) => child.tagName === "img"); - for (const source of picture.children) { - if (source.tagName !== "source" || !image) continue; - const media = source.properties?.media; - const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined; - const srcSet = source.properties?.srcSet; - const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet; - // A candidate's URL runs to the first space (a descriptor such as `2x` may follow). - const url = - typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : ""; - const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc"; - // As in a browser, the first source that matches a scheme is the one shown. - if (scheme && url && image.properties?.[key] === undefined) { - // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path. - const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url; - image.properties = { ...image.properties, [key]: value }; - } - } - picture.children = picture.children.filter((child) => child.tagName !== "source"); -} - -function rehypePreserveImageSourceMeta() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const src = node.properties?.src; - const title = node.properties?.title; - if (node.type === "element" && node.tagName === "picture") { - moveColorSchemeSourcesToImage(node); - } - if (node.type === "element" && node.tagName === "img") { - node.properties = { - ...node.properties, - ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}), - ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}), - }; - } - node.children?.forEach(visit); - }; - - visit(tree); - markStandaloneImages(tree); - }; -} - -const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"]; - -// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first. -function rehypeNormalizeLocalEditorLinks() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const href = node.properties?.href; - if (node.type === "element" && node.tagName === "a" && typeof href === "string") { - try { - const url = new URL(href); - if (isLocalEditorFileUrl(url)) node.properties = { ...node.properties, href: url.href }; - } catch { - // Not an absolute URL; the sanitizer decides. - } - } - node.children?.forEach(visit); - }; - - visit(tree); - }; -} - -const CHAT_MARKDOWN_SANITIZE_SCHEMA = { - ...defaultSchema, - attributes: { - ...defaultSchema.attributes, - "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), - // Fence languages plus the two math classes the web chat's math plugin emits. - code: [ - ["className", /^language-./, "math-inline", "math-display"], - "dataCodeMeta", - "dataInlineCode", - ], - blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], - div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES], - a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"], - img: [ - ...(defaultSchema.attributes?.img ?? []), - "dataDarkSrc", - "dataLightSrc", - "dataLocalSrc", - "dataMarkdownTitle", - "dataStandalone", - ], - }, - protocols: { - ...defaultSchema.protocols, - href: [ - ...(defaultSchema.protocols?.href ?? []), - "file", - "t3-citation", - "t3-context", - THREAD_LINK_PROTOCOL, - "board", - "t3-dashboard", - // Scheme only: the renderer's URL transform checks the rest of the link shape. - ...LOCAL_FILE_LINK_SCHEMES, - ], - src: IMAGE_SRC_PROTOCOLS, - dataDarkSrc: IMAGE_SRC_PROTOCOLS, - dataLightSrc: IMAGE_SRC_PROTOCOLS, - }, -} satisfies Parameters[0]; - export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkGfm, remarkEndAutolinksAtScriptPunctuation, @@ -294,16 +139,6 @@ export const CHAT_USER_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkEnableLeadingWhitespace, ]; -export const ASSISTANT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ - ...CHAT_MARKDOWN_REMARK_PLUGINS, - [remarkGfm, { singleTilde: false }], -]; - -export const ASSISTANT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [ - ...CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS, - [remarkGfm, { singleTilde: false }], -]; - // Start tags an HTML parser closes an open `

    ` for. const CLOSES_PARAGRAPH = new Set( "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split( @@ -767,10 +602,6 @@ function remarkNormalizeLinksAndTagInlineCode() { }; } -export function shouldPreserveAssistantLineBreaks(text: string): boolean { - return /^★ Insight(?:\s|─)/mu.test(text); -} - export function remarkAssistantInsights(this: Processor) { return (tree: Root, file: { value: unknown }) => { const source = String(file.value); @@ -855,37 +686,6 @@ const imageSourceProcessor = unified() .use(remarkRehype, { allowDangerousHtml: true }) .use(CHAT_MARKDOWN_REHYPE_PLUGINS); -export type ChatMarkdownImageProperties = { - readonly src?: unknown; - readonly dataLocalSrc?: unknown; - readonly dataDarkSrc?: unknown; - readonly dataLightSrc?: unknown; -}; - -/** Keep the authored path for file links and normalize Windows separators for classification. */ -export function chatMarkdownImageSource( - properties?: ChatMarkdownImageProperties, - theme?: "dark" | "light", -) { - const themeSrc = - theme === undefined - ? undefined - : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; - const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; - const source = - typeof themeSrc === "string" - ? themeSrc - : typeof localSrc === "string" - ? localSrc - : properties?.src; - if (typeof source !== "string") return null; - const authoredSrc = normalizeMarkdownLinkDestination(source); - return { - authoredSrc, - classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, - }; -} - interface ImageSourceNode { readonly type: string; readonly tagName?: string; diff --git a/packages/shared/src/markdownTaskEdits.ts b/packages/shared/src/markdownTaskEdits.ts new file mode 100644 index 0000000000000..2f33428613147 --- /dev/null +++ b/packages/shared/src/markdownTaskEdits.ts @@ -0,0 +1,28 @@ +/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ +export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { + const firstLineEnd = markdown.indexOf("\n", listItemStart); + const firstLine = markdown.slice( + listItemStart, + firstLineEnd === -1 ? markdown.length : firstLineEnd, + ); + const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); + if (!match?.[1]) return null; + return listItemStart + firstLine.indexOf(match[1]); +} + +export function setMarkdownTaskChecked( + markdown: string, + markerOffset: number, + checked: boolean, +): string { + if ( + markerOffset < 0 || + markdown[markerOffset] !== "[" || + !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || + markdown[markerOffset + 2] !== "]" + ) { + return markdown; + } + + return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; +} diff --git a/packages/shared/src/markdownTaskList.test.ts b/packages/shared/src/markdownTaskList.test.ts index 5e00a3926fa54..7f7519ce49ee5 100644 --- a/packages/shared/src/markdownTaskList.test.ts +++ b/packages/shared/src/markdownTaskList.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; -import { markdownTaskMarkerOffset, setMarkdownTaskChecked } from "./markdownTaskList.ts"; +import { markdownTaskMarkerOffset } from "./markdownTaskList.ts"; +import { setMarkdownTaskChecked } from "./markdownTaskEdits.ts"; describe("setMarkdownTaskChecked", () => { const markdown = "- [ ] First\n- [x] Second\n"; diff --git a/packages/shared/src/markdownTaskList.ts b/packages/shared/src/markdownTaskList.ts index fb02f757992b9..a4d18895505c6 100644 --- a/packages/shared/src/markdownTaskList.ts +++ b/packages/shared/src/markdownTaskList.ts @@ -3,36 +3,9 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; -const parser = unified().use(remarkParse).use(remarkGfm); - -/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ -export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { - const firstLineEnd = markdown.indexOf("\n", listItemStart); - const firstLine = markdown.slice( - listItemStart, - firstLineEnd === -1 ? markdown.length : firstLineEnd, - ); - const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); - if (!match?.[1]) return null; - return listItemStart + firstLine.indexOf(match[1]); -} - -export function setMarkdownTaskChecked( - markdown: string, - markerOffset: number, - checked: boolean, -): string { - if ( - markerOffset < 0 || - markdown[markerOffset] !== "[" || - !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || - markdown[markerOffset + 2] !== "]" - ) { - return markdown; - } +import { taskListMarkerOffset } from "./markdownTaskEdits.ts"; - return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; -} +const parser = unified().use(remarkParse).use(remarkGfm); /** Hard breaks as U+2028, as iOS draws them; soft breaks stay "\n". */ function plainText(node: Nodes): string { diff --git a/packages/shared/src/markdownWindowsPaths.ts b/packages/shared/src/markdownWindowsPaths.ts index c4c04490a2140..d7c827c8dba8c 100644 --- a/packages/shared/src/markdownWindowsPaths.ts +++ b/packages/shared/src/markdownWindowsPaths.ts @@ -1,5 +1,6 @@ import type { Processor } from "unified"; import { decodeString } from "micromark-util-decode-string"; +import { UNFINISHED_DRIVE_PATH } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; interface DestinationCompileContext { @@ -18,9 +19,6 @@ function keepWindowsPathDestination(this: DestinationCompileContext, token: unkn : decoded; } -// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`. -export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/; - interface EscapeCompileContext { readonly stack: ReadonlyArray<{ readonly type: string; diff --git a/packages/shared/src/nodeSqliteClient.test.ts b/packages/shared/src/nodeSqliteClient.test.ts index 24910bc0bf9cf..71a9897b841f3 100644 --- a/packages/shared/src/nodeSqliteClient.test.ts +++ b/packages/shared/src/nodeSqliteClient.test.ts @@ -148,6 +148,23 @@ layer("NodeSqliteClient", (it) => { const largeText = "x".repeat(64 * 1024 + 1); +it.effect("a rowid above 2^53 does not leave a transaction open", () => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`CREATE TABLE big (id INTEGER PRIMARY KEY, name TEXT)`; + yield* sql`INSERT INTO big (id, name) VALUES (246166233861328896, 'first')`; + // BEGIN reports the connection's last insert rowid; a failure to convert it must not + // read as a failed BEGIN, or the open transaction is never rolled back. + yield* sql.withTransaction(sql`INSERT INTO big (name) VALUES ('second')`); + yield* sql.withTransaction(sql`UPDATE big SET name = 'third' WHERE name = 'second'`); + const rows = yield* sql<{ name: string }>`SELECT name FROM big ORDER BY id`; + assert.deepStrictEqual( + rows.map((row) => row.name), + ["first", "third"], + ); + }).pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:" }))), +); + it.effect("reads integers on the values path as the caller asked, cached or not", () => Effect.gen(function* () { const sql = yield* SqlClient.SqlClient; diff --git a/packages/shared/src/nodeSqliteClient.ts b/packages/shared/src/nodeSqliteClient.ts index da521a7c6036d..bb00de7459816 100644 --- a/packages/shared/src/nodeSqliteClient.ts +++ b/packages/shared/src/nodeSqliteClient.ts @@ -286,6 +286,8 @@ parentPort.on("message", (request) => { if (pendingBatch) Atomics.wait(received, 0, 0); parentPort.postMessage({ id, rows }); } else { + // A discarded result is read as BigInt: see the same line in the in-process client. + if (!raw) statement.setReadBigInts(true); const result = statement.run(...params); parentPort.postMessage({ id, rows: raw ? result : [] }); } @@ -854,6 +856,10 @@ const make = Effect.fn("makeWithDatabase")(function* ( if (arrays) statement.setReturnArrays(true); result = Exit.succeed(statement.all(...(params as any))); } else { + // `run` reports the connection's last insert rowid even for BEGIN. One above 2^53 + // throws on conversion after the statement already took effect, so a discarded + // result is read as BigInt. + if (mode !== "raw") statement.setReadBigInts(true); const value = statement.run(...(params as any)); result = Exit.succeed( mode === "raw" ? (value as unknown as ReadonlyArray) : [], diff --git a/packages/shared/src/orchestrationV2ManualContinuation.test.ts b/packages/shared/src/orchestrationV2ManualContinuation.test.ts index 137bf6cd8f205..e7670749f6c5a 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.test.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.test.ts @@ -108,4 +108,16 @@ describe("unsentManualContinuationSource", () => { unsentManualContinuationSource(run("c", "a" as RunId), projection([a, b], [], [])), ).toBeUndefined(); }); + + it("treats a turn with promptDropped as unsent", () => { + const source = run("src"); + const a1 = attempt("a1", "src", 1); + const dropped = { ...turn("a1"), promptDropped: true as const }; + expect( + unsentManualContinuationSource( + run("r2", "src" as RunId), + projection([source], [a1], [dropped]), + ), + ).toBe(source); + }); }); diff --git a/packages/shared/src/orchestrationV2ManualContinuation.ts b/packages/shared/src/orchestrationV2ManualContinuation.ts index 3fb6c8d5a1866..ad64b63483e14 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.ts @@ -1,4 +1,8 @@ -import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { + isDeliveredProviderTurn, + type OrchestrationV2Run, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; export function unsentManualContinuationSource( run: Pick | undefined, @@ -7,7 +11,9 @@ export function unsentManualContinuationSource( let sourceId = run?.manualContinuationOfRunId; if (sourceId === undefined) return undefined; const runs = new Map(projection.runs.map((source) => [source.id, source])); - const acceptedAttempts = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttempts = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const latestAttempt = ( runId: OrchestrationV2Run["id"], matches: (attempt: (typeof projection.attempts)[number]) => boolean, diff --git a/packages/shared/src/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.ts index 8987593a0b0a5..1e011eb1c64fd 100644 --- a/packages/shared/src/orchestrationV2ThreadError.ts +++ b/packages/shared/src/orchestrationV2ThreadError.ts @@ -86,6 +86,7 @@ export function orchestrationV2WorktreePending( (latest?.status === "preparing" || latest?.status === "failed" || latest?.status === "interrupted") && + latest.startedAt === null && latest.workspacePreparation?.type === "worktree" ); } diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 08731a41c19ef..8f81723486f55 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -577,7 +577,9 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ), ).toBe(path.join(directory, "audit-command")); const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); + expect( + yield* Effect.promise(async () => resolveExecutable("audit-command", "linux", env)), + ).toBe(executable); }), ); @@ -736,7 +738,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { // A POSIX directory joined with win32 separators names nothing, so this needs a Windows host. it.effect.skipIf(HostProcess.Platform.defaultValue() !== "win32")( - "relists a changed PATH directory in the synchronous spawn resolver", + "relists a changed PATH directory in the spawn resolver", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -746,11 +748,17 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { yield* fs.utimes(directory, 946_684_800, 946_684_800); const env = { PATH: directory, PATHEXT: ".EXE;.CMD" }; const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("cursor", "win32", env)).toBe(path.join(directory, "cursor.CMD")); - expect(resolveExecutable("late", "win32", env)).toBeUndefined(); + expect(yield* Effect.promise(async () => resolveExecutable("cursor", "win32", env))).toBe( + path.join(directory, "cursor.CMD"), + ); + expect( + yield* Effect.promise(async () => resolveExecutable("late", "win32", env)), + ).toBeUndefined(); yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); yield* fs.utimes(directory, 946_684_830, 946_684_830); - expect(resolveExecutable("late", "win32", env)).toBe(path.join(directory, "late.EXE")); + expect(yield* Effect.promise(async () => resolveExecutable("late", "win32", env))).toBe( + path.join(directory, "late.EXE"), + ); }), ); }); @@ -975,6 +983,73 @@ describe("npmShimExecutable", () => { }); effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { + it.effect("yields while discovering a Windows executable", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const executable = path.join(directory, "tool.EXE"); + yield* fs.writeFileString(executable, ""); + let settled = false; + const pending = Promise.resolve( + SpawnExecutableResolution.defaultValue()(executable, "win32", { PATHEXT: ".EXE;.CMD" }), + ).then((value) => { + settled = true; + return value; + }); + try { + yield* Effect.promise(() => Promise.resolve()); + expect(settled).toBe(false); + } finally { + expect(yield* Effect.promise(() => pending)).toBe(executable); + } + }), + ), + ); + + it.effect("preserves PATH and PATHEXT order and discovers executables after a miss", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const fixture = NodePath.join(directory, "tool.EXE"); + yield* fs.writeFileString(fixture, ""); + const stat = yield* Effect.promise(() => NodeFS.promises.stat(fixture)); + const files = new Set(); + using _stat = vi.spyOn(NodeFS.promises, "stat").mockImplementation(async (candidate) => { + if (!files.has(String(candidate))) throw new Error("not found"); + return stat; + }); + const lookup = resolveSpawnCommand("tool", ["status"], { + env: { PATH: "C:\\first;C:\\later", PATHEXT: ".EXE;.CMD" }, + }); + expect((yield* lookup).command).toBe("tool"); + files.add("C:\\first\\tool.CMD"); + files.add("C:\\first\\tool.EXE"); + files.add("C:\\later\\tool.EXE"); + expect(yield* lookup).toEqual({ + command: "C:\\first\\tool.EXE", + args: ["status"], + shell: false, + }); + files.delete("C:\\first\\tool.EXE"); + expect((yield* lookup).command).toBe("C:\\first\\tool.EXE"); + expect( + yield* Effect.promise(async () => + SpawnExecutableResolution.defaultValue()("tool", "win32", { + PATH: "C:\\first;C:\\later", + PATHEXT: ".EXE;.CMD", + }), + ), + ).toBe("C:\\first\\tool.CMD"); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + ), + ), + ); + it.effect("runs Windows executables directly without a shell", () => Effect.gen(function* () { const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index ffcc1110fe381..0ba42dc3078d6 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -75,13 +75,13 @@ export type SpawnExecutableResolver = ( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -) => string | undefined; +) => string | undefined | Promise; -function resolveSpawnExecutableWithNode( +async function resolveSpawnExecutableWithNode( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -): string | undefined { +): Promise { const path = platform === "win32" ? NodePath.win32 : NodePath.posix; const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; const candidates = resolveCommandCandidates( @@ -90,20 +90,24 @@ function resolveSpawnExecutableWithNode( windowsPathExtensions, path.extname, ); - const isExecutable = (candidate: string) => { + const isExecutable = async (candidate: string) => { try { - if (!NodeFS.statSync(candidate).isFile()) return false; + if (!(await NodeFS.promises.stat(candidate)).isFile()) return false; if (platform === "win32") { return windowsPathExtensions.includes(path.extname(candidate).toUpperCase()); } - return canExecuteFile(candidate); + await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); + return true; } catch { return false; } }; if (command.includes("/") || command.includes("\\")) { - return candidates.find(isExecutable); + for (const candidate of candidates) { + if (await isExecutable(candidate)) return candidate; + } + return undefined; } for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { @@ -111,12 +115,12 @@ function resolveSpawnExecutableWithNode( if (normalizedPathEntry.length === 0) continue; const names = platform === "win32" - ? listPathDirectorySync(normalizedPathEntry, path.isAbsolute) + ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute) : undefined; for (const candidate of candidates) { if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); - if (isExecutable(candidatePath)) return candidatePath; + if (await isExecutable(candidatePath)) return candidatePath; } } return undefined; @@ -661,42 +665,42 @@ export const PathDirectoryListings = Context.Reference( { defaultValue: () => Effect.runSync(makePathDirectoryListings) }, ); -const syncPathDirectoryListings = new Map< +const resolverPathDirectoryListings = new Map< string, { readonly modified: number; readonly names: ReadonlySet } >(); -// The synchronous resolver's counterpart of `PathDirectoryListings`, under the same rules. -function listPathDirectorySync( +// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules. +async function listResolverPathDirectory( directory: string, isAbsolute: (path: string) => boolean, -): ReadonlySet | undefined { +): Promise | undefined> { let modified: number; try { - const stats = NodeFS.statSync(directory); + const stats = await NodeFS.promises.stat(directory); if (!stats.isDirectory()) return undefined; modified = stats.mtimeMs; } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; } - const cached = syncPathDirectoryListings.get(directory); + const cached = resolverPathDirectoryListings.get(directory); if (cached?.modified === modified) return cached.names; - syncPathDirectoryListings.delete(directory); + resolverPathDirectoryListings.delete(directory); // This resolver runs outside Effect, so it has no Clock to read. // @effect-diagnostics-next-line globalDate:off const listedAtMs = Date.now(); let names: ReadonlySet; try { - names = new Set(NodeFS.readdirSync(directory).map((entry) => entry.toLowerCase())); + names = new Set((await NodeFS.promises.readdir(directory)).map((entry) => entry.toLowerCase())); } catch { return undefined; } if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { - if (syncPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { - const oldest = syncPathDirectoryListings.keys().next().value; - if (oldest !== undefined) syncPathDirectoryListings.delete(oldest); + if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = resolverPathDirectoryListings.keys().next().value; + if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest); } - syncPathDirectoryListings.set(directory, { modified, names }); + resolverPathDirectoryListings.set(directory, { modified, names }); } return names; } @@ -1002,18 +1006,21 @@ const resolveMacosGit = Effect.fnUntraced(function* ( const nowNanos = yield* Clock.currentTimeNanos; const cached = cache.get(cacheKey); // An Xcode update or removal deletes the binary; look again instead of failing the spawn. - if ( - cached !== undefined && - cached.expiresAtNanos > nowNanos && - (cached.resolvedPath === null || - resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined) - ) { - return cached.resolvedPath ?? "git"; + if (cached !== undefined && cached.expiresAtNanos > nowNanos) { + const cachedPath = cached.resolvedPath; + if ( + cachedPath === null || + (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== + undefined + ) { + return cachedPath ?? "git"; + } } - const located = - resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); + const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = - located !== undefined && resolveExecutable(located, "darwin", env) !== undefined + located !== undefined && + (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined ? located : null; cacheCommandResolution(cache, cacheKey, realGit, nowNanos); @@ -1093,10 +1100,8 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( shell: false, }; } - // The scan is synchronous and runs before every child process, so it shares - // the PATH scan cache above. Explicit paths stay uncached for the same reason, - // and so do misses: a failed spawn is how providers report "not installed", - // and that has to clear the moment the binary appears. + // Cache successful PATH lookups. Explicit paths and misses stay uncached so + // newly installed executables are discoverable immediately. const explicitPath = command.includes("/") || command.includes("\\"); const cache = yield* CommandResolutionCache; const cacheKey = [ @@ -1114,7 +1119,7 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( if (cached !== undefined && cached.expiresAtNanos > nowNanos) { resolvedExecutable = cached.resolvedPath; } else { - const found = resolveExecutable(command, platform, env); + const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env)); resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env); if (!explicitPath && resolvedExecutable !== null) { cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos); diff --git a/packages/shared/src/t3McpToolPresentation.ts b/packages/shared/src/t3McpToolPresentation.ts index c85e46dd55bb3..c1718941a9a71 100644 --- a/packages/shared/src/t3McpToolPresentation.ts +++ b/packages/shared/src/t3McpToolPresentation.ts @@ -362,6 +362,7 @@ const T3_MCP_TOOLS: Readonly> = { ["Handle", "Handling", "Handled", "pending questions"], "question-respond", ), + t3_workflow: tool(["Use", "Using", "Used", "workflow runs"], "thread-send"), t3_submit_output: tool(["Submit", "Submitting", "Submitted", "the result"], "thread-send"), t3_queue_list: tool(["List", "Listing", "Listed", "queued messages"], "queue-list"), t3_queue_read: tool(["Read", "Reading", "Read", "a queued message"], "queue-read"), diff --git a/packages/shared/src/textDirection.ts b/packages/shared/src/textDirection.ts index 0d4a7d88fd837..1efe672108cad 100644 --- a/packages/shared/src/textDirection.ts +++ b/packages/shared/src/textDirection.ts @@ -2,8 +2,8 @@ export type TextDirection = "ltr" | "rtl"; // Hebrew through Arabic Extended-A, their presentation forms, and the // supplementary right-to-left blocks. -const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; -const LETTER = /\p{L}/u; +export const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; +export const LETTER = /\p{L}/u; const SENTENCE_END = /(?<=[.!?؟])(? { AzureDevOpsCli.azureCliInvocation().pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }), - Effect.provideService(SpawnExecutableResolution, () => launcher), + Effect.provideService(SpawnExecutableResolution, async () => launcher), Effect.provideService(AzureCliInstallLocation, () => install), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts index 6cffe9ab0b3ab..f289e7406950f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts @@ -495,7 +495,8 @@ export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(functio return { command: "az", args: [] } satisfies AzureCliInvocation; } const resolveExecutable = yield* SpawnExecutableResolution; - const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const launcher = yield* Effect.promise(async () => resolveExecutable("az", "win32", env)); const installFor = yield* AzureCliInstallLocation; const install = launcher === undefined ? undefined : installFor(launcher); // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode. diff --git a/packages/source-control-core/src/server/IssueTrackerHost.ts b/packages/source-control-core/src/server/IssueTrackerHost.ts index efc51b5046de2..eb85a2f711a5e 100644 --- a/packages/source-control-core/src/server/IssueTrackerHost.ts +++ b/packages/source-control-core/src/server/IssueTrackerHost.ts @@ -2,12 +2,12 @@ * What a standalone tracker package may ask of the server it runs in: the credential the user * saved in Settings. Git-host trackers never need it; their CLIs carry their own credentials. */ -import type { IssueTrackerKind } from "@t3tools/contracts"; +import type { IssueTrackerAccountId, IssueTrackerKind } from "@t3tools/contracts"; import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; +import * as Effect from "effect/Effect"; import type * as Option from "effect/Option"; -import type { IssueTrackerError } from "./IssueTracker.ts"; +import type { IssueTrackerApi, IssueTrackerError } from "./IssueTracker.ts"; export class IssueTrackerHost extends Context.Service< IssueTrackerHost, @@ -20,3 +20,53 @@ export class IssueTrackerHost extends Context.Service< }; } >()("@t3tools/source-control-core/server/IssueTrackerHost") {} + +/** + * The account a standalone tracker call is made as, set by the server around each call; null is + * the tracker's first account. A tracker never reads it: `credentials.get` does. + */ +export const IssueTrackerAccount = Context.Reference( + "@t3tools/source-control-core/server/IssueTrackerHost/IssueTrackerAccount", + { defaultValue: () => null }, +); + +/** The tracker with every call made as one account, so no call site can forget to name it. */ +export function asIssueTrackerAccount( + api: IssueTrackerApi, + accountId: IssueTrackerAccountId | null, +): IssueTrackerApi { + if (accountId === null) return api; + const as = (effect: Effect.Effect) => + Effect.provideService(effect, IssueTrackerAccount, accountId); + const { + getIssueLink, + create, + comment, + update, + setState, + setReaction, + listTemplates, + listCandidates, + } = api; + // Every key is required here, so a method added to IssueTrackerApi fails to compile until it + // is wrapped instead of silently running as the first account. + const wrapped: { readonly [K in keyof IssueTrackerApi]-?: IssueTrackerApi[K] | undefined } = { + kind: api.kind, + capabilities: api.capabilities, + getViewer: (input) => as(api.getViewer(input)), + listIssues: (input) => as(api.listIssues(input)), + getIssue: (input) => as(api.getIssue(input)), + getComments: (input) => as(api.getComments(input)), + getIssueLink: getIssueLink && ((input) => as(getIssueLink(input))), + create: create && ((input) => as(create(input))), + comment: comment && ((input) => as(comment(input))), + update: update && ((input) => as(update(input))), + setState: setState && ((input) => as(setState(input))), + setReaction: setReaction && ((input) => as(setReaction(input))), + listTemplates: listTemplates && ((input) => as(listTemplates(input))), + listCandidates: listCandidates && ((input) => as(listCandidates(input))), + }; + return Object.fromEntries( + Object.entries(wrapped).filter(([, value]) => value !== undefined), + ) as unknown as IssueTrackerApi; +} diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index 4db5f263daba1..fffa0feb4014b 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -40,6 +40,7 @@ import type { PullRequestPreview, PullRequestUpdateMethod, PullRequestViewerPermissions, + PullRequestVisibility, SourceControlProviderKind, } from "@t3tools/contracts"; import { SourceControlProviderKind as SourceControlProviderKindSchema } from "@t3tools/contracts"; @@ -108,6 +109,8 @@ export interface ProviderChangeRequest { readonly labels: ReadonlyArray; readonly reviewDecision?: PullRequestReviewDecision | null | undefined; readonly checksState?: PullRequestChecksState | null | undefined; + /** Absent where the host has no private change requests or names no visibility. */ + readonly visibility?: PullRequestVisibility; } export interface ProviderChangeRequestSummary { diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index 4a6e93ab74f45..ccf23f59b2258 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -173,6 +173,18 @@ export class SourceControlProvider extends Context.Service< }) => Effect.Effect; /** True when `createChangeRequest` opens the change request as a draft when asked. */ readonly createsDraftChangeRequests?: boolean; + /** + * The private companion of the checkout's repository, made when it has none. The branch of + * a private change request is pushed to `url` and never to the repository itself, which + * everyone can read. Absent on a host without private change requests. + */ + readonly privateChangeRequestRemote?: (input: { + readonly cwd: string; + readonly context?: SourceControlProviderContext; + }) => Effect.Effect< + { readonly url: string; readonly repository: string }, + SourceControlProviderError + >; readonly listChangeRequests: (input: { readonly cwd: string; readonly context?: SourceControlProviderContext; @@ -202,6 +214,8 @@ export class SourceControlProvider extends Context.Service< readonly bodyFile: string; /** Honored only by a provider with `createsDraftChangeRequests`. */ readonly draft?: boolean; + /** Asked only of a provider with `privateChangeRequestRemote`, which holds the head. */ + readonly private?: boolean; }) => Effect.Effect; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; diff --git a/packages/source-control-core/src/server/discovery.ts b/packages/source-control-core/src/server/discovery.ts index 62ec94d7d67fe..0cc6654adf021 100644 --- a/packages/source-control-core/src/server/discovery.ts +++ b/packages/source-control-core/src/server/discovery.ts @@ -357,7 +357,8 @@ const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(fun return installHint; } const resolveExecutable = yield* SpawnExecutableResolution; - const path = resolveExecutable(executable, platform, yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const path = yield* Effect.promise(async () => resolveExecutable(executable, platform, env)); const architecture = yield* HostProcess.Architecture; return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`; }); diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts index 7b6e475f99152..1c088a58e8876 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts @@ -24,6 +24,7 @@ import { unknownRemoteProvider, } from "@t3tools/source-control-core/shared/definition"; import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts"; +import * as ForgejoChangeRequestTemplate from "./forgejoChangeRequestTemplate.ts"; const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError); @@ -303,7 +304,7 @@ interface UnfilteredPulls { export const make = Effect.gen(function* () { const cli = yield* ForgejoCli.ForgejoCli; const fs = yield* FileSystem.FileSystem; - const { process } = yield* SourceControlHost.SourceControlHost; + const { git, process } = yield* SourceControlHost.SourceControlHost; const request = >( input: ForgejoCli.ForgejoApiInput, schema: S, @@ -488,6 +489,11 @@ export const make = Effect.gen(function* () { }, (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)), ), + readChangeRequestTemplate: Effect.fn("ForgejoSourceControlProvider.readChangeRequestTemplate")( + function ({ cwd, treeish }) { + return ForgejoChangeRequestTemplate.detect(cwd, treeish, git.execute); + }, + ), getChangeRequest: Effect.fn("ForgejoSourceControlProvider.getChangeRequest")(function (input) { return getPull(input).pipe( Effect.map(toForgejoChangeRequest), diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts new file mode 100644 index 0000000000000..87f27e315406c --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts @@ -0,0 +1,100 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +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 ForgejoCli from "./ForgejoCli.ts"; +import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts"; + +const templateRepository = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { git } = yield* SourceControlHost.SourceControlHost; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-forgejo-pr-template-" }); + const runGit = (args: ReadonlyArray) => + git.execute({ operation: "forgejoChangeRequestTemplate.test.git", cwd, args }); + yield* runGit(["init", "--initial-branch=main", "--template="]); + yield* runGit(["config", "user.email", "test@example.com"]); + yield* runGit(["config", "user.name", "Test User"]); + const provider = yield* ForgejoSourceControlProvider.make; + + return { + runGit, + writeTemplate: (relativePath: string, body: string) => + Effect.gen(function* () { + const file = path.join(cwd, relativePath); + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, body); + }), + commit: Effect.gen(function* () { + yield* runGit(["add", "-A"]); + yield* runGit(["commit", "--allow-empty", "-m", "Set pull request template"]); + }), + read: (treeish: string) => + provider.readChangeRequestTemplate?.({ cwd, treeish }) ?? Effect.succeedNone, + }; +}); + +const testLayer = Layer.mergeAll( + TestSourceControlHost.layerWithRealGit(), + Layer.mock(ForgejoCli.ForgejoCli)({}), + NodeServices.layer, +); + +it.live("reads the Gitea template committed to the target branch", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.commit; + yield* repo.runGit(["branch", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Expected on the PR"); + yield* repo.commit; + yield* repo.runGit(["checkout", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Working tree only"); + + assert.deepStrictEqual(yield* repo.read("main"), Option.some("## Expected on the PR")); + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.none()); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("uses the first non-empty Markdown template in Forgejo's lookup order", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.writeTemplate("pull_request_template.md", " \n"); + yield* repo.writeTemplate(".forgejo/PULL_REQUEST_TEMPLATE.md", "## Forgejo"); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Gitea"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Forgejo")); + + yield* repo.writeTemplate("pull_request_template.md", "## Root"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Root")); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("rejects a committed template symlink and caps the fallback blob", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + const fallback = "x".repeat(9_000); + yield* repo.writeTemplate(".github/pull_request_template.md", fallback); + yield* repo.writeTemplate("link-target", "README.md"); + yield* repo.commit; + const linkBlob = yield* repo.runGit(["rev-parse", "HEAD:link-target"]); + yield* repo.runGit([ + "update-index", + "--add", + "--cacheinfo", + `120000,${linkBlob.stdout.trim()},pull_request_template.md`, + ]); + yield* repo.runGit(["commit", "-m", "Record a template symlink"]); + + assert.deepStrictEqual( + yield* repo.read("HEAD"), + Option.some(`${fallback.slice(0, 8_000)}\n\n[truncated]`), + ); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts new file mode 100644 index 0000000000000..0ffbc33956b7d --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts @@ -0,0 +1,63 @@ +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; + +// Forgejo's Markdown lookup order also preserves Gitea's root, .gitea, .github order. +const TEMPLATE_PATHS = ["", ".forgejo/", ".gitea/", ".github/", "docs/"].flatMap((directory) => [ + `${directory}PULL_REQUEST_TEMPLATE.md`, + `${directory}pull_request_template.md`, +]); +const TEMPLATE_MAX_BYTES = 8_000; +const TREE_LIST_MAX_BYTES = 100_000; +const TRUNCATION_MARKER = "[truncated]"; + +type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"]; + +export const detect = Effect.fn("forgejoChangeRequestTemplate.detect")( + function* (cwd: string, treeish: string, executeGit: ExecuteGit) { + const listing = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.listTemplates", + cwd, + args: ["ls-tree", "-z", "--full-tree", treeish, "--", ...TEMPLATE_PATHS], + maxOutputBytes: TREE_LIST_MAX_BYTES, + appendTruncationMarker: true, + }); + if (listing.stdoutTruncated) { + return Option.none(); + } + + // Read only regular blobs from the target tree, including when the worktree has a symlink. + const objectsByPath = new Map(); + for (const record of listing.stdout.split("\0")) { + const entry = /^100(?:644|755) blob ([0-9a-f]{40,64})\t(.+)$/.exec(record); + if (entry?.[1] && entry[2]) { + objectsByPath.set(entry[2], entry[1]); + } + } + + for (const path of TEMPLATE_PATHS) { + const objectId = objectsByPath.get(path); + if (!objectId) { + continue; + } + const blob = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.readTemplate", + cwd, + args: ["cat-file", "blob", objectId], + maxOutputBytes: TEMPLATE_MAX_BYTES, + appendTruncationMarker: true, + }); + const template = blob.stdout.trim(); + if (template.length > 0) { + return Option.some( + blob.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER) + ? `${template}\n\n${TRUNCATION_MARKER}` + : template, + ); + } + } + return Option.none(); + }, + Effect.orElseSucceed(() => Option.none()), +); diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts index c04145758f7b1..c944207d639ab 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts @@ -656,6 +656,15 @@ Redact secrets before uploading.`); ["referenced", "acme/web#50"], ["closed", null], ]); + // A cross-reference keeps what a surface needs to open its source, not only a label. + expect(issue.events.find((event) => event.kind === "referenced")).toMatchObject({ + reference: { + repository: "acme/web", + number: 50, + kind: "pull-request", + url: "https://github.com/acme/web/pull/50", + }, + }); }), ); }); diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index c3cc15097dfd5..9d155cab2b794 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -3949,13 +3949,25 @@ layer("GitHubPullRequestApi.layer", (it) => { name: "build", status: "COMPLETED", conclusion: "SUCCESS", - checkSuite: { workflowRun: { workflow: { name: "linux" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_linux", name: "linux" }, + }, + }, }), checkRun({ name: "build", status: "COMPLETED", conclusion: "FAILURE", - checkSuite: { workflowRun: { workflow: { name: "windows" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_windows", name: "windows" }, + }, + }, }), ], pageInfo: { hasNextPage: false, endCursor: null }, diff --git a/packages/source-control-github/src/server/gitHubIssueJson.ts b/packages/source-control-github/src/server/gitHubIssueJson.ts index e46ad7ec9e515..59e9b9efd118e 100644 --- a/packages/source-control-github/src/server/gitHubIssueJson.ts +++ b/packages/source-control-github/src/server/gitHubIssueJson.ts @@ -5,7 +5,6 @@ import type { IssueActor, IssueComment, IssueEvent, - IssueEventKind, IssueLabel, IssueLinkedPullRequest, IssueState, @@ -137,7 +136,7 @@ function toLinkedPullRequest( /** The change GitHub recorded, or null for a kind this page has no vocabulary for. */ function toEventFields( raw: TimelineItem, -): { readonly kind: IssueEventKind; readonly detail: string | null } | null { +): Pick | null { switch (raw.__typename) { case "ClosedEvent": return { kind: "closed", detail: null }; @@ -164,15 +163,28 @@ function toEventFields( case "RenamedTitleEvent": return { kind: "renamed", detail: trimmed(raw.currentTitle) }; case "CrossReferencedEvent": { - const repository = trimmed( - raw.source != null && "repository" in raw.source - ? raw.source.repository.nameWithOwner - : null, - ); - const number = raw.source != null && "number" in raw.source ? raw.source.number : 0; + const source = + raw.source.__typename === "PullRequest" || raw.source.__typename === "Issue" + ? raw.source + : null; + const repository = trimmed(source?.repository.nameWithOwner); + const url = trimmed(source?.url); + if (source === null || repository === null || source.number <= 0) { + return { kind: "referenced", detail: null }; + } return { kind: "referenced", - detail: repository === null || number <= 0 ? null : `${repository}#${number}`, + detail: `${repository}#${source.number}`, + ...(url === null + ? {} + : { + reference: { + repository, + number: source.number, + kind: source.__typename === "PullRequest" ? "pull-request" : "issue", + url, + }, + }), }; } default: diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index 37db822d34386..e049943a3978f 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -359,10 +359,18 @@ describe("pull request detail decoding", () => { checkSuite: { workflowRun: null }, ...fields, }; - const inWorkflow = ({ workflowName, ...fields }: Record) => + const inWorkflow = ({ + workflowName, + workflowId = `W_kwDORLtfbc4${String(workflowName)}`, + event = "pull_request", + runNumber = 95380, + ...fields + }: Record) => check({ ...fields, - checkSuite: { workflowRun: { workflow: { name: workflowName } } }, + checkSuite: { + workflowRun: { event, runNumber, workflow: { id: workflowId, name: workflowName } }, + }, }); const coreJson = ( @@ -655,6 +663,139 @@ describe("pull request detail decoding", () => { } }); + it("drops a cancelled check whose workflow run was superseded by a newer run on the head", () => { + const superseded = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + status: "COMPLETED", + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:00:05Z", + }; + const replacement = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95380, + status: "COMPLETED", + conclusion: "SUCCESS", + startedAt: "2026-10-30T10:00:10Z", + completedAt: "2026-10-30T10:05:00Z", + }; + const rollup = [ + inWorkflow({ ...superseded, name: "check", conclusion: "CANCELLED" }), + inWorkflow({ + ...superseded, + name: "web browser tests (runner ${{ matrix.slice }} of 6)", + conclusion: "CANCELLED", + }), + inWorkflow({ ...replacement, name: "check" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 1 of 6)" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 2 of 6)" }), + ]; + const detail = detailOf(rollup); + + expect([detail.checks.map((check) => [check.name, check.status]), detail.checksState]).toEqual([ + [ + ["check", "success"], + ["web browser tests (runner 1 of 6)", "success"], + ["web browser tests (runner 2 of 6)", "success"], + ], + "passing", + ]); + }); + + it("keeps a cancelled check when the newer run is another workflow with the same name", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + conclusion: "CANCELLED", + }), + inWorkflow({ + name: "lint", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4ToKTh", + runNumber: 95380, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test", + "cancelled", + ]); + expect(detail.checksState).toBe("failing"); + }); + + it("drops a required cancelled check once a newer run reports it, whenever it finished", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 41, + conclusion: "CANCELLED", + isRequired: true, + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:09:00Z", + }), + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 42, + conclusion: "SUCCESS", + isRequired: true, + startedAt: "2026-10-30T10:01:00Z", + completedAt: "2026-10-30T10:05:00Z", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toEqual([["test", "success"]]); + expect(detail.checksState).toBe("passing"); + }); + + it.each([ + ["a push", "push", "push", "CANCELLED", false, "cancelled"], + ["another event", "pull_request", "pull_request_target", "CANCELLED", false, "cancelled"], + ["a pull request run", "pull_request", "pull_request", "FAILURE", false, "failure"], + [ + "a pull request run, if required", + "pull_request", + "pull_request", + "CANCELLED", + true, + "cancelled", + ], + ])( + "keeps an older run's check when the newer run is %s", + (_label, olderEvent, newerEvent, conclusion, isRequired, status) => { + const detail = detailOf([ + inWorkflow({ + name: "test (packages/shared)", + workflowName: "CI", + event: olderEvent, + runNumber: 41, + conclusion, + isRequired, + }), + inWorkflow({ + name: "test (apps/server)", + workflowName: "CI", + event: newerEvent, + runNumber: 42, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test (packages/shared)", + status, + ]); + expect(detail.checksState).toBe("failing"); + }, + ); + it("merges reviews with comments in time order and keeps a bodyless approval", () => { const detail = expectSuccess(activity(JSON.parse(detailJson) as Record)); expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 7fbe86839d495..9eed567a6a4da 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -131,6 +131,13 @@ interface LatestReviewFields { readonly isMinimized?: boolean | undefined; } +/** Run numbers count up per workflow file, whatever its name; database ids exceed int32. */ +interface WorkflowRunFields { + readonly event: string; + readonly runNumber: number; + readonly workflow: { readonly id: string }; +} + /** Check runs use status/conclusion; commit statuses use a single state. */ interface CheckFields { readonly name?: string | null | undefined; @@ -143,6 +150,8 @@ interface CheckFields { readonly targetUrl?: string | null | undefined; /** Empty for app-owned runs; absent for commit statuses. */ readonly workflowName?: string | null | undefined; + /** Absent for commit statuses and app-owned runs. */ + readonly workflowRun?: WorkflowRunFields | null | undefined; readonly startedAt?: string | null | undefined; readonly completedAt?: string | null | undefined; /** Branch protection requires this check; asked for on github.com only. */ @@ -617,16 +626,42 @@ function isNamelessCheck(raw: CheckFields): boolean { return trimmed(raw.name) === null && trimmed(raw.context) === null; } -/** Unfinished runs outrank finished runs of the same check across push/PR workflows. */ +const PULL_REQUEST_EVENTS = new Set(["pull_request", "pull_request_target"]); + +/** + * Unfinished runs outrank finished runs of the same check across push/PR workflows. A newer pull + * request run of a workflow supersedes the older one's cancelled checks, whose names can differ + * (an unexpanded matrix). Other events can run one commit in different scopes (a branch and a + * tag, dispatch inputs), so their runs replace nothing. + */ function toCheckEntries(raw: ReadonlyArray | null | undefined): ReadonlyArray<{ readonly check: PullRequestCheck; readonly workflowName: string | null; readonly at: string | null; }> { + const lineageOf = (run: WorkflowRunFields) => `${run.workflow.id} ${run.event}`; + const newestRunNumber = new Map(); + const note = (key: string, runNumber: number) => { + if (runNumber > (newestRunNumber.get(key) ?? Number.NEGATIVE_INFINITY)) { + newestRunNumber.set(key, runNumber); + } + }; + for (const check of raw ?? []) { + const run = check.workflowRun; + if (run == null || !PULL_REQUEST_EVENTS.has(run.event)) continue; + note(lineageOf(run), run.runNumber); + note(`${lineageOf(run)} ${trimmed(check.name) ?? ""}`, run.runNumber); + } return (raw ?? []).flatMap((check) => { const name = trimmed(check.name) ?? trimmed(check.context); if (name === null) return []; const status = toCheckStatus(check); + const run = check.workflowRun; + if (status === "cancelled" && run != null) { + // Branch protection names required checks, so only a newer same-name check replaces one. + const replacedBy = check.isRequired === true ? `${lineageOf(run)} ${name}` : lineageOf(run); + if (run.runNumber < (newestRunNumber.get(replacedBy) ?? run.runNumber)) return []; + } return [ { check: { @@ -1246,7 +1281,11 @@ export type GitHubCheckContext = CheckFields; function toCheckContexts(nodes: ReadonlyArray): ReadonlyArray { return nodes.map((check) => check.__typename === "CheckRun" - ? { ...check, workflowName: check.checkSuite.workflowRun?.workflow.name ?? null } + ? { + ...check, + workflowName: check.checkSuite.workflowRun?.workflow.name ?? null, + workflowRun: check.checkSuite.workflowRun, + } : check, ); } diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index 18c8cee3536a2..d8b28a08c7078 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -231,6 +231,7 @@ query IssueDetail($owner: String!, $name: String!, $number: Int!) { } ... on Issue { number + url repository { nameWithOwner } diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index 9d059396d26a0..fb393ef5ca4c6 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -487,6 +487,8 @@ export const SourceIssue = Schema.Struct({ __typename: Schema.Literal("Issue"), /** Identifies the issue number. */ number: Shared.Int, + /** The HTTP URL for this issue */ + url: Shared.URI, /** The repository associated with this node. */ repository: NodesRepositoryRepository }) @@ -584,7 +586,7 @@ export const IssueDetail = GraphQL.query("IssueDetail", { ], selections: [ { name: "viewer", body: ["{login}"] }, - { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number repository{nameWithOwner}}}}}}}}"] } + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number url repository{nameWithOwner}}}}}}}}"] } ], fragments: [ { name: "IssueRow", body: ["on Issue{number title url state stateReason createdAt updatedAt closedAt author{__typename login avatarUrl...on User{name}}}"] }, diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql index 2799b67525a27..0b8c5350c1408 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql +++ b/packages/source-control-github/src/server/pullRequestReads.graphql @@ -42,7 +42,10 @@ fragment CheckContext on StatusCheckRollupContext { isRequired(pullRequestNumber: $number) @include(if: $required) checkSuite { workflowRun { + event + runNumber workflow { + id name } } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts index ab5e211a4dec2..d26912d6aee7b 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts @@ -23,6 +23,8 @@ export interface StatusContext extends Schema.Struct.Type {} /** A workflow run. */ export const WorkflowRun = Schema.Struct({ + /** The event that triggered the workflow run */ + event: Schema.String, + /** A number that uniquely identifies this workflow run in its parent workflow. */ + runNumber: Shared.Int, /** The workflow executed in this workflow run. */ workflow: Workflow }) @@ -565,7 +571,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", { { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt mergeCommit{oid}mergedBy{__typename login avatarUrl...on User{name}}closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}mergeQueueRemovals:timelineItems(last:1 itemTypes:[REMOVED_FROM_MERGE_QUEUE_EVENT])@include(if:$", "mergeQueue", "){nodes{__typename...on RemovedFromMergeQueueEvent{id createdAt reason}}}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { @@ -617,7 +623,7 @@ export const PullRequestCheckContexts = GraphQL.query("PullRequestCheckContexts" { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){headRefOid commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100 after:$", "after", "){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index b528c1ced5a8a..04a633bba7096 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -21,6 +21,8 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo import { decodeGitLabMergeRequestJson, decodeGitLabMergeRequestListJson, + type NormalizedGitLabMergeRequestRecord, + withSourceProjectPath, } from "./gitLabMergeRequests.ts"; import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; @@ -377,6 +379,10 @@ const decodeGitLabMergeRequestProject = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })), ); +const decodeGitLabProjectPath = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ path_with_namespace: TrimmedNonEmptyString })), +); + const RawGitLabNamespaceSchema = Schema.Struct({ id: Schema.Number, }); @@ -559,6 +565,35 @@ export const make = Effect.gen(function* () { ), ); + // glab's MR JSON names a fork's source project only by `source_project_id`. + const resolveSourceProjectPaths = Effect.fn("GitLabCli.resolveSourceProjectPaths")(function* ( + cwd: string, + records: ReadonlyArray, + paths: Map, + ) { + const ids = new Set(); + for (const record of records) { + const id = record.unresolvedSourceProjectId; + if (id !== undefined && !paths.has(id)) ids.add(id); + } + yield* Effect.forEach( + ids, + (id) => + execute({ cwd, args: ["api", `projects/${id}`] }).pipe( + Effect.flatMap((result) => decodeGitLabProjectPath(result.stdout.trim())), + Effect.map((project) => project.path_with_namespace), + Effect.orElseSucceed(() => null), + Effect.map((path) => void paths.set(id, path)), + ), + { concurrency: 8, discard: true }, + ); + return records.map((record) => + record.unresolvedSourceProjectId === undefined + ? record + : withSourceProjectPath(record, paths.get(record.unresolvedSourceProjectId) ?? null), + ); + }); + return GitLabCli.of({ execute, listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) { @@ -566,6 +601,7 @@ export const make = Effect.gen(function* () { let pageSize = limit; let page = 1; const items: GitLabMergeRequestSummary[] = []; + const sourceProjectPaths = input.source?.owner ? new Map() : null; while (items.length < limit) { const result = yield* execute({ cwd: input.cwd, @@ -600,7 +636,11 @@ export const make = Effect.gen(function* () { cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated", }); } - items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt)); + // Only a fork head can match a fork's merge request, so other lookups skip the API calls. + const records = sourceProjectPaths + ? yield* resolveSourceProjectPaths(input.cwd, decoded.success, sourceProjectPaths) + : decoded.success; + items.push(...records.map(toSummaryWithOptionalUpdatedAt)); // Count raw entries: the decoder drops invalid ones, which would end paging early. const entries = decodeJsonArray(raw); if ( @@ -635,7 +675,9 @@ export const make = Effect.gen(function* () { ); } - return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success)); + return resolveSourceProjectPaths(input.cwd, [decoded.success], new Map()).pipe( + Effect.map(([record]) => toSummaryWithOptionalUpdatedAt(record!)), + ); }), ), ), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts index 7c794de8b456e..d3bd6e01366bd 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts @@ -59,6 +59,13 @@ function answer(path: string): string { created_at: "2026-07-03T00:00:00Z", system: true, }, + { + id: 10, + body: "mentioned in merge request api!51", + author: { username: "theo" }, + created_at: "2026-07-04T00:00:00Z", + system: true, + }, ]); } if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) { @@ -206,7 +213,14 @@ describe("GitLabIssueTracker", () => { expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([ ["labeled", "bug"], ["closed", null], + ["referenced", "merge request api!51"], ]); + expect(issue.events.at(-1)?.reference).toEqual({ + repository: "acme/api", + number: 51, + kind: "pull-request", + url: "https://gitlab.com/acme/api/-/merge_requests/51", + }); // A closing merge request is not repeated as a related one. expect( issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts index f8b1f80c18b0e..4f4aeb3135034 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts @@ -25,6 +25,7 @@ import { decodeIssueDetailListJson, decodeIssueListJson, decodeIssueNotesJson, + withMentionReference, decodeLabelEventsJson, decodeLinkedMergeRequestsJson, decodeProjectLabelsJson, @@ -576,9 +577,12 @@ export const make: Effect.Effect = reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [], })), commentsCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null), - events: [...systemEvents, ...labelEvents].sort((left, right) => - left.createdAt.localeCompare(right.createdAt), - ), + events: [ + ...systemEvents.map((event) => + withMentionReference(event, issue.url, input.scope), + ), + ...labelEvents, + ].sort((left, right) => left.createdAt.localeCompare(right.createdAt)), // A merge request that closes the issue outranks its sighting as a mere mention. linkedPullRequests: [ ...closing, diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts index 7038e6a82d630..abd2f7b82f218 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts @@ -106,6 +106,97 @@ it.effect("lists a nested-group fork's merge requests by source branch and names }), ); +// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its +// source project only by `source_project_id`, never by a `source_project` path. +it.effect("names a fork merge request's source project from real glab list output", () => + Effect.gen(function* () { + const branch = "feature/fork-work"; + const mergeRequest = (iid: number, sourceProjectId: number) => ({ + id: 9000 + iid, + iid, + project_id: 100, + title: `Work ${iid}`, + state: "opened", + target_branch: "main", + source_branch: branch, + source_project_id: sourceProjectId, + target_project_id: 100, + draft: false, + sha: "0123456789abcdef0123456789abcdef01234567", + updated_at: "2026-04-07T15:00:00.000Z", + references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` }, + web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`, + }); + const output = JSON.stringify([ + mergeRequest(1, 101), + mergeRequest(2, 101), + mergeRequest(3, 100), + mergeRequest(4, 102), + ]); + const apiCalls: ReadonlyArray[] = []; + const provider = yield* GitLabSourceControlProvider.make.pipe( + Effect.provide( + GitLabCli.layer.pipe( + Layer.provideMerge( + TestSourceControlHost.layer({ + process: { + run: (input) => + Effect.sync(() => { + if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output); + apiCalls.push(input.args); + return TestSourceControlHost.processOutput( + input.args[1] === "projects/101" + ? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" }) + : "not json", + ); + }), + }, + }), + ), + Layer.provide(FileSystem.layerNoop({})), + ), + ), + ); + + const upstreamHead = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: branch, + state: "open", + limit: 20, + }); + expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toEqual([]); + + const changeRequests = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: `alice:${branch}`, + state: "open", + limit: 20, + }); + // GitManager drops a cross-repository MR whose head project is unnamed. + expect(changeRequests).toMatchObject([ + { + number: 1, + isCrossRepository: true, + headRepositoryNameWithOwner: "alice/upstream", + headRepositoryOwnerLogin: "alice", + }, + { number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" }, + { number: 3, isCrossRepository: false }, + { number: 4, isCrossRepository: true }, + ]); + expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toHaveLength(2); + expect(apiCalls).toEqual( + expect.arrayContaining([ + ["api", "projects/101"], + ["api", "projects/102"], + ]), + ); + }), +); + const withRepository = ( test: (input: { readonly git: (...args: string[]) => Effect.Effect; diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index 8e5077044c6b3..c5a2d56037172 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -210,6 +210,13 @@ it.effect( headSelectors: ["octocat:feature", "feature"], state: "open", }), + { headSelectors: ["octocat:feature"], limit: 100 }, + ); + assert.deepStrictEqual( + provider.headBranchProbe?.({ + headSelectors: ["feature", "octocat:feature"], + state: "open", + }), { headSelectors: ["feature"], limit: 100 }, ); }), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts index a7d5b71ca47d3..2a2d4ac3e199c 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts @@ -211,11 +211,17 @@ export const make = Effect.gen(function* () { return SourceControlProvider.SourceControlProvider.of({ kind: SourceControlProviderKind.make("gitlab"), - // GitLab lists fork merge requests by source branch with no owner filter, so read a full page. - headBranchProbe: ({ headSelectors }) => ({ - headSelectors: headSelectors.filter((selector) => !selector.includes(":")), - limit: 100, - }), + // GitLab lists fork merge requests by source branch with no owner filter, so read a full page + // once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork + // head, which tells the list to name fork source projects. + headBranchProbe: ({ headSelectors }) => { + const byBranch = new Map(); + for (const selector of headSelectors) { + const branch = SourceControlProvider.sourceBranch({ headSelector: selector }); + if (!byBranch.has(branch)) byBranch.set(branch, selector); + } + return { headSelectors: [...byBranch.values()], limit: 100 }; + }, readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")( function ({ cwd, treeish }) { return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute); diff --git a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts index 5458ed4f859ef..7a52667a4a425 100644 --- a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts @@ -250,6 +250,41 @@ function toSystemEvent( return null; } +// The path class excludes the sigil, so matching is linear on any input. +const MENTION = /^(?:merge request ([\w.\-/]*)!|issue ([\w.\-/]*)#)([1-9]\d*)$/; + +/** + * Where a "mentioned in merge request !12" note came from, addressed from the issue's own web URL + * so a self-managed host under a subpath resolves. A commit, epic or snippet mention gets none. + */ +export function withMentionReference( + event: IssueEvent, + issueUrl: string, + scope: string, +): IssueEvent { + const match = event.kind === "referenced" ? MENTION.exec(event.detail ?? "") : null; + const projectUrl = issueUrl.split("/-/")[0]!; + if (match === null || !projectUrl.toLowerCase().endsWith(`/${scope.toLowerCase()}`)) { + return event; + } + const [, mergeRequestPath, issuePath, digits] = match; + const isMergeRequest = mergeRequestPath !== undefined; + const path = mergeRequestPath ?? issuePath ?? ""; + // A project in the same namespace is named by its path alone. + const repository = + path === "" ? scope : path.includes("/") ? path : `${scope.replace(/[^/]*$/, "")}${path}`; + const base = projectUrl.slice(0, projectUrl.length - scope.length); + return { + ...event, + reference: { + repository, + number: Number(digits), + kind: isMergeRequest ? "pull-request" : "issue", + url: `${base}${repository}/-/${isMergeRequest ? "merge_requests" : "issues"}/${digits}`, + }, + }; +} + interface GitLabIssueNotes { readonly comments: ReadonlyArray; readonly events: ReadonlyArray; diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts index ef4438f5ff3ee..a40abd786cf85 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts @@ -23,6 +23,8 @@ export interface NormalizedGitLabMergeRequestRecord { readonly isCrossRepository?: boolean; readonly headRepositoryNameWithOwner?: string | null; readonly headRepositoryOwnerLogin?: string | null; + /** Set when a cross-repository MR names its source project only by id. */ + readonly unresolvedSourceProjectId?: number; } const GitLabProjectReferenceSchema = Schema.Struct({ @@ -122,6 +124,24 @@ function normalizeGitLabMergeRequestRecord( ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}), ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + ...(isCrossRepository === true && + !sourceProjectPath && + typeof raw.source_project_id === "number" + ? { unresolvedSourceProjectId: raw.source_project_id } + : {}), + }; +} + +export function withSourceProjectPath( + record: NormalizedGitLabMergeRequestRecord, + sourceProjectPath: string | null, +): NormalizedGitLabMergeRequestRecord { + const { unresolvedSourceProjectId: _, ...resolved } = record; + const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath); + return { + ...resolved, + ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), }; } diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts new file mode 100644 index 0000000000000..838309b037617 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts @@ -0,0 +1,138 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts"; + +const HOST = "source.tanstack.com"; + +/** + * Shaped like `GET /pulls/{n}` of a private pull request: its head is `owner:branch` in the + * companion repository, and Source has stored no file or line counts for it. + */ +const PRIVATE_PULL = { + number: 42, + title: "Fix the thing", + state: "open", + visibility: "private", + draft: false, + author: "bob", + head: "acme:fix/thing", + createdAt: 1_000, + body: null, + base: "main", + headRepo: "acme/web.private", + headSha: "c".repeat(40), + baseSha: "b".repeat(40), + mergeCommitSha: null, + mergedAt: null, + mergedBy: null, + mergeable: null, + changedFiles: null, + changedLines: null, +}; + +const FILES = { + baseSha: "b".repeat(40), + headSha: "c".repeat(40), + mergeBaseSha: "b".repeat(40), + available: true, + truncated: false, + files: [ + { path: "a.ts", status: "modified", additions: 3, deletions: 1 }, + { path: "b.ts", status: "added", additions: 4, deletions: 0 }, + ], +}; + +const RESPONSES: Record = { + "/repos/acme/web/pulls/42": PRIVATE_PULL, + "/repos/acme/web/pulls/42/files": FILES, + "/repos/acme/web/pulls/42/checks": { checks: [], upToDate: null, mayMerge: true }, + "/repos/acme/web/pulls/42/stack": { members: [] }, + [`/repos/acme/web/check-runs?sha=${"c".repeat(40)}`]: [], + "/repos/acme/web/ci/runs?pull=42&limit=30": { items: [], next: null }, + "/repos/acme/web/issues/42": { + timeline: [ + { id: 1, comment: "Looks good", author: "alice", at: 2_000 }, + { event: "head_updated", actor: "bob", at: 3_000 }, + ], + next: null, + }, + "/repos/acme/web/pulls/42/comments": [], + "/repos/acme/web/pulls/42/commits": { + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: true, + commits: [], + }, + "/user": { username: "alice" }, +}; + +const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => + input.path in RESPONSES + ? Effect.succeed(JSON.stringify(RESPONSES[input.path])) + : Effect.die(`unexpected ${input.path}`), + response: () => Effect.die("unexpected response read"), +}); + +const provider = TanStackSourcePullRequestProvider.make.pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provideService( + Credentials.TanStackSourceCredentials, + Credentials.TanStackSourceCredentials.of({ + get: () => Effect.die("unexpected credential read"), + invalidate: () => Effect.void, + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected http request")), + ), +); + +describe("TanStackSourcePullRequestProvider.getChangeRequest", () => { + // A client without this host's definition percent-encodes the owner's `@`; stored links + // keep the web's own spelling. + it.effect.each(["acme/web", "@acme/web", "%40acme/web"])( + "reads a private pull request of %s", + (repository) => + Effect.gen(function* () { + const detail = yield* (yield* provider).getChangeRequest({ + host: HOST, + repository, + number: 42, + cwd: "/repo", + }); + assert.strictEqual(detail.url, `https://${HOST}/@acme/web/pull/42`); + assert.strictEqual(detail.visibility, "private"); + assert.strictEqual(detail.headBranch, "fix/thing"); + assert.strictEqual(detail.headRepositoryNameWithOwner, "acme/web.private"); + // Source stores no counts for it, so they come from its files. + assert.deepStrictEqual( + [detail.changedFiles, detail.additions, detail.deletions], + [2, 7, 1], + ); + }), + ); +}); + +describe("TanStackSourcePullRequestProvider.getChangeRequestActivity", () => { + it.effect("reads the comments of a timeline that also holds events", () => + Effect.gen(function* () { + const activity = yield* (yield* provider).getChangeRequestActivity({ + host: HOST, + repository: "acme/web", + number: 42, + cwd: "/repo", + }); + assert.deepStrictEqual( + activity.comments.map((comment) => comment.body), + ["Looks good"], + ); + }), + ); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts index 509e03e1f41f4..0529ce6df17c7 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -35,6 +35,8 @@ const PULL = { function checkout(options: { readonly recordedOwner: string | null; readonly isAncestor: boolean; + readonly pull?: Partial; + readonly force?: boolean; }) { const git: Array = []; const config = new Map( @@ -43,14 +45,28 @@ function checkout(options: { const api = TanStackSourceApi.TanStackSourceApi.of({ request: (input) => input.path === "/repos/acme/web/pulls/42" - ? Effect.succeed(JSON.stringify(PULL)) + ? Effect.succeed(JSON.stringify({ ...PULL, ...options.pull })) : Effect.die(`unexpected ${input.path}`), response: () => Effect.die("unexpected response read"), }); const host = TestSourceControlHost.layer({ git: { resolvePrimaryRemoteName: () => Effect.succeed("origin"), - ensureRemote: () => Effect.succeed("origin"), + ensureRemote: (input) => + Effect.sync(() => { + git.push(`remote ${input.preferredName} ${input.url}`); + return input.url === REMOTE ? "origin" : input.preferredName; + }), + fetchRemoteBranch: (input) => + Effect.sync( + () => + void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`), + ), + fetchRemoteTrackingBranch: () => Effect.void, + setBranchUpstream: (input) => + Effect.sync( + () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`), + ), readConfigValue: (_cwd, key) => Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)), writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)), @@ -86,7 +102,13 @@ function checkout(options: { }, }); const run = TanStackSourceSourceControlProvider.make.pipe( - Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })), + Effect.flatMap((provider) => + provider.checkoutChangeRequest({ + cwd: "/repo", + reference: "42", + ...(options.force === undefined ? {} : { force: options.force }), + }), + ), Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))), ); @@ -129,4 +151,83 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { assert.isFalse(git.some((command) => command.startsWith("checkout"))); }); }); + + // Source publishes no `refs/pull//head` for a private pull request, on either repository. + it.effect("takes a private pull request's branch from the companion repository", () => { + const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" }; + const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull }); + const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true }); + return Effect.gen(function* () { + yield* forced.run; + assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --"); + yield* run; + assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme"); + assert.deepStrictEqual(git, [ + `remote source ${REMOTE}`, + "remote acme https://source.tanstack.com/@acme/web.private.git", + "fetch acme fix-thing:fix-thing", + "upstream fix-thing acme/fix-thing", + "switch fix-thing", + ]); + }); + }); +}); + +describe("TanStackSourceSourceControlProvider private pull requests", () => { + it.effect("asks Source for the companion and opens the pull request as private", () => { + const requests: Array<{ method: string; path: string; body: unknown }> = []; + const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => { + requests.push({ method: input.method ?? "GET", path: input.path, body: input.body }); + return Effect.succeed( + JSON.stringify({ + owner: "acme", + name: "web.private", + defaultBranch: null, + cloneUrl: "https://source.tanstack.com/@acme/web.private.git", + }), + ); + }, + response: () => Effect.die("unexpected response read"), + }); + const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") }); + return Effect.gen(function* () { + const provider = yield* TanStackSourceSourceControlProvider.make; + const companion = provider.privateChangeRequestRemote; + assert.isDefined(companion); + assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), { + url: "https://source.tanstack.com/@acme/web.private.git", + repository: "acme/web.private", + }); + yield* provider.createChangeRequest({ + cwd: "/repo", + baseRefName: "main", + headSelector: "sec/fix", + title: "Fix", + bodyFile: "/tmp/body.md", + private: true, + }); + assert.deepStrictEqual(requests, [ + { method: "POST", path: "/repos/acme/web/private-remote", body: undefined }, + { + method: "POST", + path: "/repos/acme/web/pulls", + body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true }, + }, + ]); + }).pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provide( + Layer.merge( + TestSourceControlHost.layer({ + git: { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + readConfigValue: () => Effect.succeed(REMOTE), + }, + }), + files, + ), + ), + ); + }); }); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index a1abb376b472d..f194848611361 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -395,6 +395,18 @@ export const make = Effect.gen(function* () { }, ), createsDraftChangeRequests: true, + privateChangeRequestRemote: Effect.fn( + "TanStackSourceSourceControlProvider.privateChangeRequestRemote", + )(function* (input) { + const target = yield* resolveTarget("privateChangeRequestRemote", input); + const companion = yield* read( + "privateChangeRequestRemote", + input.cwd, + { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` }, + Repository, + ); + return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` }; + }), createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")( function* (input) { const target = yield* resolveTarget("createChangeRequest", { @@ -437,6 +449,7 @@ export const make = Effect.gen(function* () { base: input.target?.refName ?? input.baseRefName, ...(body.trim().length === 0 ? {} : { body }), ...(input.draft === true ? { draft: true } : {}), + ...(input.private === true ? { private: true } : {}), }, }) .pipe( @@ -494,7 +507,8 @@ export const make = Effect.gen(function* () { return repository.defaultBranch; }, ), - // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too. + // A pull request's head is published as `refs/pull//head`, forks and GitHub sync too. A + // private one has no such ref: its branch is read from the companion repository. checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")( function* (input) { const pull = yield* getPull(input); @@ -519,9 +533,26 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); - if (!pull.isCrossRepository) { + const companion = + pullRepository !== null && + pull.headRepositoryNameWithOwner?.toLowerCase() === + `${pullRepository}.private`.toLowerCase() + ? pull.headRepositoryNameWithOwner + : null; + if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; - const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch }; + const remoteBranch = { + cwd: input.cwd, + remoteName: + companion === null + ? remoteName + : yield* git.ensureRemote({ + cwd: input.cwd, + preferredName: companion.split("/")[0] ?? "private", + url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`, + }), + remoteBranch: localBranch, + }; if (input.force !== true && !branches.includes(localBranch)) yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); else yield* git.fetchRemoteTrackingBranch(remoteBranch); @@ -535,11 +566,18 @@ export const make = Effect.gen(function* () { "--no-track", "-B", localBranch, - `refs/remotes/${remoteName}/${localBranch}`, + `refs/remotes/${remoteBranch.remoteName}/${localBranch}`, "--", ], }); yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); + // Whatever push defaults say, this branch must not be published to the public remote. + if (companion !== null) + yield* git.writeConfigValue({ + cwd: input.cwd, + key: `branch.${localBranch}.pushRemote`, + value: remoteBranch.remoteName, + }); yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); return; } diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts new file mode 100644 index 0000000000000..ac43a46ccdcad --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { tanStackSourceRepositoryPath } from "./tanStackSourceHosts.ts"; + +describe("tanStackSourceRepositoryPath", () => { + it.each([ + ["acme/web", "acme/web"], + ["@acme/web", "acme/web"], + // Clients without this host's definition percent-encode the owner's `@`. + ["%40acme/web", "acme/web"], + ["/@acme/web.git/", "acme/web"], + ["acme/web.private", "acme/web.private"], + ["acme", null], + ["acme/web/extra", null], + ["acme/..", null], + ])("reads %s as %s", (path, repository) => { + expect(tanStackSourceRepositoryPath(path)).toBe(repository); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts index 22923264629bf..dfa6d4e9031a0 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts @@ -1,4 +1,4 @@ -import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts"; +import { TANSTACK_SOURCE_HOST, withoutOwnerMark } from "../shared/definition.ts"; export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const; export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number]; @@ -10,14 +10,14 @@ export function tanStackSourceHost(host: string): TanStackSourceHost | null { const SEGMENT = /^[A-Za-z0-9_.-]+$/u; -/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */ +/** `owner/name` from the API spelling or either web spelling of the owner, `.git` dropped. */ export function tanStackSourceRepositoryPath(path: string): string | null { - const [owner, name, ...rest] = path - .trim() - .replace(/^\/+|\/+$/gu, "") - .replace(/\.git$/u, "") - .replace(/^@/u, "") - .split("/"); + const [owner, name, ...rest] = withoutOwnerMark( + path + .trim() + .replace(/^\/+|\/+$/gu, "") + .replace(/\.git$/u, ""), + ).split("/"); return rest.length === 0 && owner !== undefined && name !== undefined && diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts index 4d698fb881dfb..24c93e6aac83d 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts @@ -146,6 +146,7 @@ describe("toActivity", () => { ["4", "review-comment", null], ]); expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`); + expect(Json.pullUrl(HOST, "%40TanStack/ai", 9)).toBe(`https://${HOST}/@TanStack/ai/pull/9`); expect(activity.reviewThreads).toMatchObject([ { id: "4", path: "a.ts", line: 2, side: "left", isResolved: true }, ]); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts index acf3c4158f95c..51537627ca3e7 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts @@ -16,6 +16,8 @@ import type { import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; +import { withoutOwnerMark } from "../shared/definition.ts"; + /** Source sends times as epoch milliseconds. */ const EpochMillis = Schema.Finite; const Login = Schema.String; @@ -29,6 +31,7 @@ export const SourcePull = Schema.Struct({ labels: Schema.optional(Schema.Array(Schema.String)), head: Schema.String, createdAt: EpochMillis, + visibility: Schema.optional(Schema.String), }); export type SourcePull = typeof SourcePull.Type; @@ -135,7 +138,8 @@ const TimelineEntry = Schema.Struct({ type TimelineEntry = typeof TimelineEntry.Type; export const SourceTimeline = Schema.Struct({ - timeline: Schema.Array(TimelineEntry), + // Events such as `head_updated` sit between the comments and carry no id. + timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])), next: Schema.NullOr(Schema.String), }); @@ -239,10 +243,20 @@ export const SourceUser = Schema.Struct({ username: Schema.String }); export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis)); export const pullUrl = (host: string, repository: string, number: number) => - `https://${host}/@${repository}/pull/${number}`; + `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`; -/** A GitHub-synced pull request from a fork names its head only by its pull ref. */ -export const headBranchName = (head: string) => head.replace(/^refs\/heads\//u, ""); +/** + * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private + * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede. + */ +export const headBranchName = (head: string) => + head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, ""); + +/** Absent when Source names no visibility, so a reader tells unknown from public. */ +const visibilityOf = (pull: Pick) => + pull.visibility === "private" || pull.visibility === "public" + ? { visibility: pull.visibility } + : {}; export function toActor(login: string | null, host: string): PullRequestActor | null { if (login === null || login.trim() === "") return null; @@ -280,6 +294,7 @@ export function toChangeRequest( baseBranch: pull.base ?? "", state: pull.state, isDraft: pull.draft, + ...visibilityOf(pull), mergeability: "unknown", additions: 0, deletions: 0, @@ -380,7 +395,9 @@ export function toActivity(input: { }): ProviderChangeRequestActivity { const { host } = input; const page = pullUrl(host, input.repository, input.number); - const entries = input.timeline.timeline.filter(visible); + const entries = input.timeline.timeline.filter( + (entry): entry is TimelineEntry => "id" in entry && visible(entry), + ); const comments: Array = entries.map((entry: TimelineEntry) => ({ id: String(entry.id), kind: diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts index e3ce5c867fa5c..6e09a89fa2cda 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.test.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts @@ -31,7 +31,23 @@ describe("TanStack Source definition", () => { number: 7, }), ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); + // A stored link or an older client may name the repository as the web spells it. + for (const repository of ["@TanStack/router", "%40TanStack/router"]) + expect( + definition.changeRequestUrl({ host: "source.tanstack.com", repository, number: 7 }), + repository, + ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); expect(definition.checkoutCommandArgument("src pr checkout 7")).toBe("7"); expect(definition.checkoutCommandArgument("gh pr checkout 7")).toBeNull(); }); + + it.each(["tanstack/router", "@tanstack/router", "%40tanstack/router"])( + "keys %s as the API's owner/name", + (repository) => { + expect(definition.canonicalRepositoryKey?.(`source.tanstack.com/${repository}`)).toBe( + "source.tanstack.com/tanstack/router", + ); + expect(definition.canonicalRepositoryKey?.(`github.com/${repository}`)).toBeNull(); + }, + ); }); diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts index 1aee00c968dc6..032adc5a45cdd 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.ts @@ -37,6 +37,20 @@ function parseChangeRequestUrl(url: URL) { : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` }; } +/** + * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this + * definition percent-encodes that as `%40owner/name`. + */ +export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, ""); + +/** Links stored with the web's spelling compare equal to the project's own key. */ +function canonicalRepositoryKey(key: string): string | null { + const slash = key.indexOf("/"); + return slash > 0 && isTanStackSourceHost(key.slice(0, slash)) + ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}` + : null; +} + /** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */ function repositoryKeyFromRemote(key: string): string | null { // Remote parsing spells the `@` percent-encoded. @@ -80,13 +94,13 @@ export const definition = defineSourceControl({ ? null : webUrl ? changeRequestUrlBelow(webUrl, `pull/${number}`) - : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`, + : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`, parseChangeRequestUrl, commitUrl: (input) => buildCommitUrl( input.webUrl ? input - : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` }, + : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` }, "commit", ), parseIssueUrl: (url) => @@ -122,6 +136,7 @@ export const definition = defineSourceControl({ checkoutChangeRequestHost: () => null, changeRequestHeadRef: (number) => `refs/pull/${number}/head`, repositoryKeyFromRemote, + canonicalRepositoryKey, recognizeRemote: ({ hostname }) => isTanStackSourceHost(hostname) ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` } diff --git a/patches/@legendapp__list@3.7.3.patch b/patches/@legendapp__list@3.7.3.patch new file mode 100644 index 0000000000000..2afc400b04435 --- /dev/null +++ b/patches/@legendapp__list@3.7.3.patch @@ -0,0 +1,28 @@ +diff --git a/react-native.js b/react-native.js +index 440b0ad..fd5d18d 100644 +--- a/react-native.js ++++ b/react-native.js +@@ -1344,7 +1344,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { + return; + } + if (contentSize > 0 && queuedInitialLayout) { +- const isContentLess = contentSize < scrollLength; ++ // T3 patch: a top inset (e.g. a translucent header) shrinks the room content has to fit in. ++ const isContentLess = contentSize + getContentInsetTop(ctx) < scrollLength; + set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); + set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); + set$( +diff --git a/react-native.mjs b/react-native.mjs +index b95e1f8..e2b013a 100644 +--- a/react-native.mjs ++++ b/react-native.mjs +@@ -1323,7 +1323,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { + return; + } + if (contentSize > 0 && queuedInitialLayout) { +- const isContentLess = contentSize < scrollLength; ++ // T3 patch: a top inset (e.g. a translucent header) shrinks the room content has to fit in. ++ const isContentLess = contentSize + getContentInsetTop(ctx) < scrollLength; + set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); + set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); + set$( diff --git a/patches/effect@4.1.5.patch b/patches/effect@4.1.5.patch new file mode 100644 index 0000000000000..91026f0d15bd7 --- /dev/null +++ b/patches/effect@4.1.5.patch @@ -0,0 +1,4086 @@ +diff --git a/dist/ai/McpSchema.d.ts b/dist/ai/McpSchema.d.ts +index 8f86c27..aed42ae 100644 +--- a/dist/ai/McpSchema.d.ts ++++ b/dist/ai/McpSchema.d.ts +@@ -941,6 +941,52 @@ export declare const HEADER_MISMATCH_ERROR_CODE: -32020; + * @since 4.0.6 + */ + export declare const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE: -32022; ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const NOT_FOUND_ERROR_CODE: -32023; ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const FORBIDDEN_ERROR_CODE: -32024; ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const RESOURCE_EXHAUSTED_ERROR_CODE: -32025; ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const UNSUPPORTED_ERROR_CODE: -32026; ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const CALLBACK_ENDPOINT_ERROR_CODE: -32027; + declare const ParseError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"NotFound">; ++ readonly code: Schema.tag<-32023>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class NotFound extends NotFound_base { ++} ++declare const Forbidden_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Forbidden">; ++ readonly code: Schema.tag<-32024>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Forbidden extends Forbidden_base { ++} ++declare const ResourceExhausted_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"ResourceExhausted">; ++ readonly code: Schema.tag<-32025>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class ResourceExhausted extends ResourceExhausted_base { ++} ++declare const Unsupported_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Unsupported">; ++ readonly code: Schema.tag<-32026>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Unsupported extends Unsupported_base { ++} ++declare const CallbackEndpointError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"CallbackEndpointError">; ++ readonly code: Schema.tag<-32027>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class CallbackEndpointError extends CallbackEndpointError_base { ++} + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1880,6 +2001,66 @@ declare const Skill_base: Schema.Class; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type; ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventDescriptor: Schema.Struct<{ ++ readonly name: Schema.String; ++ readonly description: Schema.decodeTo>, Schema.optionalKey, never, never>; ++ readonly delivery: Schema.$Array>; ++ readonly inputSchema: Schema.$Record; ++ readonly payloadSchema: Schema.$Record; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type; ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventOccurrence: Schema.Struct<{ ++ readonly eventId: Schema.String; ++ readonly name: Schema.String; ++ readonly timestamp: Schema.String; ++ readonly data: Schema.$Record; ++ readonly cursor: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type; + declare const PromptArgument_base: Schema.Opaque Effect.Effect Layer.Layer; ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const registerEvent: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Effect.Effect>; ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const event: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Layer.Layer>; ++declare const CallbackRejected_base: new = {}>(args: import("../Types.ts").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("../Cause.ts").YieldableError & { ++ readonly _tag: "CallbackRejected"; ++} & Readonly; ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class CallbackRejected extends CallbackRejected_base<{ ++ readonly message: string; ++}> { ++} ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const CallbackGuard: Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect; ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined; ++}>; ++declare const EventWebhooks_base: Context.ServiceClass; ++}>; ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare class EventWebhooks extends EventWebhooks_base { ++} ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect; ++} ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const layerEventWebhooks: (options: EventWebhooksOptions) => Layer.Layer; + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/McpServer.js b/dist/ai/McpServer.js +index 4bf6bca..5ad258e 100644 +--- a/dist/ai/McpServer.js ++++ b/dist/ai/McpServer.js +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.js"; + import * as Clock from "../Clock.js"; + import * as Context from "../Context.js"; + import * as Digest from "../crypto/Digest.js"; ++import * as Mac from "../crypto/Mac.js"; ++import * as SecureRandom from "../crypto/SecureRandom.js"; + import * as Data from "../Data.js"; + import * as Deferred from "../Deferred.js"; + import * as Duration from "../Duration.js"; +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.js"; + import * as Fiber from "../Fiber.js"; + import * as FindMyWay from "../http/FindMyWay.js"; + import * as Headers from "../http/Headers.js"; ++import * as HttpClient from "../http/HttpClient.js"; + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.js"; + import * as HttpRouter from "../http/HttpRouter.js"; + import * as HttpServerRequest from "../http/HttpServerRequest.js"; +@@ -55,6 +58,7 @@ import * as McpCore from "./internal/mcpCore.js"; + import * as McpProtocolInternal from "./internal/mcpProtocol.js"; + import * as McpRuntime from "./internal/mcpRuntime.js"; + import * as McpSkills from "./internal/mcpSkills.js"; ++import * as McpWebhooks from "./internal/mcpWebhooks.js"; + import * as InternalStructuredOutput from "./internal/structured-output.js"; + import * as McpSchema from "./McpSchema.js"; + import { CallToolResult, ElicitationDeclined, EnabledWhen, GetPromptResult, InternalError, InvalidParams, InvalidRequest, isParam, McpRequestContext, McpServerClient, McpServerClientMiddleware, MethodNotFound, Prompt, Resource, ResourceTemplate, ServerNotificationRpcs, TextContent, Tool as McpTool, ToolJson } from "./McpSchema.js"; +@@ -413,6 +417,9 @@ const notFound = (method, target) => { + return new McpCore.SkillNotFound({ + uri: target + }); ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target); + } + }; + const isHidden = error => error instanceof Hidden; +@@ -2637,6 +2644,155 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) + * @since 4.1.1 + */ + export const skill = options => Layer.effectDiscard(registerSkill(options)); ++// ============================================================================= ++// Events ++// ============================================================================= ++const DEFAULT_NEXT_POLL_MS = 30_000; ++/** ++* Registers an event type under the MCP Events extension (SEP-3415). ++* ++* **Details** ++* ++* The server declares `io.modelcontextprotocol/events` on revision ++* `2026-07-28` once any event type is registered, and answers `events/list`, ++* `events/poll`, `events/stream`, and with {@link EventWebhooks} ++* `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its ++* lifetime inside the request's middleware, sends heartbeats carrying the ++* last cursor, and ends when the client goes away. Services read by `poll` ++* and `stream` are request-level, as for tools. ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const registerEvent = Effect.fnUntraced(function* (options) { ++ const { name, poll, stream } = options; ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)); ++ } ++ const registry = yield* McpServer; ++ const { core, globalMiddleware } = internalState.get(registry); ++ const services = yield* Effect.context(); ++ const annotations = options.annotations ?? Context.empty(); ++ const { invoke, visible } = makeInvoke(services, globalMiddleware); ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))); ++ const parameters = options.parameters ?? Schema.Struct({}); ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)); ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)); ++ const argumentsOf = (args) => decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))); ++ const encodeEvent = (event) => encodePayload(event.data).pipe(Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), Effect.map((data) => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` }))); ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll"]), ++ ...(stream === undefined ? [] : ["push"]), ++ ...(webhooks === undefined ? [] : ["webhook"]) ++ ], ++ inputSchema: toolJsonSchema(parameters, false), ++ payloadSchema: toolJsonSchema(options.payload, false), ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, ++ poll: poll === undefined ? undefined : (request, invocation) => invoke(Effect.gen(function* () { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }); ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ }; ++ }), invocation, { method: "events/poll", target: name, payload: request }), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => invoke(Effect.scoped(Effect.gen(function* () { ++ const args = request.decoded !== undefined ? request.decoded.value : yield* argumentsOf(request.arguments); ++ const subscription = yield* stream(args, { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }); ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context(); ++ const items = subscription.items.pipe(Stream.mapEffect((item) => item._tag === "Event" ++ ? encodeEvent(item).pipe(Effect.map((event) => ({ ...event, _tag: "Event", cursor: item.cursor })), Effect.catch((error) => Effect.succeed({ _tag: "Error", error }))) ++ : Effect.succeed(item)), Stream.provideContext(context)); ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }); ++ })), invocation, { method: "events/stream", target: name, payload: request }) ++ }); ++}); ++/** ++* Creates a layer that registers an event type under the MCP Events ++* extension (SEP-3415). ++* ++* @see {@link registerEvent} for the Effect-level event registration API ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const event = (options) => Layer.effectDiscard(registerEvent(options)); ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends /*#__PURE__*/Data.TaggedError("CallbackRejected") {} ++/** ++ * Decides which webhook callback URLs may be reached. The default refuses ++ * every URL; see the source for the contract a platform guard keeps. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = /*#__PURE__*/Context.Reference("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}); ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends /*#__PURE__*/Context.Service()("effect/ai/McpServer/EventWebhooks") {} ++const webhooksState = /*#__PURE__*/new WeakMap(); ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = (options) => Layer.effect(EventWebhooks, Effect.gen(function* () { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }); ++ const service = EventWebhooks.of({ size: webhooks.size }); ++ webhooksState.set(service, webhooks); ++ return service; ++}).pipe(Effect.provide(Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe(Layer.provideMerge(SecureRandom.layerWebCrypto))))); + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/internal/mcpCore.js b/dist/ai/internal/mcpCore.js +index 4c416a8..50d2d34 100644 +--- a/dist/ai/internal/mcpCore.js ++++ b/dist/ai/internal/mcpCore.js +@@ -75,6 +75,15 @@ export const ClientNotification = /*#__PURE__*/Data.taggedEnum(); + * @internal + */ + export const ServerNotification = /*#__PURE__*/Data.taggedEnum(); ++/** ++ * @internal ++ */ ++export const eventNotFound = name => new McpSchema.NotFound({ ++ message: `Event '${name}' not found`, ++ data: { ++ kind: "event" ++ } ++}); + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a, b) => { + const rootA = a.slice(0, -"/SKILL.md".length); +@@ -90,6 +99,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + const resourceTemplateRegistrations = []; + const promptRegistrations = new Map(); + const skillRegistrations = new Map(); ++ const eventRegistrations = new Map(); + const skillFiles = new Set(); + const completionRegistrations = new Map(); + const filterList = (registrations, invocation) => Effect.map(Effect.filter(Arr.filter(registrations, entry => entry.isVisible(invocation.protocol)), entry => entry.visible === undefined ? Effect.succeed(true) : entry.visible(invocation)), entries => entries.map(entry => entry.descriptor)); +@@ -234,11 +244,22 @@ export const make = /*#__PURE__*/Effect.sync(() => { + return Array.from(children.values()).sort((a, b) => a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0); + }) + }; ++ const events = { ++ register: registration => Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration); ++ }), ++ list: invocation => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => Effect.suspend(() => { ++ const registration = eventRegistrations.get(name); ++ return registration !== undefined && registration.isVisible(invocation.protocol) ? Effect.succeed(registration) : Effect.fail(eventNotFound(name)); ++ }) ++ }; + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })); + return { + tools, +@@ -246,6 +267,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + prompts, + completions, + skills, ++ events, + registrationPresence + }; + }); +diff --git a/dist/ai/internal/mcpEvents.d.ts b/dist/ai/internal/mcpEvents.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpEvents.js b/dist/ai/internal/mcpEvents.js +new file mode 100644 +index 0000000..d875046 +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.js +@@ -0,0 +1,265 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.js"; ++import * as Clock from "../../Clock.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Option from "../../Option.js"; ++import * as Queue from "../../Queue.js"; ++import * as Result from "../../Result.js"; ++import * as Rpc from "../../rpc/Rpc.js"; ++import * as RpcGroup from "../../rpc/RpcGroup.js"; ++import * as Schema from "../../Schema.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import * as McpProtocol from "./mcpProtocol.js"; ++import * as Stateless from "./mcpSchema/v2026_07_28.js"; ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events"; ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = (extensions, servesEvents) => servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions; ++const methodNotFound = (method) => new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++}); ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core, method) => Effect.flatMap(core.registrationPresence, (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method))); ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value) => new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++}); ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++const optional = Stateless.optional; ++const Cursor = Schema.NullOr(Schema.String); ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest(Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) { ++} ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++}; ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++}), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) { ++} ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make(EventsActiveNotification, EventsEventNotification, EventsHeartbeatNotification, EventsErrorNotification, EventsTerminatedNotification) { ++} ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++const DEFAULT_HEARTBEAT_MS = 30_000; ++const MIN_HEARTBEAT_MS = 1_000; ++const MAX_HEARTBEAT_MS = 300_000; ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16; ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested) => Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)); ++const isJson = Schema.is(Schema.Json); ++/** ++ * @internal ++ */ ++export const wireError = (failure) => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}); ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function* (options) { ++ const { heartbeatMs, name, subscription } = options; ++ let cursor = subscription.cursor; ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0; ++ const send = (tag, payload) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at; ++ })); ++ const active = (truncated) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }); ++ yield* active(subscription.truncated); ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }); ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)); ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result); ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }); ++ } ++ return; ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }); ++ continue; ++ } ++ const item = next.success.value; ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor; ++ const { _meta, _tag, ...occurrence } = item; ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }); ++ break; ++ } ++ case "Position": { ++ cursor = item.cursor; ++ break; ++ } ++ case "Gap": { ++ cursor = item.cursor; ++ yield* active(true); ++ break; ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }); ++ break; ++ } ++ } ++ } ++}, Effect.scoped); +diff --git a/dist/ai/internal/mcpProtocol/v2026_07_28.js b/dist/ai/internal/mcpProtocol/v2026_07_28.js +index af1ceed..ea29279 100644 +--- a/dist/ai/internal/mcpProtocol/v2026_07_28.js ++++ b/dist/ai/internal/mcpProtocol/v2026_07_28.js +@@ -17,6 +17,7 @@ import * as Schema from "../../../Schema.js"; + import * as Scope from "../../../Scope.js"; + import * as PublicMcpSchema from "../../McpSchema.js"; + import * as McpCore from "../mcpCore.js"; ++import * as McpEvents from "../mcpEvents.js"; + import * as McpProtocol from "../mcpProtocol.js"; + import * as McpSchema from "../mcpSchema/v2026_07_28.js"; + import * as McpSkills from "../mcpSkills.js"; +@@ -242,7 +243,7 @@ const unsupported = operation => new PublicMcpSchema.McpReverseOperationUnsuppor + /** + * @internal + */ +-export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs); ++export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs, McpEvents.StatelessRpcs); + /** + * @internal + */ +@@ -260,6 +261,10 @@ export const makeHandlers = (core, _lifecycle, context) => { + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult); + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult); + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult); ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult); ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult); ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema); ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema); + const sendNotification = context.sendNotification; + const supportsSubscriptions = sendNotification !== undefined; + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -277,8 +282,11 @@ export const makeHandlers = (core, _lifecycle, context) => { + completions: {}, + logging: {} + }; +- const declared = McpSkills.declareExtension(extensions, presence.skills); ++ const declared = McpEvents.declareExtension(McpSkills.declareExtension(extensions, presence.skills), presence.events); + if (declared !== undefined) capabilities.extensions = declared; ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {}; + if (presence.tools) capabilities.tools = { + listChanged: supportsSubscriptions + }; +@@ -297,6 +305,26 @@ export const makeHandlers = (core, _lifecycle, context) => { + serverInfo: context.serverInfo + }; + }); ++ const requireEvents = (method) => McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))); ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function* (registration, args) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest); ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers); ++ } ++ }); ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function* (method, name, args) { ++ yield* requireEvents(method); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(name, invocation); ++ const { stream, webhooks } = registration; ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook"); ++ } ++ yield* validateEventHeaders(registration, args); ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments }; ++ }); + const requireSkills = method => McpSkills.requireSkills(core, method).pipe(Effect.catch(error => failWithHttpStatus(404, error))); + const getInvocation = PublicMcpSchema.McpRequestContext.useSync(McpProtocol.invocationFromRequestContext); + const getInputInvocation = Effect.fnUntraced(function* (request) { +@@ -592,6 +620,97 @@ export const makeHandlers = (core, _lifecycle, context) => { + }, context.serverInfo); + return yield* decodeReadResourceDirectoryResult(result); + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/list"); ++ yield* McpProtocol.rejectCursor(request.cursor); ++ const events = yield* core.events.list(yield* getInvocation); ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push"); ++ return delivery.length === 0 ? [] : [{ ...event, delivery }]; ++ }); ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo); ++ return yield* decodeListEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/poll"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation); ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ })), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo); ++ return yield* decodePollEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function* (request, { client, requestId }) { ++ yield* requireEvents("events/stream"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId }; ++ const send = (tag, payload) => sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }); ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs); ++ yield* Effect.raceFirst(registration.stream({ arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, invocation, (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send })), context.awaitClientEnd ?? Effect.never); ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo); ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }); ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function* (request) { ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration("events/subscribe", request.name, request.arguments); ++ const args = request.arguments ?? {}; ++ const cursor = request.cursor ?? null; ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => stream({ arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, invocation, deliver) ++ }); ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo); ++ return yield* decodeSubscribeEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function* (request) { ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments); ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }); ++ const result = yield* projectCompleteResult({}, context.serverInfo); ++ return yield* decodeUnsubscribeEventsResult(result); ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function* (_request) { + return yield* Effect.void; + }) +@@ -613,10 +732,10 @@ const runtime = { + export const protocol = /*#__PURE__*/McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: /*#__PURE__*/McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/dist/ai/internal/mcpRuntime.js b/dist/ai/internal/mcpRuntime.js +index 88238ff..721ff28 100644 +--- a/dist/ai/internal/mcpRuntime.js ++++ b/dist/ai/internal/mcpRuntime.js +@@ -39,6 +39,10 @@ const routingNameKey = method => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name"; + case "resources/read": + return "uri"; +@@ -178,7 +182,10 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey]; + const header = headers[MCP_NAME_HEADER]; +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe"); ++ if (!optional && (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name)) { + return headerMismatch("Mcp-Name header does not match request parameters"); + } + } +@@ -340,7 +347,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && (input.method === "subscriptions/listen" || input.method === "events/stream") + }; + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/dist/ai/internal/mcpWebhooks.d.ts b/dist/ai/internal/mcpWebhooks.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpWebhooks.js b/dist/ai/internal/mcpWebhooks.js +new file mode 100644 +index 0000000..4e2871a +--- /dev/null ++++ b/dist/ai/internal/mcpWebhooks.js +@@ -0,0 +1,456 @@ ++import * as Clock from "../../Clock.js"; ++import * as Digest from "../../crypto/Digest.js"; ++import * as Mac from "../../crypto/Mac.js"; ++import * as SecureRandom from "../../crypto/SecureRandom.js"; ++import * as Deferred from "../../Deferred.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Base64 from "../../encoding/Base64.js"; ++import * as Base64Url from "../../encoding/Base64Url.js"; ++import * as Fiber from "../../Fiber.js"; ++import * as FetchHttpClient from "../../http/FetchHttpClient.js"; ++import * as HttpClient from "../../http/HttpClient.js"; ++import * as HttpClientRequest from "../../http/HttpClientRequest.js"; ++import * as Option from "../../Option.js"; ++import * as Result from "../../Result.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import { wireError } from "./mcpEvents.js"; ++const MINUTE_MS = 6e4; ++const MIN_TTL_MS = MINUTE_MS; ++const MAX_TTL_MS = 60 * MINUTE_MS; ++const DEFAULT_TTL_MS = 15 * MINUTE_MS; ++const MAX_ATTEMPTS = 5; ++const FIRST_RETRY_MS = 3e4; ++const REQUEST_TIMEOUT_MS = 1e4; ++const ROTATION_GRACE_MS = 5 * MINUTE_MS; ++const VERIFIED_FOR_MS = MAX_TTL_MS; ++const FAILED_FOR_MS = 5 * MINUTE_MS; ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10; ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100; ++const MAX_CHALLENGE_RESPONSE_BYTES = 8192; ++const SECRET_PREFIX = "whsec_"; ++const invalid = (message) => new PublicMcpSchema.InvalidParams({ message }); ++const grantTtl = (suggested) => suggested === void 0 ? DEFAULT_TTL_MS : suggested === null ? MAX_TTL_MS : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)); ++const canonicalJson = (value) => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`; ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== void 0); ++ entries.sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`; ++ } ++ return JSON.stringify(value) ?? "null"; ++}; ++const encoder = new TextEncoder(); ++const parseUrl = (value, guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")); ++ let url; ++ try { ++ url = new URL(value); ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")); ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")); ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")); ++ } ++ url.hash = ""; ++ return Effect.succeed(url); ++}; ++const parseSecret = (value) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")); ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail; ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)); ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail; ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))); ++}; ++const statusCategory = (status) => status >= 500 ? "http_5xx" : "http_4xx"; ++const transportCategory = (error) => { ++ let current = error; ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = current.code; ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error"; ++ current = current.cause ?? current.reason; ++ } ++ return "connection_refused"; ++}; ++const readCapped = (response) => Effect.suspend(() => { ++ const chunks = []; ++ let total = 0; ++ let oversized = false; ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true; ++ return false; ++ } ++ total += chunk.length; ++ chunks.push(chunk); ++ return true; ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return void 0; ++ const bytes = new Uint8Array(total); ++ let offset = 0; ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset); ++ offset += chunk.length; ++ } ++ return new TextDecoder().decode(bytes); ++ }) ++ ); ++}); ++const echoedChallenge = (body) => { ++ try { ++ const parsed = JSON.parse(body); ++ const challenge = typeof parsed === "object" && parsed !== null ? parsed.challenge : void 0; ++ return typeof challenge === "string" ? challenge : void 0; ++ } catch { ++ return void 0; ++ } ++}; ++const callbackError = (category) => new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++}); ++const iso = (millis) => new Date(millis).toISOString(); ++const make = Effect.fnUntraced(function* (options) { ++ const scope = yield* Effect.scope; ++ const mac = yield* Mac.Mac; ++ const digest = yield* Digest.Digest; ++ const random = yield* SecureRandom.SecureRandom; ++ const { guard } = options; ++ const client = HttpClient.withScope(options.client); ++ const subscriptions = /* @__PURE__ */ new Map(); ++ const pending = /* @__PURE__ */ new Map(); ++ const verified = /* @__PURE__ */ new Map(); ++ const failedVerifications = /* @__PURE__ */ new Map(); ++ const verifying = /* @__PURE__ */ new Map(); ++ const verificationsByHost = /* @__PURE__ */ new Map(); ++ const forget = (subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id); ++ }; ++ const subscriptionId = (principal, url, name, args) => digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ); ++ const messageId = (prefix) => Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`); ++ const deliveryId = (subscription, eventId) => Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ); ++ const MAX_CURSORS_SINCE_GAP = 1024; ++ const advance = (subscription, cursor) => { ++ subscription.watermark = cursor; ++ const since = subscription.cursorsSinceGap; ++ if (since === void 0) return; ++ since.add(cursor); ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value); ++ }; ++ const sign = (keys, webhookId, timestamp, body) => Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ); ++ const send = Effect.fnUntraced(function* (subscription, body, webhookId, readBody) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)); ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true }; ++ } ++ const now = yield* Clock.currentTimeMillis; ++ const timestamp = Math.floor(now / 1e3); ++ const previous = subscription.previous; ++ const keys = previous !== void 0 && now < previous.until ? [subscription.key, previous.key] : [subscription.key]; ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ); ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response) => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }); ++ } ++ return readBody ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) : Effect.succeed({ _tag: "Delivered", body: void 0 }); ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch( ++ (error) => Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ); ++ return Option.getOrElse(outcome, () => ({ _tag: "Failed", category: "timeout", retryable: true })); ++ }); ++ const deliver = Effect.fnUntraced(function* (subscription, body, webhookId) { ++ for (let attempt = 1; ; attempt++) { ++ const current = subscriptions.get(subscription.id); ++ if (current !== void 0 && current !== subscription) return false; ++ const startedAt = yield* Clock.currentTimeMillis; ++ const outcome = yield* send(subscription, body, webhookId, false); ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis; ++ subscription.lastError = void 0; ++ return true; ++ } ++ subscription.lastError = outcome.category; ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false; ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis); ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)); ++ } ++ }); ++ const control = (subscription, type, fields) => Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ); ++ const run = (subscription, name, events) => events.items.pipe( ++ Stream.runForEach((item) => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...item._meta === void 0 ? {} : { _meta: item._meta } ++ }); ++ return deliver(subscription, body, webhookId); ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))); ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)); ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = /* @__PURE__ */ new Set(); ++ advance(subscription, item.cursor); ++ }) ++ ); ++ case "Error": ++ return Effect.void; ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch( ++ (failure) => Effect.suspend(() => { ++ forget(subscription); ++ return control(subscription, "terminated", { error: wireError(failure) }); ++ }) ++ ) ++ ); ++ const expiry = (subscription) => Effect.gen(function* () { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis); ++ if (left <= 0) return forget(subscription); ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)); ++ } ++ }); ++ const handshake = Effect.fnUntraced(function* (subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)); ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ); ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category); ++ const echoed = outcome.body === void 0 ? void 0 : echoedChallenge(outcome.body); ++ if (echoed === void 0 || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed"); ++ } ++ }); ++ const verify = Effect.fnUntraced(function* (subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]); ++ const now = yield* Clock.currentTimeMillis; ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry); ++ for (const [entry, failure2] of failedVerifications) if (failure2.until <= now) failedVerifications.delete(entry); ++ if (verified.has(key)) return; ++ const failure = failedVerifications.get(key); ++ if (failure !== void 0) return yield* callbackError(failure.category); ++ const inFlight = verifying.get(key); ++ if (inFlight !== void 0) return yield* Deferred.await(inFlight); ++ const host = subscription.url.hostname; ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS); ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent); ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }); ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry); ++ } ++ verificationsByHost.set(host, [...recent, now]); ++ const done = Deferred.makeUnsafe(); ++ verifying.set(key, done); ++ return yield* handshake(subscription).pipe( ++ Effect.tap( ++ () => Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS); ++ }) ++ ), ++ Effect.tapError( ++ (category) => Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }); ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit( ++ (exit) => Effect.sync(() => { ++ verifying.delete(key); ++ Deferred.doneUnsafe(done, exit); ++ }) ++ ) ++ ); ++ }); ++ const refresh = Effect.fnUntraced(function* (request, subscription, secret, expiresAt, now) { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted); ++ const start = yield* Deferred.await(subscription.accepted); ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request); ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS }; ++ subscription.secret = secret.text; ++ subscription.key = secret.key; ++ } ++ subscription.expiresAt = expiresAt; ++ const moved = subscription.deadlineMoved; ++ subscription.deadlineMoved = Deferred.makeUnsafe(); ++ Deferred.doneUnsafe(moved, Effect.void); ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start }; ++ const since = subscription.cursorsSinceGap; ++ if (since !== void 0 && since.has(request.cursor)) subscription.cursorsSinceGap = void 0; ++ const truncated = subscription.cursorsSinceGap !== void 0; ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === void 0 ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ }; ++ }); ++ const subscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const mode = request.delivery.mode; ++ if (mode !== void 0 && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'"); ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const secret = yield* parseSecret(request.delivery.secret); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const now = yield* Clock.currentTimeMillis; ++ const expiresAt = now + grantTtl(request.ttlMs); ++ const live = subscriptions.get(id); ++ if (live !== void 0) return yield* refresh(request, live, secret, expiresAt, now); ++ let held = pending.get(principal) ?? 0; ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++; ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }); ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1); ++ let reserved = true; ++ const release = () => { ++ if (!reserved) return; ++ reserved = false; ++ const left = (pending.get(principal) ?? 1) - 1; ++ if (left === 0) pending.delete(principal); ++ else pending.set(principal, left); ++ }; ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ); ++ }); ++ const create = Effect.fnUntraced(function* (request, { expiresAt, id, now, principal, release, secret, url }) { ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")); ++ const subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: void 0, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: void 0, ++ lastError: void 0, ++ fiber: void 0, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: void 0 ++ }; ++ const decoded = yield* request.decode; ++ yield* verify(subscription); ++ const raced = subscriptions.get(id); ++ if (raced !== void 0) { ++ release(); ++ return yield* refresh(request, raced, secret, expiresAt, now); ++ } ++ release(); ++ subscriptions.set(id, subscription); ++ const { accepted } = subscription; ++ const lifetime = request.open( ++ decoded, ++ (events) => Effect.suspend(() => { ++ subscription.watermark = events.cursor; ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }); ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription); ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })); ++ })) ++ ); ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope); ++ const start = yield* Deferred.await(accepted); ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated }; ++ }); ++ const unsubscribe = Effect.fnUntraced(function* (request) { ++ const principal = yield* options.principal; ++ const url = yield* parseUrl(request.delivery.url, guard); ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments); ++ const subscription = subscriptions.get(id); ++ if (subscription === void 0) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }); ++ } ++ subscriptions.delete(id); ++ if (subscription.fiber !== void 0) yield* Fiber.interrupt(subscription.fiber); ++ }); ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ }; ++}); ++export { ++ DEFAULT_TTL_MS, ++ MAX_ATTEMPTS, ++ MAX_TTL_MS, ++ MIN_TTL_MS, ++ canonicalJson, ++ grantTtl, ++ make ++}; +diff --git a/src/ai/McpSchema.ts b/src/ai/McpSchema.ts +index ba6c830..1e58fb9 100644 +--- a/src/ai/McpSchema.ts ++++ b/src/ai/McpSchema.ts +@@ -740,6 +740,57 @@ export const HEADER_MISMATCH_ERROR_CODE = -32020 as const + */ + export const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE = -32022 as const + ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const NOT_FOUND_ERROR_CODE = -32023 as const ++ ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const FORBIDDEN_ERROR_CODE = -32024 as const ++ ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const RESOURCE_EXHAUSTED_ERROR_CODE = -32025 as const ++ ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const UNSUPPORTED_ERROR_CODE = -32026 as const ++ ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const CALLBACK_ENDPOINT_ERROR_CODE = -32027 as const ++ + /** + * Represents an MCP/JSON-RPC error for invalid JSON that could not be parsed. + * +@@ -852,6 +903,74 @@ export class InternalError extends Schema.Error("effect/ai/McpSch + static readonly notImplemented = new InternalError({ message: "Not implemented" }) + } + ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class NotFound extends Schema.Error("effect/ai/McpSchema/NotFound")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("NotFound"), ++ code: Schema.tag(NOT_FOUND_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Forbidden extends Schema.Error("effect/ai/McpSchema/Forbidden")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Forbidden"), ++ code: Schema.tag(FORBIDDEN_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class ResourceExhausted extends Schema.Error("effect/ai/McpSchema/ResourceExhausted")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("ResourceExhausted"), ++ code: Schema.tag(RESOURCE_EXHAUSTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Unsupported extends Schema.Error("effect/ai/McpSchema/Unsupported")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Unsupported"), ++ code: Schema.tag(UNSUPPORTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or ++ * could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class CallbackEndpointError ++ extends Schema.Error("effect/ai/McpSchema/CallbackEndpointError")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("CallbackEndpointError"), ++ code: Schema.tag(CALLBACK_ENDPOINT_ERROR_CODE) ++ }) ++{} ++ + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1501,6 +1620,76 @@ export class Skill extends Schema.Class( + _meta: optional(UnknownObject) + }) {} + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * How a client receives an event type's occurrences under the MCP Events ++ * extension (SEP-3415): by `events/poll`, an `events/stream` push stream, or ++ * a webhook registered with `events/subscribe`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDelivery = Schema.Literals(["poll", "push", "webhook"]) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type ++ ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDescriptor = Schema.Struct({ ++ name: Schema.String, ++ description: optional(Schema.String), ++ delivery: Schema.Array(EventDelivery), ++ inputSchema: UnknownObject, ++ payloadSchema: UnknownObject, ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type ++ ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventOccurrence = Schema.Struct({ ++ eventId: Schema.String, ++ name: Schema.String, ++ timestamp: Schema.String, ++ data: UnknownObject, ++ cursor: optional(Schema.NullOr(Schema.String)), ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type ++ + // ============================================================================= + // Prompts + // ============================================================================= +diff --git a/src/ai/McpServer.ts b/src/ai/McpServer.ts +index 4c2e191..bedd064 100644 +--- a/src/ai/McpServer.ts ++++ b/src/ai/McpServer.ts +@@ -16,6 +16,8 @@ import * as Cause from "../Cause.ts" + import * as Clock from "../Clock.ts" + import * as Context from "../Context.ts" + import * as Digest from "../crypto/Digest.ts" ++import * as Mac from "../crypto/Mac.ts" ++import * as SecureRandom from "../crypto/SecureRandom.ts" + import * as Data from "../Data.ts" + import * as Deferred from "../Deferred.ts" + import * as Duration from "../Duration.ts" +@@ -26,6 +28,7 @@ import * as Exit from "../Exit.ts" + import * as Fiber from "../Fiber.ts" + import * as FindMyWay from "../http/FindMyWay.ts" + import * as Headers from "../http/Headers.ts" ++import * as HttpClient from "../http/HttpClient.ts" + import { appendPreResponseHandlerUnsafe } from "../http/HttpEffect.ts" + import * as HttpRouter from "../http/HttpRouter.ts" + import * as HttpServerRequest from "../http/HttpServerRequest.ts" +@@ -59,6 +62,7 @@ import * as McpCore from "./internal/mcpCore.ts" + import * as McpProtocolInternal from "./internal/mcpProtocol.ts" + import * as McpRuntime from "./internal/mcpRuntime.ts" + import * as McpSkills from "./internal/mcpSkills.ts" ++import * as McpWebhooks from "./internal/mcpWebhooks.ts" + import * as InternalStructuredOutput from "./internal/structured-output.ts" + import type * as McpProtocol from "./McpProtocol.ts" + import * as McpSchema from "./McpSchema.ts" +@@ -344,6 +348,9 @@ export type MiddlewareMethod = + | "skills/list" + | "skills/get" + | "resources/directory/read" ++ | "events/list" ++ | "events/poll" ++ | "events/stream" + + /** + * Request metadata passed to MCP middleware. +@@ -819,7 +826,14 @@ const internalError = new InternalError({ message: "Internal error" }) + const rejectWith = (error: McpErrorBase) => + Effect.fail(new McpCore.RequestRejected({ code: error.code, message: error.message, data: error.data, error })) + +-type CallMethod = "tools/call" | "resources/read" | "prompts/get" | "completion/complete" | "skills/get" ++type CallMethod = ++ | "tools/call" ++ | "resources/read" ++ | "prompts/get" ++ | "completion/complete" ++ | "skills/get" ++ | "events/poll" ++ | "events/stream" + + type ListMethod = Exclude + +@@ -829,6 +843,8 @@ interface NotFoundErrors { + readonly "prompts/get": McpCore.PromptNotFound + readonly "completion/complete": InvalidParams + readonly "skills/get": McpCore.SkillNotFound ++ readonly "events/poll": McpSchema.NotFound ++ readonly "events/stream": McpSchema.NotFound + } + + const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod] => { +@@ -843,6 +859,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod + return new InvalidParams({ message: "Unknown completion reference or argument" }) + case "skills/get": + return new McpCore.SkillNotFound({ uri: target }) ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target) + } + } + +@@ -4134,6 +4153,404 @@ export const registerSkill: (options: SkillOptions) => Effect.Effect => + Layer.effectDiscard(registerSkill(options)) + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. With {@link EventWebhooks} provided where the ++ * event is registered, `stream` also backs webhook delivery. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++const DEFAULT_NEXT_POLL_MS = 30_000 ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll`, `events/stream`, and with {@link EventWebhooks} ++ * `events/subscribe` and `events/unsubscribe`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const registerEvent: < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions) => Effect.Effect> = ++ Effect.fnUntraced(function*(options: EventOptions, Schema.Codec, any>) { ++ const { name, poll, stream } = options ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)) ++ } ++ const registry = yield* McpServer ++ const { core, globalMiddleware } = internalState.get(registry)! ++ const services = yield* Effect.context() ++ const annotations = options.annotations ?? Context.empty() ++ const { invoke, visible } = makeInvoke(services, globalMiddleware) ++ const webhooks = stream === undefined ++ ? undefined ++ : Option.getOrUndefined(Option.map(Context.getOption(services, EventWebhooks), (service) => webhooksState.get(service))) ++ const parameters = options.parameters ?? Schema.Struct({}) ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)) ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)) ++ const argumentsOf = (args: unknown) => ++ decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))) ++ const encodeEvent = (event: EventOccurrence) => ++ encodePayload(event.data).pipe( ++ Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), ++ Effect.map((data): McpCore.EncodedEvent => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), ++ Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` })) ++ ) ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [ ++ ...(poll === undefined ? [] : ["poll" as const]), ++ ...(stream === undefined ? [] : ["push" as const]), ++ ...(webhooks === undefined ? [] : ["webhook" as const]) ++ ], ++ inputSchema: toolJsonSchema(parameters, false) as Record, ++ payloadSchema: toolJsonSchema(options.payload, false) as Record, ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ webhooks, ++ decodeArguments: argumentsOf, ++ poll: poll === undefined ? undefined : (request, invocation) => ++ invoke( ++ Effect.gen(function*() { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }) ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ } ++ }), ++ invocation, ++ { method: "events/poll", target: name, payload: request } ++ ), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => ++ invoke( ++ Effect.scoped(Effect.gen(function*() { ++ const args = request.decoded !== undefined ++ ? request.decoded.value ++ : yield* argumentsOf(request.arguments) ++ const subscription = yield* stream(args, { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }) ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context() ++ const items = subscription.items.pipe( ++ Stream.mapEffect((item): Effect.Effect => ++ item._tag === "Event" ++ ? encodeEvent(item).pipe( ++ Effect.map((event) => ({ ...event, _tag: "Event" as const, cursor: item.cursor })), ++ Effect.catch((error) => Effect.succeed({ _tag: "Error" as const, error })) ++ ) ++ : Effect.succeed(item) ++ ), ++ Stream.provideContext(context) ++ ) ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }) ++ })), ++ invocation, ++ { method: "events/stream", target: name, payload: request } ++ ) ++ }) ++ }) as any ++ ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const event = < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions): Layer.Layer> => ++ Layer.effectDiscard(registerEvent(options)) ++ ++/** ++ * The reason a {@link CallbackGuard} refuses a callback URL. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class CallbackRejected extends Data.TaggedError("CallbackRejected")<{ ++ readonly message: string ++}> {} ++ ++/** ++ * Decides which webhook callback URLs may be reached. ++ * ++ * **Details** ++ * ++ * `check` runs when a subscription is created and again before every POST. ++ * Resolving a host name needs the platform, so the default refuses every URL: ++ * a server that offers webhooks provides a guard that resolves the host and ++ * refuses addresses that are not globally routable. That check alone cannot ++ * stop DNS rebinding, so the `HttpClient` given to {@link layerEventWebhooks} ++ * must connect only to the address it validated, sending the original host ++ * name in `Host` and TLS SNI, and must not follow redirects. `allowsPlaintext` ++ * admits an `http:` URL, which only a local test setup should do. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const CallbackGuard = Context.Reference<{ ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++}>("effect/ai/McpServer/CallbackGuard", { ++ defaultValue: () => ({ ++ check: (url) => Effect.fail(new CallbackRejected({ message: `No callback guard admits ${url.host}` })) ++ }) ++}) ++ ++/** ++ * Webhook delivery for event types under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * Event types registered with a `stream` where this service is present also ++ * offer webhook delivery. `events/subscribe` validates the callback, verifies ++ * the endpoint with a challenge, and runs the event's `stream` for the ++ * subscription's lifetime, POSTing each occurrence with Standard Webhooks ++ * signatures, one at a time, retrying with backoff. Subscriptions live in ++ * memory: every grant is finite, between a minute and an hour, so a client ++ * refreshing from its cursor recreates what a restart lost. A failure of the ++ * stream, such as `Forbidden` when access is revoked, ends the subscription ++ * with a `terminated` envelope. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export class EventWebhooks extends Context.Service ++}>()("effect/ai/McpServer/EventWebhooks") {} ++ ++const webhooksState = new WeakMap() ++ ++/** ++ * Options for {@link layerEventWebhooks}. ++ * ++ * **Details** ++ * ++ * `principal` names the authenticated subject of an `events/subscribe` or ++ * `events/unsubscribe` request, read from the request's services. It fails ++ * with `Forbidden` for a caller that may not subscribe; webhook delivery ++ * requires an authenticated principal. A subscription's identity is its ++ * principal, callback URL, event name and arguments, so the principal must ++ * stay the same across token refreshes. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventWebhooksOptions { ++ readonly principal: Effect.Effect ++} ++ ++/** ++ * Provides {@link EventWebhooks}, delivering through the given `HttpClient` ++ * and admitting callbacks through the current {@link CallbackGuard}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const layerEventWebhooks = ( ++ options: EventWebhooksOptions ++): Layer.Layer => ++ Layer.effect( ++ EventWebhooks, ++ Effect.gen(function*() { ++ const webhooks = yield* McpWebhooks.make({ ++ principal: options.principal, ++ guard: yield* CallbackGuard, ++ client: yield* HttpClient.HttpClient ++ }) ++ const service = EventWebhooks.of({ size: webhooks.size }) ++ webhooksState.set(service, webhooks) ++ return service ++ }).pipe( ++ Effect.provide( ++ Layer.mergeAll(Mac.layerWebCrypto, Digest.layerWebCrypto).pipe( ++ Layer.provideMerge(SecureRandom.layerWebCrypto) ++ ) ++ ) ++ ) ++ ) ++ + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/src/ai/internal/mcpCore.ts b/src/ai/internal/mcpCore.ts +index 643982d..d705160 100644 +--- a/src/ai/internal/mcpCore.ts ++++ b/src/ai/internal/mcpCore.ts +@@ -8,6 +8,8 @@ import * as Data from "../../Data.ts" + import * as Effect from "../../Effect.ts" + import type * as McpProtocol from "../McpProtocol.ts" + import * as McpSchema from "../McpSchema.ts" ++import type * as Stream from "../../Stream.ts" ++import type * as McpWebhooks from "./mcpWebhooks.ts" + + /** + * @internal +@@ -330,6 +332,123 @@ export interface SkillRegistration { + readonly directory: (uri: string) => ReadonlyArray | undefined + } + ++/** ++ * A failure an event handler reports to the client as a JSON-RPC error, such ++ * as `McpSchema.Forbidden` or `McpSchema.InvalidParams`. ++ * ++ * @internal ++ */ ++export interface EventFailure { ++ readonly code: number ++ readonly message: string ++ readonly data?: unknown ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollRequest { ++ readonly arguments: Readonly> ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * An occurrence with its payload already encoded for the wire. ++ * ++ * @internal ++ */ ++export interface EncodedEvent { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: Readonly> ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollOutcome { ++ readonly events: ReadonlyArray ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly hasMore: boolean ++ readonly nextPollMs: number ++} ++ ++/** ++ * @internal ++ */ ++export interface EventStreamRequest { ++ readonly arguments: Readonly> ++ // Set when the arguments were already decoded, as a webhook subscribe does first. ++ readonly decoded?: { readonly value: unknown } | undefined ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries after `notifications/events/active`: occurrences, ++ * a position checked without a match (carried by the next heartbeat), a gap ++ * (a fresh `active` with `truncated`), or a recoverable error. ++ * ++ * @internal ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EncodedEvent) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventFailure } ++ ++/** ++ * A push subscription the handler accepted. A failure of `items` ends it with ++ * `notifications/events/terminated`. ++ * ++ * @internal ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly items: Stream.Stream ++} ++ ++/** ++ * @internal ++ */ ++export interface EventRegistration { ++ readonly descriptor: McpSchema.EventDescriptor ++ readonly isVisible: (profile: NegotiatedProtocolProfile) => boolean ++ readonly visible?: Visible | undefined ++ // Set when webhook delivery is offered, which runs `stream`. ++ readonly webhooks?: McpWebhooks.Webhooks | undefined ++ readonly decodeArguments: (args: unknown) => Effect.Effect ++ readonly poll?: ++ | (( ++ request: EventPollRequest, ++ invocation: McpInvocation ++ ) => Effect.Effect) ++ | undefined ++ // Runs for the subscription's lifetime: `deliver` takes over once the ++ // handler accepts it, so a failure before that is the request's error. ++ readonly stream?: ++ | (( ++ request: EventStreamRequest, ++ invocation: McpInvocation, ++ deliver: (subscription: EventSubscription) => Effect.Effect ++ ) => Effect.Effect) ++ | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Events { ++ readonly register: (registration: EventRegistration) => Effect.Effect ++ readonly list: (invocation: McpInvocation) => Effect.Effect, RequestRejected> ++ readonly get: (name: string, invocation: McpInvocation) => Effect.Effect ++} ++ + /** + * @internal + */ +@@ -507,11 +626,13 @@ export interface McpCore { + readonly prompts: Prompts + readonly completions: Completions + readonly skills: Skills ++ readonly events: Events + readonly registrationPresence: Effect.Effect<{ + readonly tools: boolean + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +@@ -523,6 +644,12 @@ export interface McpCore { + */ + export type Visible = (invocation: McpInvocation) => Effect.Effect + ++/** ++ * @internal ++ */ ++export const eventNotFound = (name: string): McpSchema.NotFound => ++ new McpSchema.NotFound({ message: `Event '${name}' not found`, data: { kind: "event" } }) ++ + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a: string, b: string): boolean => { + const rootA = a.slice(0, -"/SKILL.md".length) +@@ -539,6 +666,7 @@ export const make: Effect.Effect = Effect.sync(() => { + const resourceTemplateRegistrations: Array = [] + const promptRegistrations = new Map() + const skillRegistrations = new Map() ++ const eventRegistrations = new Map() + const skillFiles = new Set() + const completionRegistrations = new Map< + string, +@@ -717,12 +845,28 @@ export const make: Effect.Effect = Effect.sync(() => { + }) + } + ++ const events: Events = { ++ register: (registration) => ++ Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration) ++ }), ++ list: (invocation) => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => ++ Effect.suspend(() => { ++ const registration = eventRegistrations.get(name) ++ return registration !== undefined && registration.isVisible(invocation.protocol) ++ ? Effect.succeed(registration) ++ : Effect.fail(eventNotFound(name)) ++ }) ++ } ++ + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })) + +- return { tools, resources, prompts, completions, skills, registrationPresence } ++ return { tools, resources, prompts, completions, skills, events, registrationPresence } + }) +diff --git a/src/ai/internal/mcpEvents.ts b/src/ai/internal/mcpEvents.ts +new file mode 100644 +index 0000000..54b2ca8 +--- /dev/null ++++ b/src/ai/internal/mcpEvents.ts +@@ -0,0 +1,315 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.ts" ++import * as Clock from "../../Clock.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Option from "../../Option.ts" ++import * as Queue from "../../Queue.ts" ++import * as Result from "../../Result.ts" ++import * as Rpc from "../../rpc/Rpc.ts" ++import * as RpcGroup from "../../rpc/RpcGroup.ts" ++import * as Schema from "../../Schema.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import * as McpProtocol from "./mcpProtocol.ts" ++import * as Stateless from "./mcpSchema/v2026_07_28.ts" ++ ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events" ++ ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = ( ++ extensions: Readonly> | undefined, ++ servesEvents: boolean ++): Readonly> | undefined => ++ servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions ++ ++const methodNotFound = (method: string) => ++ new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++ }) ++ ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core: McpCore.McpCore, method: string) => ++ Effect.flatMap( ++ core.registrationPresence, ++ (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method)) ++ ) ++ ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value: PublicMcpSchema.EventDelivery) => ++ new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++ }) ++ ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++ ++const optional = Stateless.optional ++const Cursor = Schema.NullOr(Schema.String) ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) ++ ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) {} ++ ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++} ++ ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++ }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), ++ [Stateless.UnknownObject] ++ ), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs ++ extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) ++{} ++ ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make( ++ EventsActiveNotification, ++ EventsEventNotification, ++ EventsHeartbeatNotification, ++ EventsErrorNotification, ++ EventsTerminatedNotification ++) {} ++ ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++ ++const DEFAULT_HEARTBEAT_MS = 30_000 ++const MIN_HEARTBEAT_MS = 1_000 ++const MAX_HEARTBEAT_MS = 300_000 ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16 ++ ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested: number | undefined): number => ++ Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)) ++ ++const isJson = Schema.is(Schema.Json) ++ ++/** ++ * @internal ++ */ ++export const wireError = (failure: McpCore.EventFailure): Stateless.McpError => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}) ++ ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function*(options: { ++ readonly name: string ++ readonly subscription: McpCore.EventSubscription ++ readonly heartbeatMs: number ++ readonly send: (tag: string, payload: Readonly>) => Effect.Effect ++}) { ++ const { heartbeatMs, name, subscription } = options ++ let cursor = subscription.cursor ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0 ++ const send = (tag: string, payload: Readonly>) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at ++ })) ++ const active = (truncated: boolean) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }) ++ yield* active(subscription.truncated) ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }) ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)) ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result) ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }) ++ } ++ return ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }) ++ continue ++ } ++ const item = next.success.value ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor ++ const { _meta, _tag, ...occurrence } = item ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }) ++ break ++ } ++ case "Position": { ++ cursor = item.cursor ++ break ++ } ++ case "Gap": { ++ cursor = item.cursor ++ yield* active(true) ++ break ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }) ++ break ++ } ++ } ++ } ++}, Effect.scoped) +diff --git a/src/ai/internal/mcpProtocol.ts b/src/ai/internal/mcpProtocol.ts +index 5393651..f40915b 100644 +--- a/src/ai/internal/mcpProtocol.ts ++++ b/src/ai/internal/mcpProtocol.ts +@@ -484,6 +484,7 @@ export interface HandlerInstallationContext { + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +diff --git a/src/ai/internal/mcpProtocol/v2026_07_28.ts b/src/ai/internal/mcpProtocol/v2026_07_28.ts +index a701ec8..8e4b36a 100644 +--- a/src/ai/internal/mcpProtocol/v2026_07_28.ts ++++ b/src/ai/internal/mcpProtocol/v2026_07_28.ts +@@ -22,6 +22,7 @@ import type * as Types from "../../../Types.ts" + import type * as PublicMcpProtocol from "../../McpProtocol.ts" + import * as PublicMcpSchema from "../../McpSchema.ts" + import * as McpCore from "../mcpCore.ts" ++import * as McpEvents from "../mcpEvents.ts" + import * as McpProtocol from "../mcpProtocol.ts" + import * as McpSchema from "../mcpSchema/v2026_07_28.ts" + import * as McpSkills from "../mcpSkills.ts" +@@ -344,7 +345,11 @@ const unsupported = ( + /** + * @internal + */ +-export const handlerRpcs = McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs) ++export const handlerRpcs = McpSchema.ClientRequestRpcs.merge( ++ McpSchema.ClientNotificationRpcs, ++ McpSkills.StatelessRpcs, ++ McpEvents.StatelessRpcs ++) + + /** + * @internal +@@ -370,6 +375,10 @@ export const makeHandlers = ( + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult) + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult) + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult) ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult) ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult) ++ const decodeSubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.SubscribeEvents.successSchema) ++ const decodeUnsubscribeEventsResult = Schema.decodeUnknownEffect(McpEvents.UnsubscribeEvents.successSchema) + const sendNotification = context.sendNotification + const supportsSubscriptions = sendNotification !== undefined + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -384,8 +393,14 @@ export const makeHandlers = ( + } + const getDiscovery = Effect.map(context.registrationPresence, (presence) => { + const capabilities: Types.Mutable = { completions: {}, logging: {} } +- const declared = McpSkills.declareExtension(extensions, presence.skills) ++ const declared = McpEvents.declareExtension( ++ McpSkills.declareExtension(extensions, presence.skills), ++ presence.events ++ ) + if (declared !== undefined) capabilities.extensions = declared ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They look for a top-level `events` capability instead of the extension. ++ if (presence.events) capabilities.events = {} + if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions } + if (presence.resources) { + capabilities.resources = { listChanged: supportsSubscriptions, subscribe: supportsSubscriptions } +@@ -393,6 +408,30 @@ export const makeHandlers = ( + if (presence.prompts) capabilities.prompts = { listChanged: supportsSubscriptions } + return { supportedVersions: context.supportedVersions, capabilities, serverInfo: context.serverInfo } + }) ++ const requireEvents = (method: string) => ++ McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))) ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function*( ++ registration: McpCore.EventRegistration, ++ args: unknown ++ ) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest) ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers) ++ } ++ }) ++ // Webhook delivery runs the event's push stream, so it needs both. ++ const webhookRegistration = Effect.fnUntraced(function*(method: string, name: string, args: unknown) { ++ yield* requireEvents(method) ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(name, invocation) ++ const { stream, webhooks } = registration ++ if (webhooks === undefined || stream === undefined) { ++ return yield* McpEvents.unsupportedDelivery("webhook") ++ } ++ yield* validateEventHeaders(registration, args) ++ return { invocation, stream, webhooks, decodeArguments: registration.decodeArguments } ++ }) + const requireSkills = (method: string) => + McpSkills.requireSkills(core, method).pipe( + Effect.catch((error) => failWithHttpStatus(404, error)) +@@ -728,6 +767,121 @@ export const makeHandlers = ( + const result = yield* projectCompleteResult({ ...cacheHint("skills"), resources }, context.serverInfo) + return yield* decodeReadResourceDirectoryResult(result) + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function*(request: typeof McpEvents.ListEvents.payloadSchema.Type) { ++ yield* requireEvents("events/list") ++ yield* McpProtocol.rejectCursor(request.cursor) ++ const events = yield* core.events.list(yield* getInvocation) ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push") ++ return delivery.length === 0 ? [] : [{ ...event, delivery }] ++ }) ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo) ++ return yield* decodeListEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function*(request: typeof McpEvents.PollEvents.payloadSchema.Type) { ++ yield* requireEvents("events/poll") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation) ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => ++ omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ }) ++ ), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo) ++ return yield* decodePollEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function*( ++ request: typeof McpEvents.StreamEvents.payloadSchema.Type, ++ { client, requestId }: { readonly client: Rpc.ServerClient; readonly requestId: RpcMessage.RequestId } ++ ) { ++ yield* requireEvents("events/stream") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId } ++ const send = (tag: string, payload: Readonly>) => ++ sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }) ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs) ++ yield* Effect.raceFirst( ++ registration.stream( ++ { arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send }) ++ ), ++ context.awaitClientEnd ?? Effect.never ++ ) ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo) ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }) ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function*(request: typeof McpEvents.SubscribeEvents.payloadSchema.Type) { ++ const { decodeArguments, invocation, stream, webhooks } = yield* webhookRegistration( ++ "events/subscribe", ++ request.name, ++ request.arguments ++ ) ++ const args = request.arguments ?? {} ++ const cursor = request.cursor ?? null ++ const subscribed = yield* webhooks.subscribe({ ++ name: request.name, ++ arguments: args, ++ delivery: request.delivery, ++ cursor, ++ ttlMs: request.ttlMs, ++ decode: decodeArguments(args), ++ open: (decoded, deliver) => ++ stream( ++ { arguments: args, decoded: { value: decoded }, cursor, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ deliver ++ ) ++ }) ++ const result = yield* projectCompleteResult(omitUndefined({ ...subscribed }), context.serverInfo) ++ return yield* decodeSubscribeEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function*( ++ request: typeof McpEvents.UnsubscribeEvents.payloadSchema.Type ++ ) { ++ const { webhooks } = yield* webhookRegistration("events/unsubscribe", request.name, request.arguments) ++ yield* webhooks.unsubscribe({ ++ name: request.name, ++ arguments: request.arguments ?? {}, ++ delivery: request.delivery ++ }) ++ const result = yield* projectCompleteResult({}, context.serverInfo) ++ return yield* decodeUnsubscribeEventsResult(result) ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function*( + _request: typeof McpSchema.CancelledNotification.payloadSchema.Type + ) { +@@ -751,10 +905,10 @@ const runtime = { + export const protocol = McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/src/ai/internal/mcpRuntime.ts b/src/ai/internal/mcpRuntime.ts +index 9d4c96e..0afe3ed 100644 +--- a/src/ai/internal/mcpRuntime.ts ++++ b/src/ai/internal/mcpRuntime.ts +@@ -53,6 +53,10 @@ const routingNameKey = (method: string): "name" | "uri" | undefined => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name" + case "resources/read": + return "uri" +@@ -319,7 +323,13 @@ export const make = Effect.fnUntraced(function*( + if (nameKey !== undefined) { + const name = asRecord(inputRecord?.params)?.[nameKey] + const header = headers[MCP_NAME_HEADER] +- if (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) { ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They send no Mcp-Name on these; one they do send must still match. ++ const optional = header === undefined && (method === "events/subscribe" || method === "events/unsubscribe") ++ if ( ++ !optional && ++ (typeof name !== "string" || header === undefined || McpProtocol.decodeRoutingHeader(header) !== name) ++ ) { + return headerMismatch("Mcp-Name header does not match request parameters") + } + } +@@ -479,7 +489,9 @@ export const make = Effect.fnUntraced(function*( + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && ++ (input.method === "subscriptions/listen" || input.method === "events/stream") + } + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/src/ai/internal/mcpWebhooks.ts b/src/ai/internal/mcpWebhooks.ts +new file mode 100644 +index 0000000..5b53d08 +--- /dev/null ++++ b/src/ai/internal/mcpWebhooks.ts +@@ -0,0 +1,692 @@ ++/** ++ * Webhook delivery for the Events extension (SEP-3415): `events/subscribe` ++ * validation, subscription identity, Standard Webhooks signing, the endpoint ++ * verification handshake and the delivery loop. ++ * ++ * Subscriptions live in memory. Every grant is finite, so a subscription lost ++ * in a restart comes back on the client's next refresh, from its cursor. ++ */ ++import * as Clock from "../../Clock.ts" ++import * as Digest from "../../crypto/Digest.ts" ++import * as Mac from "../../crypto/Mac.ts" ++import * as SecureRandom from "../../crypto/SecureRandom.ts" ++import * as Deferred from "../../Deferred.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Base64 from "../../encoding/Base64.ts" ++import * as Base64Url from "../../encoding/Base64Url.ts" ++import * as Fiber from "../../Fiber.ts" ++import * as FetchHttpClient from "../../http/FetchHttpClient.ts" ++import * as HttpClient from "../../http/HttpClient.ts" ++import * as HttpClientRequest from "../../http/HttpClientRequest.ts" ++import type * as HttpClientResponse from "../../http/HttpClientResponse.ts" ++import * as Option from "../../Option.ts" ++import * as Result from "../../Result.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import { wireError } from "./mcpEvents.ts" ++ ++const MINUTE_MS = 60_000 ++/** @internal */ ++export const MIN_TTL_MS = MINUTE_MS ++// Short grants because subscriptions live in memory: a restart loses them until the next refresh. ++/** @internal */ ++export const MAX_TTL_MS = 60 * MINUTE_MS ++/** @internal */ ++export const DEFAULT_TTL_MS = 15 * MINUTE_MS ++/** @internal */ ++export const MAX_ATTEMPTS = 5 ++// Retries wait 30 s, 1, 2 and 4 minutes: about 7.5 minutes in all. ++const FIRST_RETRY_MS = 30_000 ++const REQUEST_TIMEOUT_MS = 10_000 ++// Deliveries signed with the old secret before a rotation still verify for this long. ++const ROTATION_GRACE_MS = 5 * MINUTE_MS ++const VERIFIED_FOR_MS = MAX_TTL_MS ++// A failed challenge is answered from here, so repeated subscribes cannot flood the endpoint. ++const FAILED_FOR_MS = 5 * MINUTE_MS ++// Verification POSTs one destination host receives per minute, across all principals. ++const VERIFICATIONS_PER_HOST_PER_MINUTE = 10 ++const MAX_SUBSCRIPTIONS_PER_PRINCIPAL = 100 ++// A verification reads this many bytes of the response at most; a delivery reads none. ++const MAX_CHALLENGE_RESPONSE_BYTES = 8_192 ++const SECRET_PREFIX = "whsec_" ++ ++/** ++ * The fixed categories `deliveryStatus.lastError` and `CallbackEndpointError` ++ * report; never the endpoint's own response. ++ * ++ * @internal ++ */ ++export type FailureCategory = ++ | "connection_refused" ++ | "timeout" ++ | "tls_error" ++ | "http_4xx" ++ | "http_5xx" ++ | "challenge_failed" ++ ++/** ++ * @internal ++ */ ++export interface Guard { ++ readonly check: (url: URL) => Effect.Effect ++ readonly allowsPlaintext?: ((url: URL) => boolean) | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Options { ++ readonly principal: Effect.Effect ++ readonly guard: Guard ++ readonly client: HttpClient.HttpClient ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++ readonly cursor: string | null ++ readonly ttlMs?: number | null | undefined ++ // The event's argument decoder, run before the endpoint is contacted. ++ readonly decode: Effect.Effect ++ // Runs the event's stream for the subscription's lifetime, as push delivery does. ++ readonly open: ( ++ decoded: unknown, ++ deliver: (subscription: McpCore.EventSubscription) => Effect.Effect ++ ) => Effect.Effect ++} ++ ++/** ++ * @internal ++ */ ++export interface SubscribeResult { ++ readonly id: string ++ readonly refreshBefore: string ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly deliveryStatus?: { ++ readonly active: boolean ++ readonly lastDeliveryAt: string | null ++ readonly lastError: FailureCategory | null ++ } | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface UnsubscribeRequest { ++ readonly name: string ++ readonly arguments: Readonly> ++ readonly delivery: Readonly> ++} ++ ++/** ++ * @internal ++ */ ++export interface Webhooks { ++ readonly subscribe: ( ++ request: SubscribeRequest ++ ) => Effect.Effect ++ readonly unsubscribe: (request: UnsubscribeRequest) => Effect.Effect ++ readonly size: Effect.Effect ++} ++ ++interface Subscription { ++ readonly id: string ++ readonly principal: string ++ readonly url: URL ++ secret: string ++ key: Mac.Key ++ previous: { readonly key: Mac.Key; readonly until: number } | undefined ++ expiresAt: number ++ // Everything at or before it was acknowledged or given up on. ++ watermark: string | null ++ lastDeliveryAt: number | undefined ++ lastError: FailureCategory | undefined ++ fiber: Fiber.Fiber | undefined ++ // Completed when a refresh moves the deadline, so the expiry recomputes it. ++ deadlineMoved: Deferred.Deferred ++ // Where the event's stream started, or why it could not; a same-key refresh waits for it. ++ readonly accepted: Deferred.Deferred< ++ { readonly cursor: string | null; readonly truncated: boolean }, ++ McpCore.EventFailure | McpCore.RequestRejected ++ > ++ // After a gap whose envelope the endpoint never took: the cursors handed out since, any of ++ // which a refresh presents to say it saw past the gap. Until then every refresh is truncated. ++ cursorsSinceGap: Set | undefined ++} ++ ++type Outcome = ++ // `body` is read only for a verification, and is undefined when it was too long. ++ | { readonly _tag: "Delivered"; readonly body: string | undefined } ++ | { readonly _tag: "Failed"; readonly category: FailureCategory; readonly retryable: boolean } ++ ++const invalid = (message: string) => new PublicMcpSchema.InvalidParams({ message }) ++ ++/** ++ * The TTL granted for a suggested one: the default when none is suggested, and ++ * never unbounded, since subscriptions are not kept across restarts. ++ * ++ * @internal ++ */ ++export const grantTtl = (suggested: number | null | undefined): number => ++ suggested === undefined ++ ? DEFAULT_TTL_MS ++ : suggested === null ++ ? MAX_TTL_MS ++ : Math.min(MAX_TTL_MS, Math.max(MIN_TTL_MS, suggested)) ++ ++/** ++ * JSON with object keys sorted, so equal arguments serialize equally. ++ * ++ * @internal ++ */ ++export const canonicalJson = (value: unknown): string => { ++ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]` ++ if (typeof value === "object" && value !== null) { ++ const entries = Object.entries(value).filter(([, entry]) => entry !== undefined) ++ entries.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) ++ return `{${entries.map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}` ++ } ++ return JSON.stringify(value) ?? "null" ++} ++ ++const encoder = new TextEncoder() ++ ++const parseUrl = (value: unknown, guard: Guard) => { ++ if (typeof value !== "string") return Effect.fail(invalid("delivery.url is required")) ++ let url: URL ++ try { ++ url = new URL(value) ++ } catch { ++ return Effect.fail(invalid("delivery.url is not a valid URL")) ++ } ++ if (url.protocol !== "https:" && !(url.protocol === "http:" && guard.allowsPlaintext?.(url) === true)) { ++ return Effect.fail(invalid("delivery.url must use https")) ++ } ++ if (url.username !== "" || url.password !== "") { ++ return Effect.fail(invalid("delivery.url must not carry credentials")) ++ } ++ url.hash = "" ++ return Effect.succeed(url) ++} ++ ++const parseSecret = (value: unknown) => { ++ const fail = Effect.fail(invalid("delivery.secret must be whsec_ and the base64 of 24 to 64 random bytes")) ++ if (typeof value !== "string" || !value.startsWith(SECRET_PREFIX)) return fail ++ const bytes = Base64.decode(value.slice(SECRET_PREFIX.length)) ++ if (Result.isFailure(bytes) || bytes.success.length < 24 || bytes.success.length > 64) return fail ++ return Mac.key(Mac.hmacSha256, bytes.success).pipe(Effect.orDie, Effect.map((key) => ({ text: value, key }))) ++} ++ ++const statusCategory = (status: number): FailureCategory => (status >= 500 ? "http_5xx" : "http_4xx") ++ ++// Only codes and names are read, never what the endpoint sent. ++const transportCategory = (error: unknown): FailureCategory => { ++ let current: unknown = error ++ for (let depth = 0; depth < 8 && typeof current === "object" && current !== null; depth++) { ++ const code = (current as { readonly code?: unknown }).code ++ if (typeof code === "string" && /CERT|TLS|SSL/.test(code)) return "tls_error" ++ current = (current as { readonly cause?: unknown }).cause ?? ++ (current as { readonly reason?: unknown }).reason ++ } ++ return "connection_refused" ++} ++ ++// Stops pulling past the cap; closing the request's scope then aborts the rest. ++const readCapped = (response: HttpClientResponse.HttpClientResponse) => ++ Effect.suspend(() => { ++ const chunks: Array = [] ++ let total = 0 ++ let oversized = false ++ return response.stream.pipe( ++ Stream.takeWhile((chunk) => { ++ if (total + chunk.length > MAX_CHALLENGE_RESPONSE_BYTES) { ++ oversized = true ++ return false ++ } ++ total += chunk.length ++ chunks.push(chunk) ++ return true ++ }), ++ Stream.runDrain, ++ Effect.map(() => { ++ if (oversized) return undefined ++ const bytes = new Uint8Array(total) ++ let offset = 0 ++ for (const chunk of chunks) { ++ bytes.set(chunk, offset) ++ offset += chunk.length ++ } ++ return new TextDecoder().decode(bytes) ++ }) ++ ) ++ }) ++ ++const echoedChallenge = (body: string): string | undefined => { ++ try { ++ const parsed: unknown = JSON.parse(body) ++ const challenge = typeof parsed === "object" && parsed !== null ++ ? (parsed as { readonly challenge?: unknown }).challenge ++ : undefined ++ return typeof challenge === "string" ? challenge : undefined ++ } catch { ++ return undefined ++ } ++} ++ ++const callbackError = (category: FailureCategory) => ++ new PublicMcpSchema.CallbackEndpointError({ ++ message: `The callback endpoint failed verification: ${category}`, ++ data: { reason: category } ++ }) ++ ++const iso = (millis: number) => new Date(millis).toISOString() ++ ++/** ++ * @internal ++ */ ++export const make = Effect.fnUntraced(function*(options: Options) { ++ const scope = yield* Effect.scope ++ const mac = yield* Mac.Mac ++ const digest = yield* Digest.Digest ++ const random = yield* SecureRandom.SecureRandom ++ const { guard } = options ++ // Closing a request's scope aborts its body, so a delivery never downloads what the endpoint sends. ++ const client = HttpClient.withScope(options.client) ++ const subscriptions = new Map() ++ // Subscribes past the principal check that have not created their subscription yet. ++ const pending = new Map() ++ const verified = new Map() ++ const failedVerifications = new Map() ++ const verifying = new Map>() ++ const verificationsByHost = new Map>() ++ ++ const forget = (subscription: Subscription) => { ++ if (subscriptions.get(subscription.id) === subscription) subscriptions.delete(subscription.id) ++ } ++ ++ const subscriptionId = (principal: string, url: URL, name: string, args: unknown) => ++ digest.digestHex(Digest.sha256, encoder.encode(canonicalJson([principal, url.href, name, args]))).pipe( ++ Effect.map((hex) => `sub_${hex.slice(0, 32)}`) ++ ) ++ ++ // High entropy and unrelated to the eventId; a retry reuses it. ++ const messageId = (prefix: string) => ++ Effect.map(random.randomBytes(18), (bytes) => `${prefix}_${Base64Url.encode(bytes)}`) ++ ++ // Bridge for clients predating SEP-3415 (ChatGPT, @ai-sdk/mcp); drop per #41158. ++ // They require an event's webhook-id to equal its eventId. Both become this id, derived per ++ // subscription so two subscriptions to one URL never share it; poll and push keep the eventId. ++ const deliveryId = (subscription: Subscription, eventId: string) => ++ Effect.map( ++ digest.digest(Digest.sha256, encoder.encode(`${subscription.id}\0${eventId}`)), ++ (hash) => `evt_${Base64Url.encode(hash).slice(0, 22)}` ++ ) ++ ++ const MAX_CURSORS_SINCE_GAP = 1_024 ++ const advance = (subscription: Subscription, cursor: string | null) => { ++ subscription.watermark = cursor ++ const since = subscription.cursorsSinceGap ++ if (since === undefined) return ++ since.add(cursor) ++ if (since.size > MAX_CURSORS_SINCE_GAP) since.delete(since.values().next().value!) ++ } ++ ++ const sign = (keys: ReadonlyArray, webhookId: string, timestamp: number, body: string) => ++ Effect.forEach(keys, (key) => mac.sign(key, encoder.encode(`${webhookId}.${timestamp}.${body}`))).pipe( ++ Effect.orDie, ++ Effect.map((tags) => tags.map((tag) => `v1,${Base64.encode(tag)}`).join(" ")) ++ ) ++ ++ // One POST. The timestamp and signature are fresh on every attempt. ++ const send = Effect.fnUntraced(function*( ++ subscription: Subscription, ++ body: string, ++ webhookId: string, ++ readBody: boolean ++ ) { ++ const admitted = yield* Effect.result(guard.check(subscription.url)) ++ if (Result.isFailure(admitted)) { ++ return { _tag: "Failed", category: "connection_refused", retryable: true } satisfies Outcome ++ } ++ const now = yield* Clock.currentTimeMillis ++ const timestamp = Math.floor(now / 1000) ++ const previous = subscription.previous ++ const keys = previous !== undefined && now < previous.until ++ ? [subscription.key, previous.key] ++ : [subscription.key] ++ const request = HttpClientRequest.post(subscription.url).pipe( ++ HttpClientRequest.setHeaders({ ++ "webhook-id": webhookId, ++ "webhook-timestamp": String(timestamp), ++ "webhook-signature": yield* sign(keys, webhookId, timestamp, body), ++ "x-mcp-subscription-id": subscription.id ++ }), ++ HttpClientRequest.bodyText(body, "application/json") ++ ) ++ const outcome = yield* client.execute(request).pipe( ++ Effect.flatMap((response): Effect.Effect => { ++ if (response.status < 200 || response.status >= 300) { ++ return Effect.succeed({ ++ _tag: "Failed", ++ category: statusCategory(response.status), ++ retryable: response.status !== 410 && response.status !== 413 ++ }) ++ } ++ return readBody ++ ? Effect.map(readCapped(response), (text) => ({ _tag: "Delivered", body: text })) ++ : Effect.succeed({ _tag: "Delivered", body: undefined }) ++ }), ++ Effect.timeoutOption(Duration.millis(REQUEST_TIMEOUT_MS)), ++ Effect.scoped, ++ // `fetch` would follow a redirect itself; webhook delivery never does. ++ Effect.provideService(FetchHttpClient.RequestInit, { redirect: "manual" }), ++ // Trace ids stay inside: the endpoint belongs to someone else. ++ Effect.provideService(HttpClient.TracerPropagationEnabled, false), ++ Effect.catch((error) => ++ Effect.succeed(Option.some({ _tag: "Failed", category: transportCategory(error), retryable: true })) ++ ) ++ ) ++ return Option.getOrElse(outcome, (): Outcome => ({ _tag: "Failed", category: "timeout", retryable: true })) ++ }) ++ ++ // Retries with backoff; gives up after a 410, a 413 or the last attempt. True once delivered. ++ const deliver = Effect.fnUntraced(function*(subscription: Subscription, body: string, webhookId: string) { ++ for (let attempt = 1;; attempt++) { ++ // A subscription that ended may have been replaced under its id; this one speaks no longer. ++ const current = subscriptions.get(subscription.id) ++ if (current !== undefined && current !== subscription) return false ++ const startedAt = yield* Clock.currentTimeMillis ++ const outcome = yield* send(subscription, body, webhookId, false) ++ if (outcome._tag === "Delivered") { ++ subscription.lastDeliveryAt = yield* Clock.currentTimeMillis ++ subscription.lastError = undefined ++ return true ++ } ++ subscription.lastError = outcome.category ++ if (!outcome.retryable || attempt >= MAX_ATTEMPTS) return false ++ // Counted from the attempt's start, so a slow endpoint does not stretch the window. ++ const wait = startedAt + FIRST_RETRY_MS * 2 ** (attempt - 1) - (yield* Clock.currentTimeMillis) ++ if (wait > 0) yield* Effect.sleep(Duration.millis(wait)) ++ } ++ }) ++ ++ const control = (subscription: Subscription, type: string, fields: Readonly>) => ++ Effect.flatMap( ++ messageId(`msg_${type}`), ++ (webhookId) => deliver(subscription, JSON.stringify({ type, ...fields }), webhookId) ++ ) ++ ++ // One delivery in flight per subscription, so the watermark only moves forward ++ // once everything before it is resolved. ++ const run = (subscription: Subscription, name: string, events: McpCore.EventSubscription) => ++ events.items.pipe( ++ Stream.runForEach((item): Effect.Effect => { ++ switch (item._tag) { ++ case "Event": ++ return Effect.flatMap(deliveryId(subscription, item.eventId), (webhookId) => { ++ const body = JSON.stringify({ ++ eventId: webhookId, ++ name, ++ timestamp: item.timestamp, ++ data: item.data, ++ cursor: item.cursor, ++ ...(item._meta === undefined ? {} : { _meta: item._meta }) ++ }) ++ return deliver(subscription, body, webhookId) ++ }).pipe(Effect.andThen(Effect.sync(() => advance(subscription, item.cursor)))) ++ case "Position": ++ return Effect.sync(() => advance(subscription, item.cursor)) ++ case "Gap": ++ return control(subscription, "gap", { cursor: item.cursor }).pipe( ++ Effect.map((delivered) => { ++ if (!delivered) subscription.cursorsSinceGap = new Set() ++ advance(subscription, item.cursor) ++ }) ++ ) ++ case "Error": ++ // A webhook has no envelope for an error that leaves the subscription open. ++ return Effect.void ++ } ++ }), ++ // Ended before it says so, so a refresh meanwhile starts afresh instead of reporting it live. ++ Effect.catch((failure) => ++ Effect.suspend(() => { ++ forget(subscription) ++ return control(subscription, "terminated", { error: wireError(failure) }) ++ }) ++ ) ++ ) ++ ++ const expiry = (subscription: Subscription) => ++ Effect.gen(function*() { ++ while (true) { ++ const left = subscription.expiresAt - (yield* Clock.currentTimeMillis) ++ if (left <= 0) return forget(subscription) ++ yield* Effect.raceFirst(Effect.sleep(Duration.millis(left)), Deferred.await(subscription.deadlineMoved)) ++ } ++ }) ++ ++ const handshake = Effect.fnUntraced(function*(subscription: Subscription) { ++ const challenge = Base64Url.encode(yield* random.randomBytes(32)) ++ const outcome = yield* send( ++ subscription, ++ JSON.stringify({ type: "verification", challenge }), ++ yield* messageId("msg_verification"), ++ true ++ ) ++ if (outcome._tag === "Failed") return yield* Effect.fail(outcome.category) ++ const echoed = outcome.body === undefined ? undefined : echoedChallenge(outcome.body) ++ if (echoed === undefined || !Mac.timingSafeEqual(encoder.encode(echoed), encoder.encode(challenge))) { ++ return yield* Effect.fail("challenge_failed") ++ } ++ }) ++ ++ // Cached per (principal, url) either way; concurrent subscribes share one handshake. ++ const verify = Effect.fnUntraced(function*(subscription: Subscription) { ++ const key = JSON.stringify([subscription.principal, subscription.url.href]) ++ const now = yield* Clock.currentTimeMillis ++ for (const [entry, until] of verified) if (until <= now) verified.delete(entry) ++ for (const [entry, failure] of failedVerifications) if (failure.until <= now) failedVerifications.delete(entry) ++ if (verified.has(key)) return ++ const failure = failedVerifications.get(key) ++ if (failure !== undefined) return yield* callbackError(failure.category) ++ const inFlight = verifying.get(key) ++ if (inFlight !== undefined) return yield* Deferred.await(inFlight) ++ const host = subscription.url.hostname ++ const recent = (verificationsByHost.get(host) ?? []).filter((at) => at > now - MINUTE_MS) ++ if (recent.length >= VERIFICATIONS_PER_HOST_PER_MINUTE) { ++ verificationsByHost.set(host, recent) ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many callback verifications for this host", ++ data: { limit: "verifications", max: VERIFICATIONS_PER_HOST_PER_MINUTE } ++ }) ++ } ++ for (const [entry, times] of verificationsByHost) { ++ if (times.every((at) => at <= now - MINUTE_MS)) verificationsByHost.delete(entry) ++ } ++ verificationsByHost.set(host, [...recent, now]) ++ const done = Deferred.makeUnsafe() ++ verifying.set(key, done) ++ return yield* handshake(subscription).pipe( ++ Effect.tap(() => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ verified.set(key, at + VERIFIED_FOR_MS) ++ }) ++ ), ++ Effect.tapError((category) => ++ Effect.map(Clock.currentTimeMillis, (at) => { ++ failedVerifications.set(key, { until: at + FAILED_FOR_MS, category }) ++ }) ++ ), ++ Effect.mapError(callbackError), ++ Effect.onExit((exit) => ++ Effect.sync(() => { ++ verifying.delete(key) ++ Deferred.doneUnsafe(done, exit) ++ }) ++ ) ++ ) ++ }) ++ ++ // A caller that joins while the first subscribe's stream is opening waits for it and gets ++ // where it started; one whose subscription went away meanwhile subscribes afresh. ++ const refresh = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ subscription: Subscription, ++ secret: { readonly text: string; readonly key: Mac.Key }, ++ expiresAt: number, ++ now: number ++ ): Effect.fn.Return { ++ const opening = !Deferred.isDoneUnsafe(subscription.accepted) ++ const start = yield* Deferred.await(subscription.accepted) ++ if (subscriptions.get(subscription.id) !== subscription) return yield* subscribe(request) ++ if (subscription.secret !== secret.text) { ++ subscription.previous = { key: subscription.key, until: now + ROTATION_GRACE_MS } ++ subscription.secret = secret.text ++ subscription.key = secret.key ++ } ++ subscription.expiresAt = expiresAt ++ const moved = subscription.deadlineMoved ++ subscription.deadlineMoved = Deferred.makeUnsafe() ++ Deferred.doneUnsafe(moved, Effect.void) ++ if (opening) return { id: subscription.id, refreshBefore: iso(expiresAt), ...start } ++ // Kept until the client shows a cursor from past the gap, so a lost response hides nothing. ++ const since = subscription.cursorsSinceGap ++ if (since !== undefined && since.has(request.cursor)) subscription.cursorsSinceGap = undefined ++ const truncated = subscription.cursorsSinceGap !== undefined ++ return { ++ id: subscription.id, ++ refreshBefore: iso(expiresAt), ++ cursor: subscription.watermark, ++ truncated, ++ deliveryStatus: { ++ active: true, ++ lastDeliveryAt: subscription.lastDeliveryAt === undefined ? null : iso(subscription.lastDeliveryAt), ++ lastError: subscription.lastError ?? null ++ } ++ } satisfies SubscribeResult ++ }) ++ ++ const subscribe: Webhooks["subscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const mode = request.delivery.mode ++ if (mode !== undefined && mode !== "webhook") return yield* invalid("delivery.mode must be 'webhook'") ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const secret = yield* parseSecret(request.delivery.secret) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const now = yield* Clock.currentTimeMillis ++ const expiresAt = now + grantTtl(request.ttlMs) ++ const live = subscriptions.get(id) ++ if (live !== undefined) return yield* refresh(request, live, secret, expiresAt, now) ++ // The slot is taken before anything asynchronous, so concurrent subscribes cannot pass the cap. ++ let held = pending.get(principal) ?? 0 ++ for (const subscription of subscriptions.values()) if (subscription.principal === principal) held++ ++ if (held >= MAX_SUBSCRIPTIONS_PER_PRINCIPAL) { ++ return yield* new PublicMcpSchema.ResourceExhausted({ ++ message: "Too many webhook subscriptions", ++ data: { limit: "subscriptions", max: MAX_SUBSCRIPTIONS_PER_PRINCIPAL } ++ }) ++ } ++ pending.set(principal, (pending.get(principal) ?? 0) + 1) ++ let reserved = true ++ const release = () => { ++ if (!reserved) return ++ reserved = false ++ const left = (pending.get(principal) ?? 1) - 1 ++ if (left === 0) pending.delete(principal) ++ else pending.set(principal, left) ++ } ++ return yield* create(request, { principal, url, secret, id, expiresAt, now, release }).pipe( ++ Effect.ensuring(Effect.sync(release)) ++ ) ++ }) ++ ++ const create = Effect.fnUntraced(function*( ++ request: SubscribeRequest, ++ { expiresAt, id, now, principal, release, secret, url }: { ++ readonly principal: string ++ readonly url: URL ++ readonly secret: { readonly text: string; readonly key: Mac.Key } ++ readonly id: string ++ readonly expiresAt: number ++ readonly now: number ++ readonly release: () => void ++ } ++ ) { ++ // One answer whether the host is private or does not resolve, so it reveals neither. ++ yield* Effect.mapError(guard.check(url), () => invalid("delivery.url is not allowed")) ++ const subscription: Subscription = { ++ id, ++ principal, ++ url, ++ secret: secret.text, ++ key: secret.key, ++ previous: undefined, ++ expiresAt, ++ watermark: request.cursor, ++ lastDeliveryAt: undefined, ++ lastError: undefined, ++ fiber: undefined, ++ deadlineMoved: Deferred.makeUnsafe(), ++ accepted: Deferred.makeUnsafe(), ++ cursorsSinceGap: undefined ++ } ++ const decoded = yield* request.decode ++ yield* verify(subscription) ++ // A concurrent subscribe for the same key may have finished while this one verified. ++ const raced = subscriptions.get(id) ++ if (raced !== undefined) { ++ release() ++ return yield* refresh(request, raced, secret, expiresAt, now) ++ } ++ release() ++ subscriptions.set(id, subscription) ++ const { accepted } = subscription ++ const lifetime = request.open(decoded, (events) => ++ Effect.suspend(() => { ++ subscription.watermark = events.cursor ++ return Deferred.succeed(accepted, { cursor: events.cursor, truncated: events.truncated }) ++ }).pipe(Effect.andThen(run(subscription, request.name, events))) ++ ).pipe( ++ Effect.tapError((failure) => Deferred.fail(accepted, failure)), ++ Effect.raceFirst(expiry(subscription)), ++ Effect.ignore, ++ Effect.ensuring(Effect.suspend(() => { ++ forget(subscription) ++ return Deferred.fail(accepted, new PublicMcpSchema.InternalError({ message: "The subscription ended" })) ++ })) ++ ) ++ // Forked from the request, so the event's stream keeps the request's services. ++ subscription.fiber = yield* Effect.forkIn(lifetime, scope) ++ const start = yield* Deferred.await(accepted) ++ return { id, refreshBefore: iso(expiresAt), cursor: start.cursor, truncated: start.truncated } ++ }) ++ ++ const unsubscribe: Webhooks["unsubscribe"] = Effect.fnUntraced(function*(request) { ++ const principal = yield* options.principal ++ const url = yield* parseUrl(request.delivery.url, guard) ++ const id = yield* subscriptionId(principal, url, request.name, request.arguments) ++ const subscription = subscriptions.get(id) ++ if (subscription === undefined) { ++ return yield* new PublicMcpSchema.NotFound({ ++ message: "No webhook subscription matches", ++ data: { kind: "subscription" } ++ }) ++ } ++ subscriptions.delete(id) ++ if (subscription.fiber !== undefined) yield* Fiber.interrupt(subscription.fiber) ++ }) ++ ++ return { ++ subscribe, ++ unsubscribe, ++ size: Effect.sync(() => subscriptions.size) ++ } satisfies Webhooks ++}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 93627e4c0e561..7bcfe97d5747e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -362,7 +362,7 @@ overrides: packageExtensionsChecksum: sha256-18pwcgTDbqYFYAzCw8OfBYuC2btyq6aJSLhE/gjTJb4= -pnpmfileChecksum: sha256-h8NLkl2dhhbQKbAHnoo4rQ3tYV96igLQxJ7la6dsbSc= +pnpmfileChecksum: sha256-G0L7+qfid3Wo9BlLIlMyF/+fqBnAnqHKSe0HlWAtlg8= patchedDependencies: '@alchemy.run/test@2.0.0-beta.85': 29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e @@ -372,6 +372,7 @@ patchedDependencies: '@effect/vitest@4.1.5': dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 + '@legendapp/list@3.7.3': 85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4 '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': 7edcdd484a99c7ec0b2667499c4cb21d113ec9bea1f8570c0b0a030d33bbf1cd '@react-native-menu/menu@2.0.0': 6872ba71b9847c5a0210b1b896923dadc3860faedfe28d9f062bcedfe786ef1d @@ -379,6 +380,7 @@ patchedDependencies: alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 + effect@4.1.5: 24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28 electron-updater@6.8.9: 91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155 expo-audio@58.0.11: 92414572bf24ffd0c45de44c45f11f6c48bc0af13b8b9a56f77a67bc0e915c1e expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 @@ -436,7 +438,7 @@ importers: version: 0.15.4 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@napi-rs/keyring': specifier: ^1.3.0 version: 1.3.0 @@ -460,7 +462,7 @@ importers: version: 0.10.2(patch_hash=cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) electron: specifier: 44.10.1 version: 44.10.1(supports-color@8.1.1) @@ -491,7 +493,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -552,7 +554,7 @@ importers: version: 0.4.4(patch_hash=7a808b92da8460750b85818552e13be3fb73d111691c7db76965970351e124e4)(expo@58.0.23)(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)(typescript@6.0.3) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0) '@expo-google-fonts/dm-sans': specifier: ^0.4.2 version: 0.4.2 @@ -576,7 +578,7 @@ importers: version: 5.4.6 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(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) + version: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(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) '@material/material-color-utilities': specifier: 0.3.0 version: 0.3.0 @@ -630,7 +632,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) expo: specifier: 58.0.23 version: 58.0.23(d226faf1ca90e630d8c56a2108dee32d) @@ -817,10 +819,10 @@ importers: version: 7.29.7(supports-color@8.1.1) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) @@ -862,10 +864,10 @@ importers: version: 1.4.2(patch_hash=d9747bbf2d8fa7529b74b690087b70b3b2662fcba0d4d3148afc3b956171b54a)(zod@4.6.7) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/platform-node-shared': specifier: 4.1.5 - version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) + version: 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) '@ff-labs/fff-node': specifier: 0.11.0 version: 0.11.0(patch_hash=93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252) @@ -946,7 +948,7 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -986,10 +988,10 @@ importers: devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@handy-computer/models': specifier: 0.2.3 version: 0.2.3 @@ -1094,13 +1096,13 @@ importers: version: 3.2.2(react@19.3.0) '@effect/atom-react': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0) '@fontsource-variable/inter': specifier: ^5.3.0 version: 5.3.0 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(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) + version: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(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) '@noble/hashes': specifier: 'catalog:' version: 1.8.0 @@ -1110,6 +1112,9 @@ importers: '@pierre/trees': specifier: 1.0.0-beta.6 version: 1.0.0-beta.6(@pierre/theme@2.0.0)(@shikijs/themes@4.2.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)(shiki@4.2.0) + '@pierre/words': + specifier: file:deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz + version: file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz(@pierre/highlights@0.5.1)(react@19.3.0) '@t3tools/client-runtime': specifier: workspace:* version: link:../../packages/client-runtime @@ -1196,7 +1201,7 @@ importers: version: 3.4.17 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) entities: specifier: 8.1.0 version: 8.1.0 @@ -1230,39 +1235,21 @@ importers: lucide-react: specifier: ^0.564.0 version: 0.564.0(react@19.3.0) - mdast-util-from-markdown: - specifier: ^2.0.3 - version: 2.0.3(supports-color@8.1.1) - micromark-util-combine-extensions: - specifier: ^2.0.1 - version: 2.0.1 pdfjs-dist: specifier: 6.4.299 version: 6.4.299 pele: specifier: 'catalog:' version: 1.8.0 + property-information: + specifier: ^7.2.0 + version: 7.2.0 react: specifier: 'catalog:' version: 19.3.0 react-dom: specifier: 'catalog:' version: 19.3.0(react@19.3.0) - react-markdown: - specifier: ^10.1.0 - version: 10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1) - remark-gfm: - specifier: 'catalog:' - version: 4.0.1(supports-color@8.1.1) - remark-math: - specifier: 6.0.0 - version: 6.0.0(supports-color@8.1.1) - remark-parse: - specifier: 'catalog:' - version: 11.0.0(supports-color@8.1.1) - remark-rehype: - specifier: 'catalog:' - version: 11.1.2 saxes: specifier: 6.0.0 version: 6.0.0 @@ -1275,25 +1262,19 @@ importers: tiff: specifier: 7.1.3 version: 7.1.3 - unified: - specifier: 'catalog:' - version: 11.0.5 use-sync-external-store: specifier: ^1.6.0 version: 1.6.0(react@19.3.0) - vfile: - specifier: ^6.0.3 - version: 6.0.3 zustand: specifier: ^5.0.11 version: 5.0.14(@types/react@19.3.0)(react@19.3.0)(use-sync-external-store@1.6.0(react@19.3.0)) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@tailwindcss/vite': specifier: 4.3.3 version: 4.3.3(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)) @@ -1312,9 +1293,6 @@ importers: '@types/hast': specifier: ^3.0.4 version: 3.0.5 - '@types/mdast': - specifier: ^4.0.4 - version: 4.0.4 '@types/react': specifier: 'catalog:' version: 19.3.0 @@ -1342,9 +1320,6 @@ importers: 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 oxc-transform-react: specifier: ~0.152.0 version: 0.152.0 @@ -1365,7 +1340,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../packages/contracts @@ -1377,11 +1352,11 @@ importers: version: link:../packages/shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1393,28 +1368,28 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) + version: 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) '@alchemy.run/drizzle': specifier: 'catalog:' - version: 2.0.0-beta.85(aaf71186a61e3f73fb98ecfca2947754) + version: 2.0.0-beta.85(5cde798e96ab6d44cdc28240628f10b1) '@alchemy.run/planetscale': specifier: 'catalog:' - version: 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) + version: 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) '@clerk/backend': specifier: 3.27.0 version: 3.27.0(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@distilled.cloud/cloudflare': specifier: 'catalog:' - version: 1.0.0-rc.18(effect@4.1.5) + version: 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/sql-pg': specifier: 4.1.5 - version: 4.1.5(effect@4.1.5) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/sql-sqlite-do': specifier: 'catalog:' - version: 4.1.5(effect@4.1.5) + version: 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@noble/curves': specifier: 'catalog:' version: 1.9.1 @@ -1432,26 +1407,26 @@ importers: version: link:../../packages/shared alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) drizzle-orm: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + version: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@alchemy.run/test': specifier: 'catalog:' - version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(adf93af6036c4c597e35df2cca6d42d0) + version: 2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(a619c060a1b8ed45ad4914f1f8e44c19) '@cloudflare/workers-types': specifier: ^4.20260601.1 version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@electric-sql/pglite': specifier: 0.3.15 version: 0.3.15 @@ -1460,7 +1435,7 @@ importers: version: 24.12.4 drizzle-kit: specifier: 1.0.0-rc.5 - version: 1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)) + version: 1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809) vite: specifier: npm:@voidzero-dev/vite-plus-core@1.4.0 version: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' @@ -1472,16 +1447,16 @@ importers: dependencies: '@alchemy.run/axiom': specifier: 'catalog:' - version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) + version: 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@alchemy.run/cloudflare': specifier: 'catalog:' - version: 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) + version: 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) alchemy: specifier: 2.0.0-beta.85 - version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + version: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) jose: specifier: 'catalog:' version: 6.2.2 @@ -1491,10 +1466,10 @@ importers: version: 4.20260604.1 '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1509,14 +1484,14 @@ importers: version: 1.89.0 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1573,38 +1548,38 @@ importers: version: link:../source-control-definitions effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) gt-i18n: specifier: 1.0.40 version: 1.0.40 jszip: specifier: 3.10.1 version: 3.10.1 - remark-gfm: - specifier: 'catalog:' - version: 4.0.1(supports-color@8.1.1) - remark-parse: - specifier: 'catalog:' - version: 11.0.0(supports-color@8.1.1) three: specifier: 0.180.0 version: 0.180.0 unbash: specifier: ^5.0.0 version: 5.0.0 - unified: - specifier: 'catalog:' - version: 11.0.5 devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/mdast': specifier: ^4.0.4 version: 4.0.4 '@types/three': specifier: 0.180.0 version: 0.180.0 + remark-gfm: + specifier: 'catalog:' + version: 4.0.1(supports-color@8.1.1) + remark-parse: + specifier: 'catalog:' + version: 11.0.0(supports-color@8.1.1) + unified: + specifier: 'catalog:' + version: 11.0.5 vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1613,11 +1588,11 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) vite-plus: specifier: 1.4.0 version: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) @@ -1626,17 +1601,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1648,17 +1623,17 @@ importers: dependencies: effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/openapi-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1676,14 +1651,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1707,14 +1682,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1744,14 +1719,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1775,14 +1750,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -1806,7 +1781,7 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) jsonc-parser: specifier: 3.3.1 version: 3.3.1 @@ -1816,10 +1791,10 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1846,14 +1821,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1883,14 +1858,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1920,14 +1895,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1957,14 +1932,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -1982,7 +1957,7 @@ importers: version: 1.15.13 '@opencode/client': specifier: 2.0.28 - version: 2.0.28(effect@4.1.5) + version: 2.0.28(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@opencode/protocol': specifier: 2.0.28 version: 2.0.28 @@ -2000,14 +1975,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2031,14 +2006,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/provider-testing': specifier: workspace:* version: link:../provider-testing @@ -2053,7 +2028,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2065,11 +2040,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2084,14 +2059,14 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2124,14 +2099,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2152,7 +2127,7 @@ importers: version: link:../contracts effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ffi-rs: specifier: 1.3.2 version: 1.3.2 @@ -2162,6 +2137,9 @@ importers: gt-i18n: specifier: 1.0.40 version: 1.0.40 + hast-util-sanitize: + specifier: ^5.0.2 + version: 5.0.2 mdast-util-directive: specifier: 'catalog:' version: 3.1.0(supports-color@8.1.1) @@ -2213,16 +2191,22 @@ importers: devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + '@types/hast': + specifier: ^3.0.5 + version: 3.0.5 '@types/mdast': specifier: ^4.0.4 version: 4.0.4 '@types/node': specifier: 24.12.4 version: 24.12.4 + hast-util-to-html: + specifier: ^9.0.5 + version: 9.0.5 micromark-util-types: specifier: 'catalog:' version: 2.0.2 @@ -2246,14 +2230,14 @@ importers: version: 8.0.3 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2280,14 +2264,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2308,11 +2292,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2324,7 +2308,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2339,11 +2323,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2397,14 +2381,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2431,11 +2415,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2450,7 +2434,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2465,17 +2449,17 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) yaml: specifier: ^2.9.0 version: 2.9.0 devDependencies: '@effect/graphql-generator': specifier: 'catalog:' - version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5) + version: 4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2499,14 +2483,14 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2530,11 +2514,11 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@t3tools/source-control-testing': specifier: workspace:* version: link:../source-control-testing @@ -2549,7 +2533,7 @@ importers: dependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@t3tools/contracts': specifier: workspace:* version: link:../contracts @@ -2561,7 +2545,7 @@ importers: version: link:../source-control-core effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@types/node': specifier: 24.12.4 @@ -2577,14 +2561,14 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2602,11 +2586,11 @@ importers: version: link:../shared effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/node': specifier: 24.12.4 version: 24.12.4 @@ -2624,7 +2608,7 @@ importers: version: 0.15.5(e2e@0.23.0) '@effect/platform-node': specifier: 4.1.5 - version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + version: 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) '@electron/asar': specifier: ^4.3.0 version: 4.3.0 @@ -2648,7 +2632,7 @@ importers: version: 0.23.0 effect: specifier: 4.1.5 - version: 4.1.5 + version: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) playwright-core: specifier: 1.64.1 version: 1.64.1 @@ -2664,7 +2648,7 @@ importers: devDependencies: '@effect/vitest': specifier: 4.1.5 - version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + version: 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) '@types/plist': specifier: 'catalog:' version: 3.0.5 @@ -6493,6 +6477,18 @@ packages: react: ^18.3.1 || ^19.0.0 react-dom: ^18.3.1 || ^19.0.0 + '@pierre/words@file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz': + resolution: {integrity: sha512-EuIvU8imMY3c/deOHm9/gEh9VJga8R7jjWiIKfjKHbDXjgMo/O3NDN15H0dLc/vo+YTf/QpY0xinfnv7xpf7Rw==, tarball: file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz} + version: 0.2.2-t3.4 + peerDependencies: + '@pierre/highlights': '>=0.5.1' + react: ^18.3.1 || ^19.0.0 + peerDependenciesMeta: + '@pierre/highlights': + optional: true + react: + optional: true + '@pinojs/redact@0.4.0': resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==} @@ -11663,12 +11659,6 @@ packages: react-is@19.2.7: resolution: {integrity: sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A==} - react-markdown@10.1.0: - resolution: {integrity: sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==} - peerDependencies: - '@types/react': '>=18' - react: '>=18' - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz: resolution: {integrity: sha512-TdP2nTxn8W4jPJ5EU+9Ctgf6aOncENP/kMa9aEZpJDmWNLXkxPpcugHMWyZJt2o5WDYE4SPi0V6zV6mOl3+8cA==, tarball: file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz} version: 1.2.0-t3.18 @@ -13222,27 +13212,27 @@ snapshots: dependencies: json-schema: 0.4.0 - '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/acme@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@distilled.cloud/acme': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/axiom@2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@distilled.cloud/axiom': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(rolldown@1.2.13)(typescript@6.0.3)': + '@alchemy.run/cloudflare-runtime@2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(rolldown@1.2.13)(typescript@6.0.3)': dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@cloudflare/unenv-preset': 2.16.2(unenv@2.0.0-rc.24)(workerd@1.20261026.1) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@puppeteer/browsers': 3.2.6(yauzl@3.4.0) capnp-es: 0.0.16(typescript@6.0.3) - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) magic-string: 0.30.21 mime: 4.1.1 sharp: 0.35.5(@types/node@24.12.4) @@ -13250,8 +13240,8 @@ snapshots: workerd: 1.20261026.1 yauzl: 3.4.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) rolldown: 1.2.13 vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: @@ -13259,27 +13249,27 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/cloudflare@2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1)': - dependencies: - '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) - '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(rolldown@1.2.13)(typescript@6.0.3) - '@alchemy.run/docker': 2.0.0-beta.85(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5) - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5) - '@effect/sql-d1': 4.1.1(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@alchemy.run/cloudflare@2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e)': + dependencies: + '@alchemy.run/acme': 2.0.0-beta.85(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@alchemy.run/cloudflare-runtime': 2.0.0-beta.85(@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/node@24.12.4)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(rolldown@1.2.13)(typescript@6.0.3) + '@alchemy.run/docker': 2.0.0-beta.85(b7b9d9a38fe35faf72b0a492112f9365) + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@distilled.cloud/aws': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/cloudflare': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/iceberg': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) pathe: 2.0.3 picomatch: 4.0.7 rolldown: 1.2.13 tinyglobby: 0.2.17 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' transitivePeerDependencies: - '@effect/sql-libsql' @@ -13291,26 +13281,26 @@ snapshots: - proxy-agent - typescript - '@alchemy.run/docker@2.0.0-beta.85(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)': + '@alchemy.run/docker@2.0.0-beta.85(b7b9d9a38fe35faf72b0a492112f9365)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) rolldown: 1.2.13 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) - '@alchemy.run/drizzle@2.0.0-beta.85(aaf71186a61e3f73fb98ecfca2947754)': + '@alchemy.run/drizzle@2.0.0-beta.85(5cde798e96ab6d44cdc28240628f10b1)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@effect/sql-d1': 4.1.1(effect@4.1.5) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - effect: 4.1.5 + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@alchemy.run/cloudflare': 2.0.0-beta.85(0a873d1a656f19dfb51d9b33f93f91b1) - '@effect/sql-pg': 4.1.5(effect@4.1.5) - drizzle-kit: 1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)) + '@alchemy.run/cloudflare': 2.0.0-beta.85(0416d8b0ccd24e78c5b3f43641d5aa3e) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + drizzle-kit: 1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809) transitivePeerDependencies: - mysql2 - pg @@ -13320,13 +13310,13 @@ snapshots: chokidar: 5.0.0 rolldown: 1.2.13 - '@alchemy.run/planetscale@2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0)': + '@alchemy.run/planetscale@2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5)': dependencies: - '@alchemy.run/sql': 2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + '@alchemy.run/sql': 2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/planetscale': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: pg: 8.23.0 transitivePeerDependencies: @@ -13339,21 +13329,21 @@ snapshots: '@types/react': 19.3.0 react-devtools-core: 6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6) - '@alchemy.run/sql@2.0.0-beta.85(@effect/sql-pg@4.1.5(effect@4.1.5))(alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)))(effect@4.1.5)(pg@8.23.0)': + '@alchemy.run/sql@2.0.0-beta.85(da21ec6b7d14801bed2312314736ccf5)': dependencies: - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) - effect: 4.1.5 + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@effect/sql-pg': 4.1.5(effect@4.1.5) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) pg: 8.23.0 - '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(adf93af6036c4c597e35df2cca6d42d0)': + '@alchemy.run/test@2.0.0-beta.85(patch_hash=29c0539ea71d9cc372f0b16558640599beb9bc609605feb2a493da268d72713e)(a619c060a1b8ed45ad4914f1f8e44c19)': dependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) optionalDependencies: - '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) - alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) + '@effect/vitest': 4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) + alchemy: 2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)) vitest: 5.0.5(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/browser-preview@5.0.5)(@vitest/ui@5.0.5)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0) transitivePeerDependencies: - bufferutil @@ -14332,45 +14322,45 @@ snapshots: '@dimforge/rapier3d-compat@0.12.0': {} - '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/acme@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/aws4signer@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/aws@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5) - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/aws4signer': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/axiom@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/cloudflare@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/core@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/iceberg@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5)': + '@distilled.cloud/planetscale@1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5) - effect: 4.1.5 + '@distilled.cloud/core': 1.0.0-rc.18(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@dnd-kit/accessibility@3.1.1(react@19.3.0)': dependencies: @@ -14416,64 +14406,64 @@ snapshots: e2e: 0.23.0 playwright-core: 1.64.1 - '@effect/atom-react@4.1.5(effect@4.1.5)(react@19.3.0)(scheduler@0.28.0)': + '@effect/atom-react@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react@19.3.0)(scheduler@0.28.0)': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) react: 19.3.0 scheduler: 0.28.0 - '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)': + '@effect/graphql-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5)(encoding@0.1.13)': + '@effect/openapi-generator@4.1.5(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(encoding@0.1.13)': dependencies: - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) swagger2openapi: 7.0.8(encoding@0.1.13) transitivePeerDependencies: - encoding - '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6)': + '@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6)': + '@effect/platform-node-shared@4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6)': dependencies: '@types/ws': 8.18.2 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6)': + '@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6)': dependencies: - '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - effect: 4.1.5 + '@effect/platform-node-shared': 4.1.5(patch_hash=06952843c6f431ca83c78762fd18d23cda76883801049ee311feced2438ecf14)(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) redis: 6.2.1 undici: 8.12.4 transitivePeerDependencies: - bufferutil - utf-8-validate - '@effect/sql-d1@4.1.1(effect@4.1.5)': + '@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: '@cloudflare/workers-types': 5.20261026.1 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/sql-pg@4.1.5(effect@4.1.5)': + '@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) - '@effect/sql-sqlite-do@4.1.5(effect@4.1.5)': + '@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@effect/tsgo-darwin-arm64@0.67.1': optional: true @@ -14506,9 +14496,9 @@ snapshots: '@effect/tsgo-win32-arm64': 0.67.1 '@effect/tsgo-win32-x64': 0.67.1 - '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': + '@effect/vitest@4.1.5(patch_hash=dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5)(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0)': dependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) vite-plus: 1.4.0(@astrojs/compiler-rs@0.5.1)(@types/node@24.12.4)(@vitest/browser-playwright@5.0.5)(@vitest/ui@5.0.5)(@volar/typescript@2.4.28(typescript@6.0.3))(bufferutil@4.1.0)(esbuild@0.28.2)(jiti@2.7.0)(jsdom@30.1.0(@noble/hashes@1.8.0))(playwright@1.64.1)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(utf-8-validate@6.0.6)(yaml@2.9.0) transitivePeerDependencies: - '@arethetypeswrong/core' @@ -15680,7 +15670,7 @@ snapshots: '@koromix/koffi-win32-x64@3.3.6': optional: true - '@legendapp/list@3.7.3(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)': + '@legendapp/list@3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(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)': dependencies: react: 19.3.0 use-sync-external-store: 1.7.0(react@19.3.0) @@ -15984,22 +15974,22 @@ snapshots: dependencies: cross-spawn: 7.0.6 - '@opencode/client@2.0.28(effect@4.1.5)': + '@opencode/client@2.0.28(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))': dependencies: '@opencode/protocol': 2.0.28 '@opencode/schema': 2.0.28 optionalDependencies: - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@opencode/protocol@2.0.28': dependencies: '@opencode/schema': 2.0.28 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@opencode/schema@2.0.28': dependencies: '@standard-schema/spec': 1.1.0 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) '@oslojs/asn1@1.0.0': dependencies: @@ -16600,6 +16590,11 @@ snapshots: - '@shikijs/themes' - shiki + '@pierre/words@file:apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz(@pierre/highlights@0.5.1)(react@19.3.0)': + optionalDependencies: + '@pierre/highlights': 0.5.1 + react: 19.3.0 + '@pinojs/redact@0.4.0': {} '@polka/url@1.0.0-next.29': {} @@ -18083,12 +18078,12 @@ snapshots: json-schema-traverse: 1.0.0 require-from-string: 2.0.2 - alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): + alchemy@2.0.0-beta.85(patch_hash=07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd)(@effect/platform-bun@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6))(@effect/platform-node@4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0))(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6))(ws@8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6)): dependencies: '@alchemy.run/node-utils': 2.0.0-beta.85 '@alchemy.run/sigil': 0.1.0-alpha.1(@types/react@19.3.0)(react-devtools-core@6.1.5(bufferutil@4.1.0)(utf-8-validate@6.0.6)) capnweb: 0.12.0 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) fflate: 0.8.3 pathe: 2.0.3 picomatch: 4.0.7 @@ -18096,8 +18091,8 @@ snapshots: tinyglobby: 0.2.17 yaml: 2.9.0 optionalDependencies: - '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(utf-8-validate@6.0.6) - '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5)(redis@6.2.1)(utf-8-validate@6.0.6) + '@effect/platform-bun': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(utf-8-validate@6.0.6) + '@effect/platform-node': 4.1.5(bufferutil@4.1.0)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(redis@6.2.1)(utf-8-validate@6.0.6) vite: '@voidzero-dev/vite-plus-core@1.4.0(@types/node@24.12.4)(@volar/typescript@2.4.28(typescript@6.0.3))(esbuild@0.28.2)(jiti@2.7.0)(terser@5.48.0)(typescript@6.0.3)(unrun@0.2.39)(yaml@2.9.0)' ws: 8.22.0(bufferutil@4.1.0)(utf-8-validate@6.0.6) transitivePeerDependencies: @@ -19056,21 +19051,21 @@ snapshots: dotenv@16.6.1: {} - drizzle-kit@1.0.0-rc.5(drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7)): + drizzle-kit@1.0.0-rc.5(73cc0b8bb5cef1afe1d24404a4fb8809): optionalDependencies: - drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) + drizzle-orm: 1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7) - drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5))(@effect/sql-pg@4.1.5(effect@4.1.5))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5)(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): + drizzle-orm@1.0.0-rc.5(@cloudflare/workers-types@4.20260604.1)(@effect/sql-d1@4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-pg@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@effect/sql-sqlite-do@4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)))(@electric-sql/pglite@0.3.15)(@libsql/client@0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6))(@types/sql.js@1.4.11)(bun-types@1.3.14)(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28))(expo-sqlite@58.0.15(expo@58.0.23)(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))(pg@8.23.0)(sql.js@1.15.0)(zod@4.6.7): optionalDependencies: '@cloudflare/workers-types': 4.20260604.1 - '@effect/sql-d1': 4.1.1(effect@4.1.5) - '@effect/sql-pg': 4.1.5(effect@4.1.5) - '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5) + '@effect/sql-d1': 4.1.1(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-pg': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) + '@effect/sql-sqlite-do': 4.1.5(effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28)) '@electric-sql/pglite': 0.3.15 '@libsql/client': 0.17.3(bufferutil@4.1.0)(utf-8-validate@6.0.6) '@types/sql.js': 1.4.11 bun-types: 1.3.14 - effect: 4.1.5 + effect: 4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28) expo-sqlite: 58.0.15(expo@58.0.23)(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) pg: 8.23.0 sql.js: 1.15.0 @@ -19109,7 +19104,7 @@ snapshots: ee-first@1.1.1: {} - effect@4.1.5: {} + effect@4.1.5(patch_hash=24395ce5abc3df3a44cceace2bb247cfe7d201e82b099212372b9347de142f28): {} ejs@3.1.10: dependencies: @@ -22604,24 +22599,6 @@ snapshots: react-is@19.2.7: {} - react-markdown@10.1.0(@types/react@19.3.0)(react@19.3.0)(supports-color@8.1.1): - dependencies: - '@types/hast': 3.0.5 - '@types/mdast': 4.0.4 - '@types/react': 19.3.0 - devlop: 1.1.0 - hast-util-to-jsx-runtime: 2.3.6(supports-color@8.1.1) - html-url-attributes: 3.0.1 - mdast-util-to-hast: 13.2.1(patch_hash=57ea46c73aea3c876ab8d351fe0482ddd081dcb4a0610576e399dbe5eb59d2b1) - react: 19.3.0 - remark-parse: 11.0.0(supports-color@8.1.1) - remark-rehype: 11.1.2 - unified: 11.0.5 - unist-util-visit: 5.1.0 - vfile: 6.0.3 - transitivePeerDependencies: - - supports-color - react-native-enriched-markdown@file:apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz(katex@0.16.47)(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: react: 19.3.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index a91c6a863c2df..fac5a9a9755b0 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -233,6 +233,7 @@ patchedDependencies: react-native-image-viewing@0.2.2: patches/react-native-image-viewing@0.2.2.patch mdast-util-math@3.0.0: patches/mdast-util-math@3.0.0.patch micromark-extension-llm-math@3.1.0: patches/micromark-extension-llm-math@3.1.0.patch + "@legendapp/list@3.7.3": patches/@legendapp__list@3.7.3.patch micromark-extension-gfm-table@2.1.1: patches/micromark-extension-gfm-table@2.1.1.patch micromark@4.0.2: patches/micromark@4.0.2.patch mdast-util-to-hast@13.2.1: patches/mdast-util-to-hast@13.2.1.patch @@ -285,6 +286,8 @@ patchedDependencies: react-native-svg@15.16.1: patches/react-native-svg@15.16.1.patch # Android: double-tap zoom no longer cancels itself, and taps near a link open it. react-native-pdf-jsi@6.1.0: patches/react-native-pdf-jsi@6.1.0.patch + # The MCP Events extension (SEP-3415) on effect/ai, until Effect ships it. + effect@4.1.5: patches/effect@4.1.5.patch # Unmet peers fail resolution, so a pin outside a dependency's peer range is # caught when the lockfile changes instead of scrolling past as a warning. diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts index 135ff4ed201f7..d5881661f4cdc 100644 --- a/scripts/check-changed.ts +++ b/scripts/check-changed.ts @@ -433,6 +433,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { file === ".pnpmfile.cjs" || file.startsWith("patches/") || file.startsWith("apps/mobile/deps/") || + file.startsWith("apps/web/deps/") || path.basename(file) === "package.json", ); @@ -479,7 +480,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { if (yield* fs.exists(inRoot(manifest))) yield* copy(manifest); } } - for (const extra of ["apps/mobile/deps", "patches", ".pnpmfile.cjs"]) { + for (const extra of ["apps/mobile/deps", "apps/web/deps", "patches", ".pnpmfile.cjs"]) { if (yield* fs.exists(inRoot(extra))) yield* copy(extra); } const result = yield* vp(["install", "--lockfile-only", "--ignore-scripts"], temp); diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 3c58be4cbabbf..e7acbf1e76ff1 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -68,11 +68,12 @@ function copyWorkspaceManifestFixture(targetRoot: string): void { NodeFS.cpSync(sourcePath, destinationPath); } - const mobileDependencies = NodePath.resolve(repoRoot, "apps/mobile/deps"); - if (NodeFS.existsSync(mobileDependencies)) { - NodeFS.cpSync(mobileDependencies, NodePath.resolve(targetRoot, "apps/mobile/deps"), { - recursive: true, - }); + // Fork tarballs that file: dependencies install from. + for (const forks of ["apps/mobile/deps", "apps/web/deps"]) { + const source = NodePath.resolve(repoRoot, forks); + if (NodeFS.existsSync(source)) { + NodeFS.cpSync(source, NodePath.resolve(targetRoot, forks), { recursive: true }); + } } const patchesDirectory = NodePath.resolve(repoRoot, "patches"); diff --git a/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts b/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts index b6afb9358cd2b..66c69347e4aa4 100644 --- a/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts +++ b/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts @@ -9,7 +9,8 @@ test( await t3.project("demo"); await t3.open(); - await screen.getByRole("button", "Add project").tap(); + await screen.getByRole("combobox", "Projects").tap(); + await screen.getByRole("option", "Add project").tap(); await screen.getByText("Git URL").tap(); await screen.getByRole("combobox").fill("https://github.com/pingdotgg/t3code.git"); const submit = screen.getByRole("button", "Continue (Enter)"); diff --git a/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts new file mode 100644 index 0000000000000..6cfbafc6c49b2 --- /dev/null +++ b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const FILE = "handoff.txt"; + +test( + "A bare citation leaves the file unresolved when other projects contain several matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("planning"); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: [`See :codex-file-citation{path="${FILE}" line_range_start="1"}`], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-handoff-citation"); + } + }, +); diff --git a/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts new file mode 100644 index 0000000000000..22458e6223fbb --- /dev/null +++ b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts @@ -0,0 +1,34 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A bare citation leaves the file unresolved when the thread project has ambiguous matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: ['See :codex-file-citation{path="handoff.txt" line_range_start="1"}'], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-local-handoff-citation"); + } + }, +); diff --git a/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts new file mode 100644 index 0000000000000..739497a827757 --- /dev/null +++ b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts @@ -0,0 +1,113 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fixture holds Git's HTTP request open. +import * as NodeHttp from "node:http"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { ProjectId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Stream from "effect/Stream"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +test( + "Dismissing clone progress leaves the later failure notification visible", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Other work", messages: ["Start"] }); + const gitRequest = Promise.withResolvers(); + const remote = NodeHttp.createServer((_request, response) => { + gitRequest.resolve(response); + }); + + try { + await new Promise((resolve) => remote.listen(0, "127.0.0.1", resolve)); + const address = remote.address(); + if (!address || typeof address === "string") throw new Error("No Git fixture port"); + const projectId = ProjectId.make( + await runPromise( + SecureRandom.SecureRandom.pipe( + Effect.flatMap((random) => random.uuidV4()), + Effect.provide(NodeCrypto.layer), + ), + ), + ); + const name = "pending-clone"; + const origin = app.baseUrl ?? ""; + await t3.open(thread); + await screen.getByText("Start", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + const createdAt = DateTime.formatIso(yield* DateTime.now); + yield* client["projectClone.start"]({ + projectId, + title: name, + createdAt, + remoteUrl: `http://127.0.0.1:${address.port}/${name}.git`, + destinationPath: `${project}/../${name}`, + }); + }).pipe(Effect.scoped), + ); + const response = await gitRequest.promise; + + const toastTitle = (title: string) => + browser.locator(`[data-slot="toast-title"]:text-is("${title}")`); + const dismiss = async (title: string) => { + await browser + .locator( + `[data-position]:has(> div > [data-slot="toast-close"]):has([data-slot="toast-title"]:text-is("${title}"))`, + ) + .getByRole("button", "Dismiss notification", { exact: true }) + .tap(); + await toastTitle(title).waitFor({ state: "detached" }); + }; + const progress = toastTitle(`Cloning ${name}`); + const failure = toastTitle(`Failed to clone ${name}`); + + await progress.waitFor(); + await dismiss(`Cloning ${name}`); + + response.writeHead(404).end(); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + yield* client.subscribeProjectClones({}).pipe( + Stream.filter((clones) => + clones.some((clone) => clone.projectId === projectId && clone.phase === "failed"), + ), + Stream.runHead, + ); + }).pipe(Effect.scoped, Effect.timeout("10 seconds")), + ); + + try { + await expect(failure).toBeVisible(); + } finally { + await app.screenshot("after-background-clone-fails"); + } + + await dismiss(`Failed to clone ${name}`); + + const retryRequest = Promise.withResolvers(); + remote.once("request", (_request, response) => retryRequest.resolve(response)); + const retry = await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + return yield* client["projectClone.retry"]({ projectId }); + }).pipe(Effect.scoped), + ); + await expect(retry.applied).toBe(true); + const retryResponse = await retryRequest.promise; + await expect(progress).toBeVisible(); + retryResponse.writeHead(404).end(); + await expect(failure).toBeVisible(); + } finally { + remote.close(); + remote.closeAllConnections(); + } + }, +); diff --git a/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts new file mode 100644 index 0000000000000..dbd90361cfe45 --- /dev/null +++ b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts @@ -0,0 +1,139 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodeCredential = Schema.decodeUnknownSync(Schema.Struct({ credential: Schema.String })); + +test( + "A closed linked-thread tab does not take over the conversation when pairing finishes", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("primary"); + const parent = await t3.thread({ + project, + title: "Current work", + messages: ["Keep this conversation open"], + }); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + const second = makeState(SECOND_HOME); + const issued = await runPromise(second.cli(["auth", "session", "issue", "--token-only"])); + // @effect-diagnostics-next-line globalFetch:off -- Seeds the real peer link from the scenario's Node fixture. + const pairing = await fetch(`${host}/api/auth/pairing-token`, { + method: "POST", + headers: { + authorization: `Bearer ${issued.stdout.trim()}`, + "content-type": "application/json", + }, + body: JSON.stringify({ purpose: "peer-link", access: "full-access" }), + }); + if (!pairing.ok) throw new Error(`Could not mint a peer-link code: ${pairing.status}`); + const { credential } = decodeCredential(await pairing.json()); + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "full-access", + }); + }).pipe(Effect.scoped), + ); + + const linkedProject = await second.state.project("linked"); + const linkedTitle = "Remote design notes"; + const linkedPrompt = "Read the remote design notes"; + const remoteThread = await second.state.thread({ + project: linkedProject, + title: linkedTitle, + messages: [linkedPrompt], + }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + await browser.setViewport({ width: 1440, height: 900 }); + + // Restore the same saved tab that opening the delegated thread in the panel would leave. + await browser.addInitScript( + ({ via, linked, parentId, childId, title }) => { + if (location.pathname !== `/${via}/${parentId}`) return; + const id = `linked-thread:${encodeURIComponent(via)}:${encodeURIComponent(linked)}:${encodeURIComponent(childId)}`; + localStorage.setItem( + "t3code:right-panel-state:v2", + JSON.stringify({ + version: 16, + state: { + byThreadKey: { + [`${via}:${parentId}`]: { + isOpen: true, + activeSurfaceId: id, + surfaces: [ + { + kind: "linked-thread", + id, + viaEnvironmentId: via, + environmentId: linked, + threadId: childId, + label: "Scenario", + title, + }, + ], + }, + }, + threadPanelVisibilityByThreadKey: {}, + }, + }), + ); + }, + { + via, + linked, + parentId: parent.threadId, + childId: remoteThread.threadId, + title: linkedTitle, + }, + ); + + const tokenUrl = `${host}/oauth/token`; + const requested = Promise.withResolvers(); + const release = Promise.withResolvers(); + await browser.route(tokenUrl, async (route) => { + if (route.request.method !== "POST") return route.fallback(); + requested.resolve(); + await release.promise; + await route.continue(); + }); + try { + await t3.open(parent); + await screen.getByText(linkedPrompt, { exact: true }).waitFor(); + const originalUrl = await browser.url(); + await screen.getByRole("button", "Connect to interact", { exact: true }).tap(); + await requested.promise; + await screen.getByRole("button", `Close ${linkedTitle}`, { exact: true }).tap(); + + release.resolve(); + await screen + .getByText("This device is paired with it and can use its threads.", { exact: true }) + .waitFor(); + + await app.screenshot("after-pairing-finishes"); + await expect(browser).toHaveURL(originalUrl); + } finally { + release.resolve(); + await browser.unroute(tokenUrl); + } + } finally { + await server.stop(); + } + }, +); diff --git a/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts b/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts new file mode 100644 index 0000000000000..42c5c57b1ea4c --- /dev/null +++ b/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts @@ -0,0 +1,88 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +const linkEnvironments = Effect.fn("scenario.linkEnvironments")(function* ( + primaryOrigin: string, + secondOrigin: string, + fallback: string, +) { + const primary = yield* rpcClient(T3_HOME, primaryOrigin); + const second = yield* rpcClient(SECOND_HOME, secondOrigin); + for (const client of [primary, second]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: secondOrigin, + alternateUrls: [fallback], + pairingCode: credential, + access: "full-access", + }); +}, Effect.scoped); + +test( + "Connect to interact opens the editable thread before a silent fallback times out", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const primary = app.baseUrl ?? ""; + const secondServer = startSecondServer(primary); + try { + const { host } = await secondServer.ready; + const alternate = new URL(host); + alternate.hostname = "127.0.0.2"; + await runPromise(linkEnvironments(primary, host, alternate.origin)); + + const second = makeState(SECOND_HOME).state; + const project = await second.project("linked"); + const thread = await second.thread({ + project, + title: "Linked handoff", + messages: ["first"], + }); + const via = await runPromise(environmentId(primary)); + const target = await runPromise(environmentId(host)); + + await browser.addInitScript((fallback) => { + const fetchActual = globalThis.fetch; + globalThis.fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input), location.href); + if (url.origin !== fallback || url.pathname !== "/.well-known/t3/environment") { + // @effect-diagnostics-next-line globalFetch:off - This interception runs inside the browser. + return fetchActual(input, init); + } + // The browser's network silently drops this route. The preferred address is still real. + return new Promise((_, reject) => { + const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined); + signal?.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); + }; + }, alternate.origin); + + await t3.open(`/linked/${via}/${target}/${thread.threadId}`); + await screen.getByRole("heading", "Linked handoff").waitFor(); + await screen.getByRole("button", "Connect to interact").tap(); + + try { + await expect + .poll(() => browser.evaluate(() => location.pathname), { timeout: 4_000 }) + .toBe(`/${target}/${encodeURIComponent(thread.threadId)}`); + } finally { + await app.screenshot("linked-thread-after-connect"); + } + } finally { + await secondServer.stop(); + } + }, +); diff --git a/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts new file mode 100644 index 0000000000000..fd24c39b74dea --- /dev/null +++ b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts @@ -0,0 +1,105 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +test( + "Try again immediately reads a linked thread once it is reachable", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli([ + "auth", + "pairing", + "create", + "--json", + ]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "approval-required", + }); + }).pipe(Effect.scoped), + ); + + const remote = makeState(SECOND_HOME).state; + const project = await remote.project("linked"); + const prompt = "Read the linked design notes"; + const thread = await remote.thread({ project, title: "Design notes", messages: [prompt] }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + + // Drop only the first subscription, as if the linked machine were briefly unreachable. + // Every later request goes to the real server and reads the seeded thread. + await browser.addInitScript(() => { + let failed = false; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (failed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = Array.isArray(parsed) ? parsed : [parsed]; + const request = messages.find( + (message) => message?._tag === "Request" && message.tag === "peerLinks.subscribeThread", + ); + if (!request) return send.call(this, data); + failed = true; + const others = messages.filter((message) => message !== request); + if (others.length > 0) send.call(this, JSON.stringify(others)); + // @effect-diagnostics-next-line globalTimers:off - This callback is injected into the browser. + setTimeout(() => { + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId: request.id, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "PeerLinkThreadReadError", + reason: "unreachable", + label: "Scenario", + message: "The linked machine is temporarily unreachable.", + }, + }, + ], + }, + }), + }), + ); + }, 0); + }; + }); + + await t3.open(`/linked/${via}/${linked}/${thread.threadId}`); + await screen.getByRole("button", "Try again", { exact: true }).tap(); + await app.screenshot("after-trying-again"); + // The automatic retry waits 15 seconds. This checks the user's explicit retry. + await expect(screen.getByText(prompt, { exact: true })).toBeVisible({ timeout: 4_000 }); + } finally { + await server.stop(); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts new file mode 100644 index 0000000000000..c944cf1ec9d42 --- /dev/null +++ b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts @@ -0,0 +1,80 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const savedResults = Array.from({ length: 17 }, (_, index) => `Saved result ${index + 1}`); +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: [ + { output_type: "stream", name: "stdout", text: Array(12).fill("Processing").join("\n") }, + ...savedResults.map((result) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `${result}` }, + })), + ], + }, + ], +}; +const lastOutput = '[data-notebook-output="0-17"]'; + +test( + "All saved notebook outputs render when they fit in a tall preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // The stream puts the final result below the fold until the user scrolls. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 1070; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator('[data-notebook-output="0-15"] iframe').waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = viewport.scrollHeight; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + const bounds = viewport.getBoundingClientRect(); + return Array.from(viewport.querySelectorAll("[data-notebook-output]"), (output) => { + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return "Output is offscreen"; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }); + }, lastOutput), + ) + .toEqual(savedResults); + } finally { + await app.screenshot("last-saved-output-in-tall-preview"); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts new file mode 100644 index 0000000000000..2897ecc0df7eb --- /dev/null +++ b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts @@ -0,0 +1,77 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: Array.from({ length: 17 }, (_, index) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `Saved result ${index + 1}` }, + })), + }, + ], +}; +const fifteenthOutputFrame = '[data-notebook-output="0-14"] iframe'; +const lastOutput = '[data-notebook-output="0-16"]'; + +test( + "A visible saved notebook output renders when earlier outputs have scrolled above it", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // Leave room for the final output and fewer than sixteen preceding outputs. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 940; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator(fifteenthOutputFrame).waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = 170; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const output = document.querySelector(selector); + const viewport = output?.closest(".scrollbar-gutter-both"); + if (!output || !viewport) return null; + const bounds = viewport.getBoundingClientRect(); + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return null; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }, lastOutput), + ) + .toBe("Saved result 17"); + } finally { + await app.screenshot("last-saved-output"); + } + }, +); diff --git a/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts new file mode 100644 index 0000000000000..8ee5453bbba20 --- /dev/null +++ b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A queued message shows its @-file mention by name, not as a raw link", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "src/foo.ts": "export {};\n" }); + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @foo"); + await screen.getByRole("option", "foo.ts", { exact: false }).tap(); + await expect(composer).toContainText("foo.ts"); + + // The showcase recording streams for several seconds, long enough to queue behind its turn. + await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Show me again"])); + await screen.getByText("Working for", { exact: false }).waitFor(); + // Enter steers by default; the alternate send queues. + await browser.keyboard.press("ControlOrMeta+Enter"); + + const queued = screen.getByRole("listitem", "Queued message 1 of 1, not sent"); + await queued.waitFor(); + // Read the row once: the queued message sends, and its row goes, when the turn ends. + const text = await queued.textContent(); + await app.screenshot("queued-row"); + expect(text).toContain("Review foo.ts"); + }, +); diff --git a/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts new file mode 100644 index 0000000000000..49186eaa4429a --- /dev/null +++ b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts @@ -0,0 +1,64 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +declare global { + interface Window { + releaseOldThemeRead: () => void; + } +} + +test( + "An earlier theme file cannot become the draft after its replacement is rejected", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + + await browser.evaluate(() => { + const target = document.querySelector('input[type="file"]')?.parentElement; + if (!target) throw new Error("No theme file drop target"); + + const gate = Promise.withResolvers(); + const theme = JSON.stringify({ + version: 1, + name: "Earlier theme", + appearance: "dark", + colors: { accent: "#734ee4" }, + }); + const first = new File([theme], "earlier.json", { type: "application/json" }); + const text = File.prototype.text; + File.prototype.text = function () { + if (this.name === first.name) return gate.promise.then(() => theme); + return text.call(this); + }; + window.releaseOldThemeRead = gate.resolve; + + const drop = (file: File) => { + const files = new DataTransfer(); + files.items.add(file); + target.dispatchEvent( + new DragEvent("drop", { dataTransfer: files, bubbles: true, cancelable: true }), + ); + }; + drop(first); + drop(new File([" ".repeat(300_000)], "replacement.json", { type: "application/json" })); + return null; + }); + + await dialog.getByText(/That file is/).waitFor(); + await browser.evaluate(async () => { + window.releaseOldThemeRead(); + // Let the earlier file response and its React update reach the dialog. + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + return null; + }); + await app.screenshot("dialog-after-earlier-theme-read-finishes"); + await expect(dialog.getByRole("button", "Add theme", { exact: true })).toBeDisabled(); + }, +); diff --git a/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts b/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts new file mode 100644 index 0000000000000..2aa4c70a1fa12 --- /dev/null +++ b/scripts/scenarios/server-preview-app-link-stops-loading.e2e.ts @@ -0,0 +1,53 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - one fixture page for the server's browser to load +import * as NodeHttp from "node:http"; + +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +// One app link that fills the page. Its click renames the page a moment later, after the server +// has seen the link's request. +const PAGE = ` +Note link +Open the note`; + +test( + "An app link clicked in the Browser leaves the page shown and loaded", + WEB, + async ({ t3, app, browser, screen }) => { + const server = NodeHttp.createServer((_request, response) => { + response.writeHead(200, { "content-type": "text/html" }); + response.end(PAGE); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + try { + const address = server.address(); + if (address === null || typeof address === "string") throw new Error("No page port."); + const url = `http://127.0.0.1:${address.port}/`; + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Note check", messages: ["first"] }); + await t3.open(thread); + + await screen.getByRole("button", "Toggle right panel").tap(); + await screen.getByRole("button", "Browser B").tap(); + const addressBar = screen.getByRole("textbox", "Search or enter URL"); + await addressBar.fill(url); + await browser.keyboard.press("Enter"); + await expect(screen.getByText("Note link")).toBeVisible(); + + // The page draws on the canvas beside its input proxy. + await browser.locator('canvas:has(~ textarea[aria-label="Browser page"])').tap(); + try { + // Chromium hands the link to the OS and keeps the page, which goes on renaming itself. + await expect(screen.getByText("Link clicked")).toBeVisible({ timeout: 2_000 }); + await expect(addressBar).toHaveValue(url); + await expect(screen.getByRole("button", "Refresh", { exact: true })).toBeVisible(); + } finally { + await app.screenshot("after-click"); + } + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }, +); diff --git a/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts new file mode 100644 index 0000000000000..1f93e154b89e2 --- /dev/null +++ b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts @@ -0,0 +1,51 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A worktree thread stopped mid-turn and moved to the project checkout runs its next message", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + // The question recording waits for an answer, so the turn is running in its new worktree. + const started = await runPromise( + makeState(T3_HOME).cli( + [ + "thread", + "start", + project, + "Ask me something", + "--worktree", + "main", + "--provider", + "devReplay", + "--model", + "question", + "--wait", + "--json", + ], + [2], + ), + ); + await t3.open(JSON.parse(started.stdout) as { threadId: string }); + + const stop = screen.getByRole("button", "Stop generation"); + await stop.waitFor({ timeout: 60_000 }); + await stop.tap(); + await stop.waitFor({ state: "hidden" }); + + await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').click(); + await screen.getByRole("option", /^main\b/).tap(); + // The server has moved the thread to the project checkout before the send. + await browser + .locator('[aria-label^="Run context:"][aria-label$="Local checkout"]') + .waitFor({ timeout: 60_000 }); + + await screen.getByRole("textbox").fill("Once more"); + await screen.getByRole("textbox").press("Enter"); + await screen.getByText("Once more").first().waitFor(); + await expect(stop).toBeVisible({ timeout: 60_000 }); + await app.screenshot("running-in-checkout"); + }, +); diff --git a/scripts/scenarios/terminal-latched-modifier-reads-selected.e2e.ts b/scripts/scenarios/terminal-latched-modifier-reads-selected.e2e.ts new file mode 100644 index 0000000000000..5ee593a409190 --- /dev/null +++ b/scripts/scenarios/terminal-latched-modifier-reads-selected.e2e.ts @@ -0,0 +1,41 @@ +import { expect } from "e2e"; + +import { MOBILE } from "../e2e.config.ts"; +import { environmentId, runPromise } from "./t3.ts"; +import { IOS, test } from "./t3-mobile.ts"; + +test( + "A latched terminal ctrl key reads as selected to iOS accessibility", + IOS, + async ({ t3, app, screen, device }) => { + const project = await t3.project("demo"); + const { threadId } = await t3.thread({ project, title: "Latched keys", messages: ["hello"] }); + await t3.open(); + await screen.getByText("Latched keys", { exact: false }).first().waitFor({ timeout: 120_000 }); + + const environment = await runPromise( + environmentId(`http://${MOBILE.host}:${MOBILE.serverPort}`), + ); + await device.openLink(`t3code-dev://threads/${environment}/${threadId}/terminal`, { + app: "com.t3tools.t3code.dev", + }); + await device.alert("accept").catch(() => {}); + + // The keyboard toolbar shows with the software keyboard; ctrl starts past its right edge. + const esc = screen.getByRole("button", "esc"); + await esc.waitFor({ timeout: 60_000 }); + const box = await esc.boundingBox(); + const x = (box?.x ?? 0) + (box?.width ?? 0); + const y = (box?.y ?? 0) + (box?.height ?? 0) / 2; + // A slow drag, so the scroller stops with ctrl in view instead of flinging to its end. + await screen.swipe({ from: { x, y }, to: { x: x - 150, y }, duration: 1_500 }); + const ctrl = screen.getByRole("button", "ctrl"); + await ctrl.waitFor(); + await ctrl.tap(); + await app.screenshot("ctrl-latched"); + await expect(ctrl).toBeSelected(); + + await ctrl.tap(); + await expect(ctrl).not.toBeSelected(); + }, +); diff --git a/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts new file mode 100644 index 0000000000000..acd9096465978 --- /dev/null +++ b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts @@ -0,0 +1,75 @@ +import { ProjectSnapshot, ProviderInstanceId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const PROMPT_LOG_LIMIT = 64 * 1024; +const FRAME_OPEN = "".length; + +const deliverStraddlingEmoji = Effect.fn("scenario.deliverStraddlingEmoji")( + function* (origin: string) { + const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); + const { projects } = yield* HttpClient.execute( + HttpClientRequest.get(`${origin}/api/projects`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)), + ); + const client = yield* rpcClient(T3_HOME, origin); + const { task } = yield* client["scheduledTasks.upsert"]({ + title: "Webhook log", + prompt: "{{body.text}}", + enabled: true, + schedule: { type: "webhook" }, + projectId: projects.find((project) => project.title === "webhook-log")!.id, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + // The emoji's high surrogate is the last code unit the delivery log keeps. + const text = `${"a".repeat(PROMPT_LOG_LIMIT - 1 - FRAME_OPEN)}😀 tail`; + yield* HttpClient.execute( + HttpClientRequest.post(`${origin}${task.webhook!.path}`).pipe( + HttpClientRequest.bodyJsonUnsafe({ text }), + ), + ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + }, + Effect.scoped, + Effect.provide(FetchHttpClient.layer), +); + +test( + "A long webhook prompt in the delivery log does not end in a broken character", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("webhook-log"); + await runPromise(deliverStraddlingEmoji(app.baseUrl ?? "")); + + await t3.open("/settings/scheduled-tasks"); + await screen.getByRole("button", "Actions for Webhook log").tap(); + await screen.getByRole("menuitem", "Deliveries").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByRole("button", /POST/).tap(); + const prompt = dialog.getByText(/^ { + const block = [...document.querySelectorAll("pre")].find((pre) => + pre.textContent?.startsWith(" +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import JSZip from "jszip"; + +import { test, WEB } from "./t3.ts"; + +const SHEETS = ["Overview", "Actuals", "Forecast"]; +const RELATIONSHIPS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + +async function workbook() { + const archive = new JSZip(); + const sheets = SHEETS.map( + (name, index) => ``, + ).join(""); + archive.file( + "xl/workbook.xml", + `${sheets}`, + ); + const relationships = SHEETS.map( + (_, index) => + ``, + ).join(""); + archive.file("xl/_rels/workbook.xml.rels", `${relationships}`); + for (const [index] of SHEETS.entries()) + archive.file( + `xl/worksheets/sheet${index + 1}.xml`, + `${index + 1}`, + ); + return archive.generateAsync({ type: "uint8array" }); +} + +test( + "Two rapid right arrows advance two tabs in an Excel preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "budget.xlsx": await workbook() }); + const archive = await JSZip.loadAsync(await workbook()); + const manifest = (await archive.file("xl/workbook.xml")!.async("string")).replace( + ' { + const first = document.querySelector( + '[role="tablist"] [role="tab"][aria-selected="true"]', + )!; + first.focus(); + for (let press = 0; press < 2; press++) + document.activeElement?.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), + ); + return null; + }); + await screen.getByRole("grid", /Actuals|Forecast/).waitFor(); + await app.screenshot("after-two-right-arrows"); + await expect + .poll(() => + browser.evaluate( + () => + document + .querySelector('[role="tablist"]') + ?.parentElement?.querySelector('[role="grid"]') + ?.getAttribute("aria-label") ?? null, + ), + ) + .toBe("Forecast"); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("wraparound.xlsx"); + await screen.getByRole("option", "wraparound.xlsx", { exact: false }).tap(); + await browser + .locator('[data-active-tab="true"]') + .getByText("wraparound.xlsx", { exact: true }) + .waitFor(); + const overview = screen.getByRole("tab", "Overview"); + await overview.waitFor(); + + const { ok: showSucceeded, selectedAtSecondPress } = await browser.evaluate(async () => { + const first = document.querySelector( + '[role="tablist"] [role="tab"][aria-selected="true"]', + )!; + const pressRight = () => + document.activeElement?.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), + ); + const postMessage = Worker.prototype.postMessage; + return await new Promise<{ ok: boolean; selectedAtSecondPress: string | null }>((resolve) => { + Worker.prototype.postMessage = function ( + this: Worker, + message: { method?: string; id?: number }, + options?: Transferable[] | StructuredSerializeOptions, + ) { + if (message.method === "show") { + Worker.prototype.postMessage = postMessage; + const onReply = (event: MessageEvent<{ id: number; ok: boolean }>) => { + if (event.data.id !== message.id) return; + this.removeEventListener("message", onReply); + if (event.data.ok !== true) { + resolve({ ok: false, selectedAtSecondPress: null }); + return; + } + // The worker client has queued the first layout, and React has yet to commit it. + queueMicrotask(() => { + const selected = first.getAttribute("aria-selected"); + pressRight(); + resolve({ ok: true, selectedAtSecondPress: selected }); + }); + }; + this.addEventListener("message", onReply); + } + Reflect.apply(postMessage, this, [message, options]); + }; + first.focus(); + pressRight(); + }); + }); + expect(showSucceeded).toBe(true); + expect(selectedAtSecondPress).toBe("true"); + await expect(overview).toBeFocused(); + await app.screenshot("after-wrapping-to-overview"); + await expect(overview).toHaveAttribute("aria-selected", "true"); + await expect(screen.getByRole("grid", "Overview")).toBeVisible(); + }, +); diff --git a/skills/t3-workflows/SKILL.md b/skills/t3-workflows/SKILL.md new file mode 100644 index 0000000000000..7f600e0b4cee5 --- /dev/null +++ b/skills/t3-workflows/SKILL.md @@ -0,0 +1,353 @@ +--- +name: t3-workflows +description: Author, edit, run, and debug durable T3 Code workflows (`~/.t3/workflows/*.ts`). Use when asked to build or change a multi-step T3 Code automation tying together agent threads, code steps, schedules, webhooks, issue/PR trackers, or human approvals, or to inspect, resume, signal, or cancel workflow runs. +--- + +# T3 Code workflows + +A workflow is a TypeScript function the T3 Code server runs durably on Effect v4 (`effect/workflow`). Every step's result is stored, so restarts replay to where the run left off and a failing step pauses the run instead of losing it. Runs can sleep for days, wait on signals or pull requests, ask a person a question, and launch agents in ordinary threads. + +Use a workflow for multi-stage work that must not be lost or repeated (triage → fix → verify, nightly reports, webhook reactions). For a single prompt on a timer, use a scheduled task instead. + +## Quick start + +Workflows are a Labs feature, off by default. If `t3 workflow` says workflows are off, ask the user to turn them on in Settings → Labs → Workflows; do not edit their settings yourself. + +Put a `.ts` file in `~/.t3/workflows/` (the `workflows` folder of T3 home, or the path in `T3CODE_WORKFLOWS`). Once workflows are on, the server watches the folder and reloads files automatically—nothing to restart. A file name with a space or other unusual character (`fix issue.ts`) is skipped with a warning in the server log: use letters, digits, `-`, `_` and `.`. Files run with Node's type stripping, so only erasable TypeScript works: no `enum`, `namespace` or parameter properties. + +Workflow files import nothing from T3 or Effect. `T3`, `Effect`, `Schema`, `Option`, `Duration`, and `Schedule` are injected as globals. Never `import` from `effect` (that loads a second runtime copy the engine cannot run). Node built-ins (`node:fs`, `node:crypto`) can be imported normally. + +```ts +const { workflow, agent, ask, stop, title, every, Tick } = T3; + +workflow( + "dependency-report", + { version: 1, payload: Tick, triggers: [every("1 day")] }, + Effect.fn(function* (tick) { + yield* title(`Dependencies ${tick.scheduledAt.slice(0, 10)}`); + + const audit = yield* agent("audit", { + project: "/home/me/app", // the project's folder, or its id + brief: "List this repository's outdated dependencies. Do not change any file.", + returns: Schema.Struct({ + outdated: Schema.Array(Schema.Struct({ name: Schema.String, latest: Schema.String })), + }), + }); + if (audit.value.outdated.length === 0) return yield* stop("nothing is outdated"); + + const answer = yield* ask("approve-upgrade", { + title: `Upgrade ${audit.value.outdated.length} dependencies?`, + choices: ["upgrade", "skip"], + data: audit.value, + timeout: "2 days", + }); + if (Option.isNone(answer) || answer.value.choice === "skip") { + return yield* stop("not approved"); + } + + yield* agent("upgrade", { + thread: audit.thread, + brief: "Upgrade the dependencies you listed, run the tests, and say what changed.", + }); + }), +); +``` + +### What `T3` holds + +Only `T3`, `Effect`, `Schema`, `Option`, `Duration` and `Schedule` are globals. Everything below is a +property of `T3`: take what you use at the top of the file, as the quick start does +(`const { workflow, step, daily } = T3;`), or write `T3.step(…)` in full. A bare `daily(…)` or +`step(…)` without that line is a `ReferenceError`. + +- **Definitions & body**: `workflow`, `step`, `agent`, `ask`, `wait`, `sleep`, `title`, `stop`, `skip`, `invoke` +- **Inside `step` / `onEnd` only**: `store`, `signal`, `signalAll`, `start`, `runs`, `cancel` +- **Trackers & hosts**: `issues`, `pullRequests` (triggers, step calls, and `pullRequests.wait` in the body) +- **Triggers**: `every`, `daily`, `webhook` +- **Schemas**: `Tick`, `WebhookRequest`, `Issue`, `IssueDetail`, `PullRequest`, `PullRequestStanding` + +### Effect v4 `Schema` cheatsheet + +```ts +Schema.String; +Schema.Number; +Schema.Boolean; +Schema.Void; +Schema.Null; +Schema.Struct({ name: Schema.String, count: Schema.optional(Schema.Number) }); +Schema.Array(Schema.String); +Schema.Literals(["open", "closed"]); +Schema.NullOr(Schema.String); +Schema.Record(Schema.String, Schema.Number); // two arguments, not an object +``` + +## Defining a workflow + +`workflow(name, options, body)` registers a workflow and returns a handle you can pass to `invoke`, `start`, `runs`, or `signal`. Each `(name, version)` pair must be unique across all files. + +| Option | Required | Meaning | +| ------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `version` | Yes | Integer version. Raise it whenever the body changes (see rules below). | +| `payload` | Yes | `Schema` of the run's input. | +| `returns` | No | `Schema` of the body's return value. If omitted, any JSON value (or `undefined`) is accepted. | +| `triggers` | No | Array of triggers that start runs automatically. | +| `resumeAfter` | No | Durations to wait before auto-resuming a paused run. Defaults to `["5 minutes", "20 minutes", "80 minutes"]`. The server checks about every 15 seconds, so shorter waits act as 15 seconds. | +| `onEnd` | No | `(payload, { id, outcome, reason }) => Effect`: cleanup hook run once when the run ends. | + +The body is `Effect.fn(function* (payload, run) { … })`, where `run.id` is the run's id. Use `yield*` on every primitive. + +### Cleanup with `onEnd` + +`onEnd` runs once when a run completes, stops, is skipped, or is cancelled—not when it pauses. It runs with step services (`store`, `signal`, `issues`, etc.), receives `(payload, { id, outcome, reason })`, and cannot see local variables from the body. Name external resources after `run.id`, and make `onEnd` safe if the run was cancelled before acquiring anything. + +```ts +const { workflow, step, agent, Issue } = T3; + +workflow( + "fix", + { + version: 1, + payload: Issue, + onEnd: (issue, end) => exec("machines.sh", ["delete", `fix-${end.id}`]), + }, + Effect.fn(function* (issue, run) { + const environment = yield* step( + "machine", + { returns: Schema.String }, + exec("machines.sh", ["create-and-link", `fix-${run.id}`]), + ); + yield* agent("fix", { environment, project: "/home/user/app", brief: issue.title }); + }), +); +``` + +(`exec` above is your own Effect helper, not part of `T3`.) On normal end, `onEnd` retries 3 times before pausing at the `onEnd` step; on cancel, it waits for any in-flight step to finish, then tries up to 5 times, 5 minutes, 20 minutes, 80 minutes and 5 hours apart. The workflow version stays required until one try succeeds; after the last failed try the `onEnd` step stays `failed` on the run and nothing retries it, so make cleanup something a person can redo by hand. + +## Body primitives + +Call these directly in the workflow body with `yield*`. Every named primitive stores its result under `name`, which must be unique across all primitives in the run (an `ask("fix", …)` and `agent("fix", …)` collide). + +| Call | Behavior | Returns | +| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------- | +| `step(name, { returns, retry? }, effect)` | Runs code once per run and journals the result. Failure pauses the run. | `A` | +| `step.try(name, { returns, retry? }, effect)` | Same as `step`, but returns failure as data instead of pausing. | `{ outcome: "done", value }` or `{ outcome: "failed", reason }` | +| `agent(name, { brief, project? \| thread?, returns?, … })` | Runs an agent in a thread. Failure pauses the run for a person. | `{ value, thread }` (`value` matches `returns`, or last reply string) | +| `agent.try(name, { brief, project? \| thread?, returns?, … })` | Same as `agent`, but returns failure as data instead of pausing. | `{ outcome: "done", value, thread }` or `{ outcome: "failed", reason, thread? }` | +| `ask(name, { title, choices, data?, timeout? })` | Puts a multiple-choice question to a person. | `Option<{ choice, reason? }>` (`None` on timeout) | +| `wait(name, { returns, timeout?, channel? })` | Sleeps until signalled by `{ runId, wait }` or `{ workflow, channel }`. | `Option` (`None` on timeout) | +| `pullRequests.wait(name, pr, { until, timeout? })` | Sleeps until PR checks settle, or the PR merges or closes. | `Option` (`None` on timeout) | +| `sleep(name, duration)` | Durable sleep across restarts (e.g. `"1 hour"`, `"2 days"`). | `void` | +| `invoke(name, workflow, payload, { key? })` | Runs another workflow as a child run and waits for it to end. | `{ outcome: "completed", value }` or `{ outcome: "stopped" \| "skipped" \| "cancelled", reason }` | +| `title(text)` | Sets the run's display title in lists (cut to 200 characters). Takes no step name. | `void` | +| `stop(reason)` | Ends the run on purpose as `stopped` (not a failure). Body only: inside a `step` it fails the step and pauses the run, and so does `skip`. | `never` | +| `skip(reason)` | Ends the run as `skipped`, which run lists leave out unless asked (`runs()` includes them). | `never` | + +- **Retries and failures:** A `step` runs once by default. For idempotent work, pass `retry: { times: 3, schedule: Schedule.exponential("2 seconds") }`. Nothing in the body can catch a failed `step` or `agent` because the engine pauses the run—use `step.try` or `agent.try` whenever the workflow should branch on failure. +- **Timeouts are checked about every 15 seconds:** a `wait` or `ask` timeout can end up to 15 seconds late, and a signal that arrives before the check still wins. +- **`Option` results:** `wait`, `ask` and `pullRequests.wait` always give an `Option`, with or without a `timeout`. Check `Option.isNone(result)` first, then read `result.value`. Never put the `Option` itself into a string or a return value. +- **Concurrency:** Run steps or agents in parallel with `Effect.all([agent("a", …), agent("b", …)], { concurrency: 2 })`. +- **Strict options:** Every call refuses an option it does not take, naming the ones it does, since workflow files are not type-checked. So does `every` under a minute and a `daily` time it cannot read. + +## Agents (`agent` and `agent.try`) + +| Option | Applies to | Meaning | +| ----------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | +| `brief` | All | Full task instructions. The agent sees only this brief and its project. | +| `project` | New thread | Project id (from `t3_project_list`) or absolute folder path. | +| `thread` | Continue | `thread` returned by an earlier `agent` step. Continues it as it started, so the New thread options are refused alongside it. | +| `returns` | All | Optional `Schema`. Completes only when the agent submits valid data (up to 2 correction prompts). | +| `model` | New thread | `{ instanceId, model, options? }`; `options` is `[{ id, value }]` (e.g. `[{ id: "reasoningEffort", value: "high" }]`). Defaults to project default. | +| `workspace` | New thread | `{ type: "root" }` (default) or `{ type: "worktree", baseRef: "origin/main", startFromOrigin: true }`. | +| `runtimeMode` | New thread | `"full-access" \| "auto" \| "auto-accept-edits" \| "approval-required"` (waits on thread approvals). Project default if omitted. | +| `interactionMode` | New thread | `"default" \| "plan"`. | +| `title` | New thread | Thread title. Defaults to `: `. | +| `environment` | New thread | Linked environment id (`t3 environment list`). Folder paths not yet registered there are registered automatically. | +| `issue` | Local only | `Issue` or `{ project, url }`. Links the thread to that issue (not applied in linked environments). | +| `timeout` | All | Time limit for each attempt (e.g. `"2 hours"`); an automatic retry or a resume starts a new one. Past it, the turn is stopped and the step fails. | +| `quiet` | All | Idle grace period (e.g. `"45 minutes"`) for agents that wait across turns before submitting `returns`. | + +- **Worktrees:** Use a `worktree` workspace whenever two agents can edit the same repo at once (concurrent runs or parallel `agent` calls). +- **Waiting across turns (`quiet`):** If an agent watches PR checks or background work and ends its turn while waiting to be woken, set `quiet: "45 minutes"` and tell it in `brief` to end waiting turns without submitting. The step prompts for the result only after the thread has been idle for `quiet`. Without `quiet`, it prompts as soon as a turn ends without output. Always set a `timeout` alongside `quiet`. +- **Retries and pauses:** If a turn dies (crashes or is cut off), `agent` automatically tries once more (on a fresh thread, or the same thread if continuing `thread`). An agent that finishes its turn without valid `returns` is asked to correct it twice in the same thread, and then gives up without starting the job again. A timeout or manual stop does not auto-retry. A run paused by an agent that ran and gave up or timed out waits for a person—`resumeAfter` does not auto-resume it (`t3 workflow resume` starts a fresh attempt). An agent that could not be started at all (no project at that folder, linked environment unreachable) pauses like a failed `step` and resumes on its own; `agent.try` returns that failure as data instead. +- **Fallback with `agent.try`:** + +```ts +Effect.fn(function* () { + let fix = yield* agent.try("fix", { project, brief, returns: Fix, timeout: "2 hours" }); + if (fix.outcome === "failed") { + fix = yield* agent.try("fix-again", { project, brief, returns: Fix, model: stronger }); + } + if (fix.outcome === "failed") return yield* stop(`no fix: ${fix.reason}`); +}); +``` + +- **Linked environments:** Enable Settings → Labs → Linked environments. The run stays on this server; only the thread runs remotely, bounded by the link's paired access. For a machine per run, create and link it in a `step` (`t3 auth pairing create --json` on the remote, `t3 environment link --pairing-code --access ` here), return its id, and delete it in `onEnd`. + +## Other workflows + +Define caller and callee in the same file and keep the callee in a variable so its payload and return type flow through: + +```ts +const { workflow, invoke, stop } = T3; + +const review = workflow("review", { version: 1, payload: Change, returns: Verdict }, reviewBody); + +workflow( + "fix", + { version: 1, payload: Issue }, + Effect.fn(function* (issue) { + const ended = yield* invoke("review", review, { branch: `fix/${issue.key}` }); + if (ended.outcome !== "completed") { + return yield* stop(`review ${ended.outcome}: ${ended.reason}`); + } + return ended.value; // Verdict + }), +); +``` + +| Call | Where | Behavior | +| ------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `invoke(name, workflow, payload, { key? })` | Body | Starts a child run and waits for it (including while it is paused). Listed and resumed independently; cancelling the parent cancels the child. Pass the definition `workflow(…)` returned, not its name. `key` names the child run; one already started under that key by something else is refused. | +| `start(workflow, payload, { key })` | `step` / `onEnd` | Fire-and-forget. Returns `{ runId }`. Same `key` returns the same run. Use for fan-out. | +| `runs({ workflow?, status?, keyPrefix? })` | `step` / `onEnd` | Lists up to 500 matching runs (skipped runs included), newest first: `{ id, workflow, key, title, status, detail, startedAt, endedAt }`. `workflow` is a definition or its name. | +| `cancel(runId, reason)` | `step` / `onEnd` | Cancels another run (stops agents, withdraws questions, cancels invoked children, runs `onEnd`). Cannot cancel self—use `stop`. | + +End subject keys with a separator (e.g. `issue/412/`), so `runs({ workflow: fix, keyPrefix: "issue/412/" })` does not match `issue/4120`. + +## Store and signals + +`store` holds durable key-value state shared across all workflows on the server (cursors, switches, counters, queues). Call `store`, `signal`, and `signalAll` **only inside `step` or `onEnd`**—never directly in the body. + +| Call | Behavior | +| ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `store.entry(key, Schema)` | Handle for one key: `.get` (`Option`), `.set(value)`, `.delete`. | +| `entry.update((current) => next)` | Atomic read-modify-write; `current` is `Option`. Return `undefined` to delete. Returns `Option`. | +| `store.entries(prefix, Schema)` | Every `{ key, value }` starting with `prefix`, in key order. Fails if any matching row does not fit `Schema`. | +| `store.transaction(effect)` | Runs all store reads and writes in `effect` atomically (all or nothing). | +| `signal(address, value, { id?, ttl? })` | Wakes one `wait` at `{ runId, wait }` or `{ workflow, channel }`. Buffered until a wait opens or `ttl` (default 7 days) expires. Returns `"delivered" \| "buffered"`. `"buffered"` checks neither the address nor the shape: a wrong workflow or wait name, or a run that has ended, also buffers. A value that does not fit an open wait fails the sending step. | +| `signalAll({ channel, workflow? }, value)` | Wakes every run currently waiting on `channel` (one workflow or all). Returns count woken. Buffers nothing. | + +```ts +const { step, store, Issue } = T3; +const seen = store.entry("issues/seen", Schema.String); + +Effect.fn(function* () { + const fresh = yield* step( + "fetch", + { returns: Schema.Array(Issue) }, + Effect.gen(function* () { + const since = yield* seen.get; + const batch = yield* fetchIssuesAfter(Option.getOrUndefined(since)); + if (batch[0]) yield* seen.set(batch[0].createdAt); + return batch; + }), + ); +}); +``` + +- **Shared gate pattern (`signalAll`):** Because `signalAll` keeps nothing for late arrivals, check the switch in a `step`, then while it is on call `wait` with `{ channel: "main-green", timeout: "10 minutes", returns: Schema.Null }` and re-check in a loop. Number step names per iteration (`switch/1`, `released/1`, `switch/2`, `released/2`). Whoever clears the switch calls `signalAll({ channel: "main-green" }, null)`. +- **Transactions:** Use `entry.update` or `store.transaction` whenever a write depends on a read, or when a step might fail after writing. +- **CLI access:** Inspect or flip keys with `t3 workflow store list [prefix]`, `store set ''`, and `store delete `. + +## Issues and pull requests + +Reads and writes the project's configured tracker (GitHub, GitLab, Linear, etc.) and git host using the project's credentials. Pass an issue/PR object from a trigger or `list`, or `{ project, url }` (useful when an agent returns a URL). + +| Call | Where | Returns | +| ----------------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------- | +| `issues.list({ project, state?, labels?, query?, assignee?, sort?, limit? })` | `step` / `onEnd` | `Issue[]` (`state` defaults to `"open"`) | +| `issues.read(issue)` | `step` / `onEnd` | `IssueDetail` (body, comments, valid `states`) | +| `issues.comment(issue, body)` | `step` / `onEnd` | `void` | +| `issues.setState(issue, name)` | `step` / `onEnd` | `void` (`name` from `issues.read(issue).states`) | +| `issues.create({ project, title, body?, labels?, assignees? })` | `step` / `onEnd` | `{ key, displayKey, url }` | +| `pullRequests.list({ project, state?, query?, limit? })` | `step` / `onEnd` | `PullRequest[]` (`state` defaults to `"open"`) | +| `pullRequests.read(pr)` | `step` / `onEnd` | State, checks, reviews, mergeability | +| `pullRequests.comment(pr, body)` | `step` / `onEnd` | `void` | +| `pullRequests.act(pr, action, { mergeMethod? })` | `step` / `onEnd` | `void` (`merge`, `close`, `ready`, `update-branch`, etc.) | +| `pullRequests.wait(name, pr, { until, timeout? })` | **Body** | `Option` (`{ state, checks, mergeability, url }`) | + +Keep one comment or mutation per `step` so a retry does not post twice. + +```ts +const { workflow, title, agent, step, issues, Issue } = T3; + +workflow( + "triage", + { version: 1, payload: Issue, triggers: [issues.opened({ project: "/home/me/app" })] }, + Effect.fn(function* (issue) { + yield* title(`${issue.displayKey} ${issue.title}`); + const found = yield* agent("reproduce", { + project: "/home/me/app", + issue, + brief: `Reproduce this on main. Change nothing.\n\n${issue.url}`, + returns: Schema.Struct({ reproduced: Schema.Boolean, summary: Schema.String }), + }); + yield* step("report", { returns: Schema.Void }, issues.comment(issue, found.value.summary)); + }), +); +``` + +`pullRequests.wait` polls about once a minute. `until` is `"checks"` (no checks still pending), `"merged"`, or `"closed"`. Merging or closing ends any wait, so always check `state` before `checks` (`"passing" | "failing" | "pending" | "none"`): + +```ts +Effect.fn(function* () { + const at = yield* pullRequests.wait( + "checks", + { project, url }, + { until: "checks", timeout: "2 hours" }, + ); + if (Option.isNone(at) || at.value.state !== "open" || at.value.checks !== "passing") { + return yield* stop("not ready to merge"); + } + yield* step("merge", { returns: Schema.Void }, pullRequests.act({ project, url }, "merge")); +}); +``` + +## Triggers + +A workflow's `payload` schema must match what its `triggers` emit. + +| Trigger | Payload | Notes | +| ------------------------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `every("1 hour")` | `Tick` | `{ scheduledAt }`. Minimum 1 minute. The first run comes one interval after the file loads, not at load. Downtime collapses into one run, not one per missed interval. | +| `daily("09:00", { weekdays?: [1, 2, 3, 4, 5] })` | `Tick` | Server local time; `0` is Sunday. Missed by more than 10 minutes is skipped. | +| `webhook("name", { key? })` | `WebhookRequest` | `{ method, headers, query, body }` (lowercase header names, text `query`/`body`). Set `payload: WebhookRequest`, taken from `T3`; never write its shape out yourself. `t3 workflow hooks` prints URL paths (includes secret). A retry that repeats a delivery header (`X-GitHub-Delivery`, `Idempotency-Key`, `webhook-id`, and the Gitea, GitLab and Linear ones) starts no second run; for other senders, `key: (r) => …` names the run from the request. Bodies over 1 MiB are refused. | +| `issues.opened({ project, labels?, query? })` | `Issue` | Polls ~once a minute. Only issues opened after the workflow first loaded. Issue must carry all `labels`. | +| `pullRequests.opened({ project, query? })` | `PullRequest` | Polls ~once a minute. Only pull requests opened after the workflow first loaded. | + +Filter unwanted deliveries in the body with `skip("not a push to main")` so they stay out of run lists. Verify webhook signatures inside a `step`. + +Start any workflow manually with `t3 workflow start --input '' --key `. A `key` identifies one run of that workflow across all versions. + +## Rules you must not break + +1. **The body is replayed from the top.** After every wait or restart, the body runs again and completed primitives return their stored values. Put all side effects, I/O, clock reads, randomness, and `store`/API reads inside `step` or `agent`. Code between calls must be deterministic given `payload` and earlier results. +2. **Names are journal keys.** Every named primitive (`step`, `agent`, `ask`, `wait`, `sleep`, `invoke`, `pullRequests.wait`) must have a unique name within the run, across all kinds. Loops need distinct names (``step(`check-${i}`, …)``). Never name a body step `"onEnd"` (reserved for cleanup). `invoke("x", …)` also takes `x/start`, and `title(…)` takes `title/0`, `title/1`, …. +3. **Bump `version` when changing a live workflow.** Do not reorder, rename, or change the stored schema of steps in a version that still has unfinished runs. Register the updated body under a higher `version` and keep the old version in the file until its runs finish. Runs started by the CLI, a trigger or a webhook use the highest version; `start` and `invoke` run the version of the definition you pass them, so point callers at the new definition when you bump. Keys still deduplicate across versions. +4. **Never import `effect`, and take every `T3` name you use.** The globals are `T3`, `Effect`, `Schema`, `Option`, `Duration` and `Schedule`; `step`, `daily`, `WebhookRequest` and the rest come from `const { … } = T3;` at the top of the file, and one left out of that line is a `ReferenceError`. Shared helpers go in a subfolder (dotfiles and folders are ignored by the loader), and changing an imported helper requires a server restart. +5. **Payloads and step results must fit their `Schema`.** Everything journaled is serialized as JSON; a value that fails encoding fails the step. +6. **Steps can run more than once.** A crash mid-step, a retry, or a manual resume re-runs the step. Make external side effects idempotent (derive idempotency keys from `payload` or `run.id`, keep one comment/post per step, wrap dependent store writes in `store.transaction`). + +## Files, reloading, and CLI + +If an edited file fails to load, its last good version keeps running and the server logs `A workflow definitions file was not loaded` with the reason. A change that defines the same `(name, version)` twice or removes a version with unfinished runs is rejected. The Workflows page shows these errors, and its Definitions view validates files on save. + +```sh +t3 workflow start --input '' --key +t3 workflow list [--status paused] +t3 workflow show [--json] +t3 workflow resume +t3 workflow cancel [--reason ''] +t3 workflow questions +t3 workflow signal '{"choice":"upgrade"}' --run --wait approve-upgrade +t3 workflow signal '' --workflow --channel +t3 workflow hooks +t3 workflow store list [prefix] +t3 workflow store set '' +t3 workflow store delete +``` + +- **Run states:** `running`, `waiting` (agent, signal, question, PR wait, or sleep), `paused` (step failed), `completed`, `stopped`, `skipped`, `cancelled`. +- **Resuming:** Check the failing step and error with `show`, fix the cause, then `resume` (only the failed step re-runs). A paused run also resumes by itself on `resumeAfter` (default 5, 20, 80 minutes), unless it paused because its agent gave up. +- **Retired runs:** A run whose version was removed shows `"retired": true` in `show --json` and cannot continue until that version is restored. +- **Stuck agents:** An agent step's thread is an ordinary thread—open it to inspect or steer the agent. The step finishes as soon as the agent submits its result.