diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td index 5c0f9e1f74a2a..a2981329cda25 100644 --- a/.github/VOUCHED.td +++ b/.github/VOUCHED.td @@ -46,6 +46,7 @@ github:jamesx0416 github:jappyjan github:jasonLaster github:JoeEverest +github:jschachter github:justsomelegs github:kridaydave github:lgwacker 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 c3fb7fad73ff8..8ce568c117dce 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -64,6 +64,7 @@ import { pastedPathQueryLength, } from "~/composer-logic"; import { useStableCallback } from "~/hooks/useStableCallback"; +import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { caretLineDirection, ComposerTextDirectionExtension } from "~/composer-text-direction"; import { collapseShownMarkdownSource, @@ -203,6 +204,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; @@ -1127,6 +1130,7 @@ function ComposerPromptEditorTiptapInner( suppressTrigger, contextIds, previousSnapshot.value !== nextValue, + isHistoryTransaction(transaction), ); }; @@ -1762,6 +1766,11 @@ function ComposerPromptEditorTiptapInner( if (replacements.length > 0) replaceSkillChips(editor, replacements); }, [editor, literalText, modelKeys, skills]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the mounted editor's visible text anchored while its DOM width changes + useLayoutEffect(() => { + if (editor) return preserveReadingPosition(editor.view.dom); + }, [editor]); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores ProseMirror focus and caret scroll when the keyed editor remounts, capturing focus on teardown useLayoutEffect(() => { if (!editor) return; @@ -1975,7 +1984,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/HistorySwipeNavigation.browser.test.tsx b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx index d2a15729b0df2..d36efc1d535d7 100644 --- a/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.browser.test.tsx @@ -24,7 +24,19 @@ describe("HistorySwipeNavigation", () => { false, ], ["scrolling left inside a scroller keeps the thread", "light", 100, -130, false], - ["swiping back at a shadow-root scroller's left edge navigates", "shadow", 0, -130, true], + ["scrolling at a shadow-root scroller's left edge keeps the thread", "shadow", 0, -130, false], + [ + "scrolling at a shadow-root scroller's right edge keeps the thread", + "shadow", + 800, + 130, + false, + ], + ["scrolling at a scroller's left edge keeps the thread", "light", 0, -130, false], + ["scrolling at a scroller's right edge keeps the thread", "light", 800, 130, false], + ["scrolling over a preview panel keeps the thread", "preview-panel", 0, -130, false], + ["scrolling over a desktop preview keeps the thread", "preview-viewport", 0, 130, false], + ["scrolling over a streamed preview keeps the thread", "server-browser", 0, -130, false], ["swiping back over a panel without overflow navigates", "none", 0, -130, true], ["a swipe that started in a closed dialog keeps the thread", "closed-dialog", 0, -130, false], ] as const)("%s", async (_name, scroller, scrollLeft, deltaX, navigates) => { @@ -34,7 +46,10 @@ describe("HistorySwipeNavigation", () => { const panel = screen.container.appendChild(document.createElement("div")); const root = scroller.startsWith("shadow") ? panel.attachShadow({ mode: "open" }) : panel; const viewport = root.appendChild(document.createElement("div")); - const noOverflow = scroller === "none" || scroller === "closed-dialog"; + const noOverflow = !scroller.startsWith("shadow") && scroller !== "light"; + if (scroller === "preview-panel") panel.setAttribute("data-preview-panel-mode", "inline"); + if (scroller === "preview-viewport") panel.setAttribute("data-preview-viewport", "tab"); + if (scroller === "server-browser") panel.setAttribute("data-server-browser-surface", "tab"); viewport.style.cssText = `width: 200px; overflow-x: ${noOverflow ? "visible" : "auto"}`; const content = viewport.appendChild(document.createElement("div")); content.style.cssText = `height: 20px; width: ${noOverflow ? 100 : 1000}px`; @@ -72,6 +87,32 @@ describe("HistorySwipeNavigation", () => { expect(navigateHistory).not.toHaveBeenCalled(); }); + it.each([ + ["Shift-scroll keeps the thread", [[-130, true]]], + [ + "pressing Shift during a swipe cancels navigation", + [ + [-130, false], + [-1, true], + ], + ], + [ + "releasing Shift during a scroll keeps the thread", + [ + [-1, true], + [-130, false], + ], + ], + ] as const)("%s", async (_name, events) => { + navigateHistory.mockReset(); + using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("MacIntel"); + await using screen = await render(); + for (const [deltaX, shiftKey] of [...events, [0, false] as const]) { + screen.container.dispatchEvent(new WheelEvent("wheel", { deltaX, shiftKey, bubbles: true })); + } + expect(navigateHistory).not.toHaveBeenCalled(); + }); + // A vertical scroll 15° off vertical. const drift = Array.from({ length: 30 }, () => [-4, 15] as const); it.each([ diff --git a/apps/web/src/components/HistorySwipeNavigation.tsx b/apps/web/src/components/HistorySwipeNavigation.tsx index 2924f82cd3136..09b363c2d1f7e 100644 --- a/apps/web/src/components/HistorySwipeNavigation.tsx +++ b/apps/web/src/components/HistorySwipeNavigation.tsx @@ -44,16 +44,12 @@ function readMainContentBounds(): SwipeBounds { } // `event.target` stops at a shadow host; the composed path also reaches scrollers inside it. -function canScrollHorizontally(path: readonly EventTarget[], deltaX: number): boolean { +function hasHorizontalScroller(path: readonly EventTarget[]): boolean { for (const element of path) { if (!(element instanceof Element) || element.scrollWidth <= element.clientWidth) continue; const { overflowX } = getComputedStyle(element); if (overflowX !== "auto" && overflowX !== "scroll") continue; - const canScroll = - deltaX < 0 - ? element.scrollLeft > 0 - : element.scrollLeft + element.clientWidth < element.scrollWidth - 1; - if (canScroll) return true; + return true; } return false; } @@ -71,10 +67,19 @@ function lockSwipeAxis( if (Math.abs(sumX) <= Math.abs(sumY) || isVerticalScroll(Math.abs(sumX), Math.abs(sumY))) { return { kind: "ignored" }; } - if (path.some((node) => node instanceof Element && node.matches('[role="dialog"]'))) { + // Preview contents can scroll in another document or on the server, outside this DOM. + if ( + path.some( + (node) => + node instanceof Element && + node.matches( + '[role="dialog"], [data-preview-panel-mode], [data-preview-viewport], [data-server-browser-surface]', + ), + ) + ) { return { kind: "ignored" }; } - if (canScrollHorizontally(path, sumX)) return { kind: "ignored" }; + if (hasHorizontalScroller(path)) return { kind: "ignored" }; const direction = sumX < 0 ? "back" : "forward"; if (!canNavigateHistory(direction)) return { kind: "ignored" }; return { @@ -134,6 +139,11 @@ export function HistorySwipeNavigation() { gesture = null; }); const onWheel = (event: WheelEvent) => { + if (event.shiftKey) { + if (gesture?.kind === "tracking") hideIndicator(); + gesture = { kind: "ignored" }; + return; + } if (gesture === null) { gesture = event.ctrlKey || event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL 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/RightPanelTabs.browser.test.tsx b/apps/web/src/components/RightPanelTabs.browser.test.tsx index 515d5cdbfb32b..347971993c7c3 100644 --- a/apps/web/src/components/RightPanelTabs.browser.test.tsx +++ b/apps/web/src/components/RightPanelTabs.browser.test.tsx @@ -68,7 +68,7 @@ const surfaces: RightPanelSurface[] = Array.from({ length: 16 }, (_, index) => ( })); describe("RightPanelTabs", () => { - it("a flick that scrolls the tab strip to its left edge keeps the thread, a swipe from the edge goes back", async () => { + it("a flick that scrolls the tab strip to its left edge keeps the thread, and so does a swipe from the edge", async () => { navigateHistory.mockReset(); const { bridge, scroll } = trackpad(); using _bridge = stubGlobal("desktopBridge", bridge); @@ -139,7 +139,7 @@ describe("RightPanelTabs", () => { viewport.scrollLeft = 0; scroll(viewport.querySelector("[data-active-tab]")!, [-40, -40, -40, -40, -40]); - expect(navigateHistory).toHaveBeenCalledExactlyOnceWith("back"); + expect(navigateHistory).not.toHaveBeenCalled(); }); }); diff --git a/apps/web/src/components/Sidebar.browser.test.tsx b/apps/web/src/components/Sidebar.browser.test.tsx index 1a0b4c588d64c..1fb930f55fabc 100644 --- a/apps/web/src/components/Sidebar.browser.test.tsx +++ b/apps/web/src/components/Sidebar.browser.test.tsx @@ -329,6 +329,57 @@ describe("sidebar thread rename", () => { ); }); +describe("sidebar thread click", () => { + // regression: #40715 macOS counts quick clicks on different rows, so the next row got detail 2 and was ignored + it("opens another thread when the click arrives with a double-click count", async () => { + const activeProject = project("active"); + const threads = [threadShell(activeProject.id, 0), threadShell(activeProject.id, 1)]; + const routeThreadRef: ScopedThreadRef = { + environmentId: activeProject.environmentId, + threadId: threads[0]!.id, + }; + vi.mocked(useProjects).mockReturnValue([activeProject]); + vi.mocked(useQuietThreadShells).mockReturnValue(threads); + vi.mocked(useThreadRouteTarget).mockReturnValue({ kind: "server", threadRef: routeThreadRef }); + vi.mocked(useHandleNewThread).mockReturnValue({ + activeDraftThread: null, + activeThread: null, + defaultProjectRef: { + environmentId: activeProject.environmentId, + projectId: activeProject.id, + }, + defaultProjectFallbackReady: true, + handleNewThread: vi.fn().mockResolvedValue(null), + routeDraftId: null, + routeThreadRef, + }); + await using screen = await render( + + + , + { router: "/local/thread-0" }, + ); + const navigate = vi.spyOn(screen.router!, "navigate").mockResolvedValue(undefined); + + const openRow = screen.getByText("Thread 0").first().element(); + await act(() => { + openRow.dispatchEvent( + new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 }), + ); + }); + expect(navigate).not.toHaveBeenCalled(); + + const row = screen.getByText("Thread 1").first().element(); + await act(() => { + row.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 2 })); + }); + + expect(navigate).toHaveBeenCalledWith( + expect.objectContaining({ params: expect.objectContaining({ threadId: "thread-1" }) }), + ); + }); +}); + describe("sidebar thread menu", () => { it("tells the menu whether the keyboard opened it", async () => { const activeProject = project("active"); 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 98ed2224169cd..2a8dcdff50d86 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"; @@ -187,6 +187,7 @@ import { buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, deleteSelectedThreadEntries, + ADD_PROJECT_SCOPE_ITEM_VALUE, filterSidebarProjectScopeItems, firstValidTimestampMs, isSidebarNestedLinkClick, @@ -271,7 +272,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, @@ -430,6 +436,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. @@ -444,9 +451,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; @@ -512,11 +521,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); } @@ -524,10 +533,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); @@ -835,6 +844,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, @@ -1160,6 +1170,13 @@ 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); // Pinning from a row keeps rows in place while the menu is open. const projectScopeItems = useOrderWhileOpen( @@ -1171,7 +1188,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, @@ -1189,13 +1206,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 ( @@ -1340,6 +1361,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. @@ -1429,7 +1451,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; @@ -1586,7 +1612,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve rangeSelectTo(threadKey, orderedThreadKeysRef.current); return; } - if (isTrailingDoubleClick(event.detail)) { + // macOS keeps counting quick clicks across rows, so only the open row's trailing click is a double-click. + if (isTrailingDoubleClick(event.detail) && routeThreadKey === threadKey) { return; } navigateToThread(threadRef); @@ -1626,9 +1653,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( @@ -1651,6 +1680,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSettle?.(); + } else { + stayOnRouteThread(threadKey); } })(); }; @@ -2184,6 +2215,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), ); @@ -2198,6 +2230,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) navigateAfterSettle?.(); + else stayOnRouteThread(activeKey); return; } case "move-active": @@ -2253,9 +2286,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); @@ -2270,6 +2305,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSnooze?.(); + } else { + stayOnRouteThread(threadKey); } return { status: "success" } as const; }; @@ -3047,7 +3084,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 && @@ -3066,12 +3106,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") } /> } @@ -3096,7 +3136,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) : ( - + )} {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} @@ -3158,6 +3198,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) @@ -3233,7 +3283,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } - onNewProject={openAddProjectCommandPalette} onNewThread={handleNewThreadClick} newThreadDisabled={projects.length === 0} newThreadShortcutLabel={newThreadShortcutLabel} @@ -3555,6 +3604,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/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 6fb651c3471f6..5b540f48c483e 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,7 +135,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, - isImageOnlyClipboardHtml, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -213,6 +216,7 @@ import { } from "./ComposerCommandMenu"; import { ComposerAttachButton, + ComposerAttachInput, ComposerAttachmentFileList, ComposerAttachmentMediaRow, ComposerFilePreviewDialog, @@ -286,6 +290,7 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; import { cancelHeldComposerSend, countPreparingComposerImages, @@ -456,8 +461,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: ( @@ -598,7 +606,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onExpandImage, onFileOpen, editingQueuedAttachments, + removedEditingQueuedAttachments, onRemoveEditingQueuedAttachment, + onRestoreEditingQueuedAttachment, } = props; const { activePendingProgress: incomingPendingProgress, @@ -656,6 +666,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 = @@ -756,33 +772,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) => useRightPanelStore.getState().openFile(routeThreadRef, 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) => { @@ -797,6 +835,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; @@ -1080,6 +1120,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); @@ -1392,12 +1433,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({ @@ -1446,6 +1495,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 @@ -1651,6 +1702,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], textChanged: boolean, + fromHistory = false, ) => { refreshWorkspaceSnapshotOnTyping(); const trigger = cursorAdjacentToMention @@ -1761,6 +1813,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, @@ -1780,6 +1840,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); }; @@ -2947,18 +3013,19 @@ 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 && + (canAttachFiles && shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment, - htmlIsOnlyImage: - plainText.length > 0 && - isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + htmlIsOnlyImage: htmlImageContent === "only-image", })) ) { event.preventDefault(); @@ -2971,6 +3038,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; } @@ -3542,10 +3616,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) /> ) : null; const composerAttachButton = showComposerAttachAction ? ( - + composerAttachInputRef.current?.click()} /> ) : null; return (
+ {showComposerAttachAction ? ( + + ) : null}
0 && ( + activeEditingQueuedAttachments !== null && + activeEditingQueuedAttachments.length > 0 && ( )} 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/ComposerModelEffort.browser.test.tsx b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx index ab7d560d5c676..1678552dd0ab2 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx @@ -122,3 +122,27 @@ it("draws an agent's reasoning as bars and keeps its mode out of the levels", as .toBeInTheDocument(); await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); }); + +it("focuses a reasoning level by its first letter without selecting it", async () => { + await using screen = await render(, { router: false }); // no routes involved + await userEvent.tab(); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("l"); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + await expect + .element(screen.getByRole("radio", { name: "Medium" })) + .toHaveAttribute("aria-checked", "true"); + for (const key of ["{Control>}h{/Control}", "{Meta>}h{/Meta}", "{Alt>}h{/Alt}", "{Delete}"]) { + await userEvent.keyboard(key); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + } + await userEvent.keyboard("H"); + await expect.element(screen.getByRole("radio", { name: "High" })).toHaveFocus(); + // Wraps past the last level back to the first match. + await userEvent.keyboard("m"); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("h{Enter}"); + await expect + .element(screen.getByRole("radio", { name: "High" })) + .toHaveAttribute("aria-checked", "true"); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.tsx b/apps/web/src/components/chat/ComposerModelEffort.tsx index 1d0227c0f6482..b5d5a519a3410 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.tsx @@ -206,8 +206,8 @@ function ColumnRow(props: { "aria-checked": props.selected, disabled: props.disabled, "data-effort-row": true, - // Focus lands on a level after a model pick. - "data-effort-level": true, + // Focus lands on a level after a model pick, and a typed letter finds one by its label. + "data-effort-level": props.label, // Up and Down move between rows. tabIndex: props.tabStop ? 0 : -1, className: COLUMN_ROW, @@ -244,15 +244,28 @@ function ColumnRow(props: { } function moveBetweenRows(event: KeyboardEvent) { - if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; + const arrow = event.key === "ArrowDown" || event.key === "ArrowUp"; + if ( + !arrow && + (event.key.length !== 1 || + event.key.trim() === "" || + event.ctrlKey || + event.altKey || + event.metaKey || + event.nativeEvent.isComposing) + ) + return; // An option's side menu is a React child here, but it moves through its own items. if (!event.currentTarget.contains(event.target as Node)) return; const rows = Array.from( event.currentTarget.querySelectorAll("[data-effort-row]:not(:disabled)"), ); const index = rows.findIndex((row) => row === document.activeElement); - const next = - rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))]; + const next = arrow + ? rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))] + : [...rows.slice(index + 1), ...rows.slice(0, index + 1)].find((row) => + row.dataset.effortLevel?.toLowerCase().startsWith(event.key.toLowerCase()), + ); if (!next) return; event.preventDefault(); event.stopPropagation(); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index c55d843510080..46e3fec307bf1 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -3,6 +3,7 @@ import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react"; import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { RelativeTime } from "../RelativeTime"; import { m, type MessageResolver } from "~/i18n/messages"; @@ -18,7 +19,9 @@ function missingImageCount(entry: PromptStashEntry): number { export function stashEntrySnippet(entry: PromptStashEntry, resolve: MessageResolver = m): string { const trimmed = assistantCitationsToPlainText( - replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + ), ) .trim() .replace(/\s+/g, " "); diff --git a/apps/web/src/components/chat/FeedbackRequestCard.tsx b/apps/web/src/components/chat/FeedbackRequestCard.tsx new file mode 100644 index 0000000000000..4cd7bcb9f92ca --- /dev/null +++ b/apps/web/src/components/chat/FeedbackRequestCard.tsx @@ -0,0 +1,218 @@ +import { T, msg, useMessages } from "gt-react"; +import { pipe } from "effect/Function"; +import { + feedbackCardPreview, + feedbackConversationHint, + feedbackPreviewFields, + feedbackRequestDisplay, + feedbackRequestFailureMessage, + type FeedbackRequestItem, + feedbackTraceLines, + feedbackTraceSummary, +} from "@t3tools/client-runtime/feedback-request"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, +} from "@t3tools/client-runtime/state/runtime"; +import type { + AgentFeedbackPreview, + EnvironmentId, + OrchestrationV2ProjectedTurnItem, +} from "@t3tools/contracts"; +import { CheckIcon, ChevronDownIcon, LockIcon, MessageSquareIcon, MinusIcon } from "lucide-react"; +import { useAtomValue } from "@effect/atom-react"; +import { useRef, useState } from "react"; + +import { serverEnvironment } from "../../state/server"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { Button } from "../ui/button"; +import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible"; +import { Switch } from "../ui/switch"; +import { WorkLogRow } from "./WorkLog"; + +const TITLE = msg("Feedback for the T3 team"); + +export function FeedbackRequestCard(props: { + readonly environmentId: EnvironmentId; + readonly item: FeedbackRequestItem; + readonly visibility: OrchestrationV2ProjectedTurnItem["visibility"]; +}) { + const m = useMessages(); + const { item } = props; + const display = feedbackRequestDisplay(item, props.visibility, m); + if (display.kind !== "pending") { + const Icon = + display.kind === "pending-elsewhere" + ? LockIcon + : display.outcome === "sent" + ? CheckIcon + : MinusIcon; + return ( + + } + label={ + <> + {m(TITLE)} · {display.label} + + } + trailing={} + /> + } + /> + +
+ +
+
+
+ ); + } + return ; +} + +function PendingFeedbackRequest(props: { + readonly environmentId: EnvironmentId; + readonly item: FeedbackRequestItem; +}) { + const m = useMessages(); + const answer = useAtomCommand(serverEnvironment.answerFeedbackRequest, { + label: "answer feedback request", + reportFailure: false, + }); + const canAnswer = useAtomValue( + serverEnvironment.answerFeedbackRequest.permissionAtom(props.environmentId), + ); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + const [includeConversation, setIncludeConversation] = useState(false); + // Two clicks can land before a render. + const inFlight = useRef(false); + + const send = async (reply: "send" | "decline") => { + if (inFlight.current) return; + inFlight.current = true; + setSubmitting(true); + setError(null); + const result = await answer({ + environmentId: props.environmentId, + input: { + threadId: props.item.threadId, + turnItemId: props.item.id, + answer: reply, + includeConversation, + }, + }).finally(() => { + inFlight.current = false; + setSubmitting(false); + }); + if (result._tag === "Success" || isAtomCommandInterrupted(result)) return; + pipe( + squashAtomCommandFailure(result), + (failure) => feedbackRequestFailureMessage(failure, m), + setError, + ); + }; + const disabled = submitting || !canAnswer; + + return ( +
+
+

+ + Send this report to the T3 team? +

+

+ This is everything that leaves your machine. Nothing is sent unless you press Send. +

+
+ {props.item.conversationTrace !== undefined ? ( + + ) : null} + + {error !== null ? ( +

+ {error} +

+ ) : !canAnswer ? ( +

+ Only someone who can run agents on this machine can send or decline it. +

+ ) : null} +
+ + +
+
+ ); +} + +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/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index d15a26ca43db0..bce13bb454379 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -626,6 +626,48 @@ describe("MessagesTimeline messages", () => { await vi.waitFor(() => expect(viewport.scrollTop).toBeLessThan(atEnd)); }); + it("keeps the visible sentence in a long message when the chat width changes", async () => { + setup(); + const size = { width: window.innerWidth, height: window.innerHeight }; + onTestFinished(() => page.viewport(size.width, size.height)); + await page.viewport(1200, 1400); + const props = { ...baseProps(), liveFollowEnabled: false }; + const paragraphs = Array.from( + { length: 30 }, + (_, index) => + `Paragraph ${index + 1}. ${"A side panel should not move the sentence being read out of view. ".repeat(5)}`, + ); + await using screen = await renderTimeline( + [message(paragraphs.join("\n\n"), { role: "assistant" })], + props, + ); + screen.container.style.width = "900px"; + const viewport = props.listRef.current!.getScrollableNode()!; + const target = page.getByText(paragraphs[15]!.trim(), { exact: true }).element(); + await vi.waitFor(() => { + expect(viewport.scrollHeight).toBeGreaterThan(1000); + expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); + }); + await props.listRef.current!.scrollToOffset({ + offset: + viewport.scrollTop + + target.getBoundingClientRect().top - + viewport.getBoundingClientRect().top - + 24, + animated: false, + }); + viewport.dispatchEvent(new Event("scroll")); + const before = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(before - 24)).toBeLessThan(2); + for (const width of [500, 900]) { + screen.container.style.width = `${width}px`; + await vi.waitFor(() => { + const after = target.getBoundingClientRect().top - viewport.getBoundingClientRect().top; + expect(Math.abs(after - before)).toBeLessThan(30); + }); + } + }); + it("disables the minimap's next turn button at the bottom of the thread", async () => { setup(); const props = baseProps(); 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 b00a48185b9db..6bd30f1ac3212 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1056,8 +1056,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); @@ -1612,6 +1613,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; @@ -1663,7 +1666,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( @@ -2376,6 +2383,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(); @@ -2383,6 +2395,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 89cc3f8701c55..aaaba1d4bc921 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,5 +1,6 @@ import { T, useGT, useMessages, Var } from "gt-react"; import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import type { ThreadRunSummary } from "@t3tools/client-runtime/state/models"; import { threadErrorText } from "@t3tools/client-runtime/state/threads"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -26,6 +27,7 @@ import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor"; import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime"; import { observeResize } from "~/lib/observeResize"; +import { preserveReadingPosition } from "~/lib/preserveReadingPosition"; import { useStableCallback } from "~/hooks/useStableCallback"; const NOOP_USE_ARTIFACT_TEMPLATE = () => {}; @@ -241,6 +243,7 @@ interface MessagesTimelineProps { activeTurnStartedAt?: string | null; /** Replaces "Thinking" while the active run's provider has not started a turn. */ providerStartingLabel?: string | null; + providerStarting?: NonNullable | null; worktreeSetup?: WorktreeSetupSnapshot | null; onCancelWorktreeSetup?: () => void; retryableWorkspacePreparationRunIds?: ReadonlySet; @@ -257,6 +260,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. */ @@ -287,6 +291,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; @@ -362,6 +368,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ runlessWorkActive = false, activeTurnStartedAt = null, providerStartingLabel = null, + providerStarting = null, worktreeSetup = null, footer = null, onCancelWorktreeSetup, @@ -381,6 +388,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ activeFindMatch = null, findNavigationId = 0, latestRun, + usageLimitRunId = null, announcedRun = null, detailBehindShell = false, runningRunId = null, @@ -748,6 +756,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ timelineEntries, pendingApprovalRequestIds, latestRun, + usageLimitRunId, runningRunId, expandedRunIds: visibleExpandedRunIds, expandedAttemptIds: visibleExpandedAttemptIds, @@ -1187,6 +1196,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ awaitingUser: awaitingUser !== null, isPreparingWorktree, providerStartingLabel, + providerStarting, latestRunId: latestRun?.runId ?? null, liveAnswerPreview: isWorking && toolCallVisibility === "zen" ? liveAnswerPreview(timelineEntries) : null, @@ -1218,13 +1228,14 @@ const ConversationTimeline = memo(function ConversationTimeline({
@@ -1252,6 +1266,14 @@ const ConversationTimeline = memo(function ConversationTimeline({ const canvas = useChatCanvas(); const registerTimeline = canvas?.registerTimeline; + const shouldPreserveReadingPosition = useStableCallback( + () => + !liveFollowEnabled && + !anchoredEndSpace && + !findActive && + !citationPositioning && + !restoringThreadPosition, + ); // Stable so the list attaches once per mount, not on every render. const setTimelineList = useStableCallback((list: LegendListRef | null) => { listRef.current = list; @@ -1267,6 +1289,9 @@ const ConversationTimeline = memo(function ConversationTimeline({ }) : null; viewportRef.current = viewport; + const stopPreservingReadingPosition = scrollNode + ? preserveReadingPosition(scrollNode, shouldPreserveReadingPosition) + : undefined; const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined; const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition); const stopDisclosureReveal = viewport?.subscribe(() => { @@ -1295,6 +1320,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ scheduleContentSizeChanged(); return () => { stopListeningToContentSize?.(); + stopPreservingReadingPosition?.(); stopRememberingRelease?.(); stopDisclosureReveal?.(); if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame); diff --git a/apps/web/src/components/chat/ProviderStartingIcon.tsx b/apps/web/src/components/chat/ProviderStartingIcon.tsx new file mode 100644 index 0000000000000..634f1f742f1d6 --- /dev/null +++ b/apps/web/src/components/chat/ProviderStartingIcon.tsx @@ -0,0 +1,67 @@ +import { useAtomValue } from "@effect/atom-react"; +import { + type EnvironmentId, + PROVIDER_DISPLAY_NAMES, + type ProviderDriverKind, + type ProviderInstanceId, +} from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { Atom } from "effect/reactivity"; + +import { brandProviderInstanceEntries, deriveProviderInstanceEntries } from "~/providerInstances"; +import { serverEnvironment } from "~/state/server"; +import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; + +interface ProviderStartingPresentation { + readonly displayName: string; + readonly acpRegistryAgentId: string | undefined; + readonly acpRegistryIconUrl: string | undefined; +} + +// Keyed per instance so provider status pushes don't rerender the live row. +const providerStartingPresentationAtom = Atom.family((key: string) => + Atom.make((get): ProviderStartingPresentation | null => { + const [environmentId, instanceId] = key.split("\u0000") as [string, string]; + const config = get(serverEnvironment.configValueAtom(environmentId as EnvironmentId)); + const provider = config?.providers.find((candidate) => candidate.instanceId === instanceId); + if (!config || !provider) return null; + const [entry] = brandProviderInstanceEntries( + deriveProviderInstanceEntries([provider]), + config.settings, + ); + if (!entry) return null; + const next = { + displayName: entry.displayName, + acpRegistryAgentId: entry.acpRegistryAgentId, + acpRegistryIconUrl: entry.acpRegistryIconUrl, + }; + const previous = Option.getOrNull(get.self()); + return previous && + previous.displayName === next.displayName && + previous.acpRegistryAgentId === next.acpRegistryAgentId && + previous.acpRegistryIconUrl === next.acpRegistryIconUrl + ? previous + : next; + }).pipe(Atom.withLabel("provider-starting-presentation")), +); + +/** The logo of the provider a run is waiting on, shown in place of the thinking icon. */ +export function ProviderStartingIcon(props: { + readonly environmentId: EnvironmentId | null; + readonly instanceId: ProviderInstanceId; + readonly driver: ProviderDriverKind; +}) { + const presentation = useAtomValue( + providerStartingPresentationAtom(`${props.environmentId ?? ""}\u0000${props.instanceId}`), + ); + return ( + + ); +} 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 076c78d88d468..8b4bb6232287b 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -141,9 +141,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, @@ -205,12 +210,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 1b179329994f9..02817cbc32ed5 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 ? (
@@ -517,6 +542,7 @@ function LiveActivityRow({ function LiveActivityContent({ label, iconName, + iconNode, toolIcon, failed = false, announceFailure = false, @@ -525,6 +551,7 @@ function LiveActivityContent({ }: { label: ReactNode; iconName: WorkEntryIconName | undefined; + iconNode?: ReactNode; toolIcon?: ToolActivityIcon | undefined; failed?: boolean; announceFailure?: boolean; @@ -551,12 +578,16 @@ function LiveActivityContent({ role={announceFailure ? "img" : undefined} aria-label={announceFailure ? gt("Tool call failed") : undefined} > - + {iconNode ? ( + {iconNode} + ) : ( + + )} ) : null } diff --git a/apps/web/src/components/chat/composerAttachmentFiles.test.ts b/apps/web/src/components/chat/composerAttachmentFiles.test.ts index f842566d7cd60..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"; @@ -141,6 +142,12 @@ describe("composer attachment files", () => { 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 191c5841185ff..538d2dfd67304 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -247,11 +247,33 @@ function isOnlyFileNames(text: string, files: ReadonlyArray): boolean { .every((line) => names.has(line)); } -/** A browser's Copy Image puts only an in text/html; rich text sources put the text there. */ -export function isImageOnlyClipboardHtml(html: string): boolean { - if (html.length === 0) return false; +/** + * 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; - return body.querySelector("img") !== null && (body.textContent ?? "").trim().length === 0; + 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: { @@ -269,10 +291,7 @@ export function shouldHandleComposerAttachmentPaste(input: { ) { return true; } - const hasImage = input.files.some((file) => { - const classification = classifyComposerAttachmentFile(file); - return classification === "image" || classification === "unsupported-image"; - }); + const hasImage = input.files.some(isPastedImageFile); if (input.plainText.length === 0) { return hasImage || input.files.some((file) => classifyComposerAttachmentFile(file) === "file"); } 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/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/timelineRowContext.ts b/apps/web/src/components/chat/timelineRowContext.ts index 5ff5c032db981..139379fbeefda 100644 --- a/apps/web/src/components/chat/timelineRowContext.ts +++ b/apps/web/src/components/chat/timelineRowContext.ts @@ -1,5 +1,6 @@ import type { ToolCallDiffTarget } from "../../diffPanelStore"; import type { SideThreadOpenIntent } from "@t3tools/client-runtime/side-thread"; +import type { ThreadRunSummary } from "@t3tools/client-runtime/state/models"; import type { ProviderApprovalDecision, ResponseContextRecord, @@ -117,6 +118,7 @@ export interface TimelineRowActivityState { awaitingUser: boolean; isPreparingWorktree: boolean; providerStartingLabel: string | null; + providerStarting: NonNullable | null; latestRunId: RunId | null; backgroundWorktreeSetup: WorktreeSetupSnapshot | null; liveAnswerPreview: string | null; 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/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index bc38e5001dde1..18a9a54715a38 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -67,7 +67,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, @@ -1754,8 +1754,7 @@ export function useComposerSend(input: ComposerSendInput) { }; 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 @@ -1767,6 +1766,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 ab7ce9b40186b..0fb3f31e5413e 100644 --- a/apps/web/src/components/composerContextPresentation.tsx +++ b/apps/web/src/components/composerContextPresentation.tsx @@ -2,7 +2,10 @@ import ChatMarkdown from "./ChatMarkdown"; import { isSvgAttachment } from "@t3tools/shared/image"; import { ReadOnlySourcePreview } from "./files/AttachmentFilePreview"; import type { + ChatAttachment, + ComposerContextId, EnvironmentContextRecord, + EnvironmentId, PreviewAnnotationPayload, ThreadContextRecord, } from "@t3tools/contracts"; @@ -40,6 +43,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"; @@ -60,6 +64,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 } @@ -68,8 +77,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 }; @@ -84,7 +103,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( @@ -99,9 +118,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", @@ -183,7 +237,7 @@ function useUploadStatusSuffix( } function attachmentTooltip( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: Pick, upload: AttachmentUploadState | undefined, resolve: MessageResolver, ): string { @@ -193,7 +247,7 @@ function attachmentTooltip( } function ImageContextChip(props: { - record: ComposerImageAttachment; + record: ComposerImageContextAttachment; upload: AttachmentUploadState | undefined; }) { const actions = use(ComposerContextActionsContext); diff --git a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx index add8d7368e2ab..9316935ba2df0 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx @@ -499,48 +499,56 @@ describe("bounded binary previews", () => { } }); - it("keeps WhiteIsZero TIFF brightness and rejects oversized metadata before decoding", async () => { - const tags = [ - [256, 2], - [257, 1], - [258, 8], - [259, 1], - [262, 0], - [273, 134], - [277, 1], - [278, 1], - [279, 2], - [284, 1], - ]; - const bytes = new ArrayBuffer(136); - const view = new DataView(bytes); - view.setUint16(0, 0x4949); - view.setUint16(2, 42, true); - view.setUint32(4, 8, true); - view.setUint16(8, tags.length, true); - tags.forEach(([tag, value], index) => { - const offset = 10 + index * 12; - view.setUint16(offset, tag!, true); - view.setUint16(offset + 2, 4, true); - view.setUint32(offset + 4, 1, true); - view.setUint32(offset + 8, value!, true); - }); - view.setUint8(135, 255); - const src = URL.createObjectURL(new Blob([bytes])); - try { - const blob = await decodeImagePreview(src, false, new AbortController().signal); - const bitmap = await createImageBitmap(blob); - const canvas = new OffscreenCanvas(2, 1); - const context = canvas.getContext("2d")!; - context.drawImage(bitmap, 0, 0); - expect([...context.getImageData(0, 0, 2, 1).data]).toEqual([ - 255, 255, 255, 255, 0, 0, 0, 255, - ]); - bitmap.close(); - } finally { - URL.revokeObjectURL(src); + it("keeps WhiteIsZero TIFF brightness and alpha with SubIFDs tags and rejects oversized metadata before decoding", async () => { + let bytes = new ArrayBuffer(0); + for (const { pixels, expected } of [ + { pixels: [0, 255], expected: [255, 255, 255, 255, 0, 0, 0, 255] }, + { pixels: [0, 255, 255, 0], expected: [255, 255, 255, 255, 0, 0, 0, 0] }, + ]) { + const samples = pixels.length / 2; + const start = samples === 2 ? 158 : 146; + const tags = [ + [256, 2], + [257, 1], + [258, 8], + [259, 1], + [262, 0], + [273, start], + [277, samples], + [278, 1], + [279, pixels.length], + [284, 1], + [330, 0, 13], + ...(samples === 2 ? [[338, 2]] : []), + ]; + bytes = new ArrayBuffer(start + pixels.length); + const view = new DataView(bytes); + view.setUint16(0, 0x4949); + view.setUint16(2, 42, true); + view.setUint32(4, 8, true); + view.setUint16(8, tags.length, true); + tags.forEach(([tag, value, type = 4], index) => { + const offset = 10 + index * 12; + view.setUint16(offset, tag!, true); + view.setUint16(offset + 2, type, true); + view.setUint32(offset + 4, 1, true); + view.setUint32(offset + 8, value!, true); + }); + new Uint8Array(bytes, start).set(pixels); + const src = URL.createObjectURL(new Blob([bytes])); + try { + const blob = await decodeImagePreview(src, false, new AbortController().signal); + const bitmap = await createImageBitmap(blob); + const canvas = new OffscreenCanvas(2, 1); + const context = canvas.getContext("2d")!; + context.drawImage(bitmap, 0, 0); + expect([...context.getImageData(0, 0, 2, 1).data]).toEqual(expected); + bitmap.close(); + } finally { + URL.revokeObjectURL(src); + } } - view.setUint32(14, 1_000_000, true); + new DataView(bytes).setUint32(14, 1_000_000, true); const invalid = URL.createObjectURL(new Blob([bytes])); try { await expect( @@ -582,8 +590,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} @@ -1951,7 +1965,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; @@ -1965,12 +1981,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/AttachmentFilePreview.office.browser.test.tsx b/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx index 516ea535fd9b6..6826d3369c76a 100644 --- a/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx +++ b/apps/web/src/components/files/AttachmentFilePreview.office.browser.test.tsx @@ -286,6 +286,8 @@ it("preserves merged text across tile clears", async () => { context, { viewport: { x: 0, y: 0, width: 400, height: 80 }, + behind: { x: 0, y: 0 }, + panes: { width: 0, height: 0 }, list: { width: 400, height: 80, commands: [] }, tiles: [ { 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 cd44d99220939..8f0bf626ba034 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -649,6 +649,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 714e45bac76fb..07e05010baab3 100644 --- a/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx +++ b/apps/web/src/components/files/FilePreviewPanel.browser.test.tsx @@ -562,17 +562,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(); }); @@ -580,6 +591,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 2c27cfb8d80d1..2ef4d67095e55 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, @@ -122,6 +123,8 @@ import { FileSurfaceLoading, } from "./fileSurfaceChrome"; import SourceFilePreview from "./ReadOnlySourcePreview"; +import LargeFilePreview from "./LargeFilePreview"; +import { FULL_TEXT_MAX_BYTES } from "./largeTextProtocol"; import { resolveCenteredFileLineScrollTop } from "./fileLineReveal"; import { DiffCommentAnnotation } from "../diffs/DiffCommentAnnotation"; import { projectFileCacheKey } from "./fileContentRevision"; @@ -841,43 +844,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; @@ -1218,30 +1184,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); - } - } - /> - + ); } @@ -1394,7 +1357,8 @@ export default function FilePreviewPanel({ const revealHandled = revealLine === null || (handledReveal?.path === relativePath && handledReveal.requestId === revealRequestId); - 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; @@ -1408,7 +1372,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 && @@ -1439,6 +1406,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) => @@ -1680,6 +1656,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.}}", @@ -1789,21 +1775,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({ @@ -2013,78 +2083,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 c2104ad2ddec6..e4858515024db 100644 --- a/apps/web/src/components/files/NotebookPreview.tsx +++ b/apps/web/src/components/files/NotebookPreview.tsx @@ -47,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 ( <> @@ -121,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/ProjectFilePicker.logic.test.ts b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts index f112ba97ab5d6..47efe8f58c44f 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.test.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.test.ts @@ -37,4 +37,18 @@ describe("getProjectFilePickerMatches", () => { [0, 1, 2], ); }); + + it("maps highlights back to original characters when lowercasing expands them", () => { + const entries = [{ kind: "file", path: "icons/İ-logo.svg" }] as const; + const indices = (query: string) => { + const match = getProjectFilePickerMatches(entries, query)[0]; + return [match?.nameMatchIndices, match?.pathMatchIndices]; + }; + + assert.deepEqual(indices("logo"), [ + [2, 3, 4, 5], + [8, 9, 10, 11], + ]); + assert.deepEqual(indices("İ"), [[0], [0, 6]]); + }); }); diff --git a/apps/web/src/components/files/ProjectFilePicker.logic.ts b/apps/web/src/components/files/ProjectFilePicker.logic.ts index 87fa4212eb384..a19e8b4a1e8d5 100644 --- a/apps/web/src/components/files/ProjectFilePicker.logic.ts +++ b/apps/web/src/components/files/ProjectFilePicker.logic.ts @@ -19,12 +19,23 @@ function findMatchIndices(value: string, query: string): number[] | null { if (!query) return []; const normalizedValue = value.toLowerCase(); + // Lowercasing lengthens İ (to i̇) and shortens nothing, so only a longer result needs mapping back. + const sourceSpans: Array = []; + if (normalizedValue.length !== value.length) { + let sourceOffset = 0; + for (const char of value) { + const span = [sourceOffset, sourceOffset + char.length] as const; + for (let n = char.toLowerCase().length; n > 0; n -= 1) sourceSpans.push(span); + sourceOffset = span[1]; + } + } const indices: number[] = []; let queryIndex = 0; for (let valueIndex = 0; valueIndex < normalizedValue.length; valueIndex += 1) { if (normalizedValue[valueIndex] !== query[queryIndex]) continue; - indices.push(valueIndex); + const [start, end] = sourceSpans[valueIndex] ?? [valueIndex, valueIndex + 1]; + for (let i = Math.max(start, (indices.at(-1) ?? -1) + 1); i < end; i += 1) indices.push(i); queryIndex += 1; if (queryIndex === query.length) return indices; } 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/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/imageDecode.worker.ts b/apps/web/src/components/files/imageDecode.worker.ts index f19174b62af35..9cd3140308612 100644 --- a/apps/web/src/components/files/imageDecode.worker.ts +++ b/apps/web/src/components/files/imageDecode.worker.ts @@ -25,7 +25,7 @@ function validateTiffMetadata(bytes: ArrayBuffer) { const tag = view.getUint16(entry, littleEndian); const type = view.getUint16(entry + 2, littleEndian); const values = view.getUint32(entry + 4, littleEndian); - const width = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8][type]; + const width = [0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 4][type]; if (!width) throw new PreviewError({ code: "tiff-metadata-type" }); const length = values * width; const start = length > 4 ? view.getUint32(entry + 8, littleEndian) : entry + 8; @@ -190,6 +190,9 @@ async function decode(bytes: ArrayBuffer, heif: boolean) { const rgba = new Uint8ClampedArray(image.width * image.height * 4); const scale = image.bitsPerSample === 16 ? 257 : 1; const palette = image.palette; + const alpha = image.alpha; + // The tiff decoder inverts every WhiteIsZero sample, alpha included. + const invertAlpha = alpha && image.type === 0; for (let pixel = 0; pixel < image.width * image.height; pixel++) { const index = pixel * image.components; if (palette) { @@ -203,7 +206,8 @@ async function decode(bytes: ArrayBuffer, heif: boolean) { const gray = image.data[index]! / scale; rgba.fill(gray, pixel * 4, pixel * 4 + 3); } - rgba[pixel * 4 + 3] = image.alpha ? image.data[index + image.components - 1]! / scale : 255; + const value = alpha ? image.data[index + image.components - 1]! / scale : 255; + rgba[pixel * 4 + 3] = invertAlpha ? 255 - value : value; } const canvas = new OffscreenCanvas(image.width, image.height); const context = canvas.getContext("2d"); 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 5ff8580ee0a36..28f45c906b5ba 100644 --- a/apps/web/src/components/files/office/Spreadsheet.tsx +++ b/apps/web/src/components/files/office/Spreadsheet.tsx @@ -55,8 +55,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(() => { @@ -75,7 +74,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}}", { @@ -92,22 +91,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} @@ -126,9 +129,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 @@ -143,7 +146,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/office/sheet-frame.ts b/apps/web/src/components/files/office/sheet-frame.ts index 3b7868bf2d3fe..80723af7256cd 100644 --- a/apps/web/src/components/files/office/sheet-frame.ts +++ b/apps/web/src/components/files/office/sheet-frame.ts @@ -1,10 +1,5 @@ // Adapted from opencode (MIT). Copyright (c) 2025 opencode. See LICENSE.opencode. -import { - paintDisplayList, - type DisplayList, - type GridMeta, - type WorkbookHandle, -} from "@betteroffice/xlsx"; +import { paintDisplayList, type DisplayList, type WorkbookHandle } from "@betteroffice/xlsx"; import { attempt } from "./sheet-cells"; import { frozenSize } from "./sheet-paint"; import type { SheetViewport } from "./sheet-protocol"; @@ -21,6 +16,12 @@ const maxSplit = 8; */ const seamOverlap = 8; +/** + * How far before a frame its cells are drawn from, in CSS pixels. The engine draws only the cells from a viewport's + * first track on, so the text of a cell before it, overflowing or merged into the frame, would vanish with that cell. + */ +const reach = { x: 1024, y: 512 }; + /** Part of a frame: its display list, where its origin sits in the frame, and where it starts to show. */ type Tile = { readonly list: DisplayList; @@ -32,12 +33,14 @@ type Tile = { /** * A frame of cells: the tiles that draw it, one display list for its grid and links, without draw commands, and the - * viewport it shows. + * viewport it shows. The tiles' cells past the frozen panes start `behind` the viewport's. */ export type Frame = { readonly list: DisplayList; readonly tiles: readonly Tile[]; readonly viewport: SheetViewport; + readonly behind: { readonly x: number; readonly y: number }; + readonly panes: { readonly width: number; readonly height: number }; }; /** @@ -50,22 +53,20 @@ export function drawFrame( frozen: { readonly rows: number; readonly cols: number }, wider?: SheetViewport, ): Frame | undefined { - const around = wider && untruncated(workbook, wider); - - if (wider && around) - return { - list: around, - tiles: [{ list: around, x: 0, y: 0, clipX: 0, clipY: 0 }], - viewport: wider, - }; - - const whole = untruncated(workbook, viewport); - - if (whole) - return { list: whole, tiles: [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }], viewport }; + return ( + (wider && reaching(workbook, wider, frozen, false)) || + reaching(workbook, viewport, frozen, true) + ); +} - // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. One row and one column of - // the frame give its tracks, and so where its frozen panes end. +/** A frame of `viewport` drawn from up to `reach` before it, split into tiles when `split` and the engine needs it. */ +function reaching( + workbook: WorkbookHandle, + viewport: SheetViewport, + frozen: { readonly rows: number; readonly cols: number }, + split: boolean, +): Frame | undefined { + // One row and one column of the viewport give its tracks, and so where its frozen panes end. const columns = untruncated(workbook, { ...viewport, height: 1 })?.grid; const rows = untruncated(workbook, { ...viewport, width: 1 })?.grid; @@ -79,8 +80,33 @@ export function drawFrame( ...(columns.colIndices ? { colIndices: columns.colIndices } : {}), colOffsets: columns.colOffsets, }; + const panes = frozenSize(grid, frozen); + const behind = { x: Math.min(reach.x, viewport.x), y: Math.min(reach.y, viewport.y) }; + const area = { + x: viewport.x - behind.x, + y: viewport.y - behind.y, + width: viewport.width + behind.x, + height: viewport.height + behind.y, + }; + const whole = untruncated(workbook, area); + // The engine refuses a viewport with too many cells, as a wide pane of narrow columns has. + const tiles = whole + ? [{ list: whole, x: 0, y: 0, clipX: 0, clipY: 0 }] + : split + ? tiled(workbook, area, panes, 2) + : undefined; - return tiled(workbook, viewport, frozenSize(grid, frozen), grid, 2); + if (!tiles) return undefined; + + const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []); + + return { + list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks }, + tiles, + viewport, + behind, + panes, + }; } /** The engine's screen gridlines: one-pixel solid lines in its gridline grey, unlike any border it draws. */ @@ -133,7 +159,7 @@ export function chartFonts( /** * Draws a frame's tiles with the cells' top-left corner at `origin`, in device pixels, each tile from its seam on, so a - * tile covers the panes it repeats. + * tile covers the panes it repeats. The cells past the frozen panes move back by `behind`; the panes stay put. */ export function paintFrame( context: OffscreenCanvasRenderingContext2D, @@ -148,58 +174,92 @@ export function paintFrame( const tiled = frame.tiles.length > 1; const text = tiled ? new OffscreenCanvas(context.canvas.width, context.canvas.height) : undefined; const textContext = text?.getContext("2d"); - - frame.tiles.forEach((tile) => { - const at = { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio }; - const list = tiled - ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") } - : tile.list; - - if (tile.clipX === 0 && tile.clipY === 0) return paintDisplayList(painter, list, ratio, at); + const columns = bands(frame.panes.width, frame.behind.x); + const rows = bands(frame.panes.height, frame.behind.y); + const parts = frame.tiles.flatMap((tile) => + rows.flatMap((row) => + columns.flatMap((column) => { + const left = Math.max(column.start, tile.clipX - column.shift); + const top = Math.max(row.start, tile.clipY - row.shift); + + if (left >= column.end || top >= row.end) return []; + + const clip = { + left: Math.round(origin.x + left * ratio), + top: Math.round(origin.y + top * ratio), + right: Math.round(origin.x + column.end * ratio), + bottom: Math.round(origin.y + row.end * ratio), + }; + + return [ + { + tile, + at: { + x: origin.x + (tile.x - column.shift) * ratio, + y: origin.y + (tile.y - row.shift) * ratio, + }, + clip: + left === 0 && top === 0 && column.end === Infinity && row.end === Infinity + ? undefined + : clip, + }, + ]; + }), + ), + ); + const clipped = (clip: (typeof parts)[number]["clip"], paint: () => void) => { + if (!clip) return paint(); context.save(); context.setTransform(1, 0, 0, 1, 0, 0); context.beginPath(); context.rect( - Math.round(origin.x + tile.clipX * ratio), - Math.round(origin.y + tile.clipY * ratio), - context.canvas.width, - context.canvas.height, + clip.left, + clip.top, + Math.min(clip.right, context.canvas.width) - clip.left, + Math.min(clip.bottom, context.canvas.height) - clip.top, ); context.clip(); - paintDisplayList(painter, list, ratio, at); + paint(); context.restore(); + }; + + parts.forEach(({ tile, at, clip }) => { + const list = tiled + ? { ...tile.list, commands: tile.list.commands.filter((command) => command.op !== "text") } + : tile.list; + + clipped(clip, () => paintDisplayList(painter, list, ratio, at)); }); // Text clips can span a merged range beyond its tile. Composite it after all tile clears and backgrounds. if (text && textContext) - frame.tiles.forEach((tile) => { + parts.forEach(({ tile, at, clip }) => { textContext.reset(); paintDisplayList( textContext as unknown as CanvasRenderingContext2D, { ...tile.list, - width: frame.viewport.width - tile.x, - height: frame.viewport.height - tile.y, + width: frame.viewport.width + frame.behind.x - tile.x, + height: frame.viewport.height + frame.behind.y - tile.y, commands: tile.list.commands.filter((command) => command.op === "text"), }, ratio, - { x: origin.x + tile.x * ratio, y: origin.y + tile.y * ratio }, - ); - context.save(); - context.setTransform(1, 0, 0, 1, 0, 0); - context.beginPath(); - context.rect( - Math.round(origin.x + tile.clipX * ratio), - Math.round(origin.y + tile.clipY * ratio), - context.canvas.width, - context.canvas.height, + at, ); - context.clip(); - context.drawImage(text, 0, 0); - context.restore(); + clipped(clip, () => context.drawImage(text, 0, 0)); }); } +/** A side's frozen pane, drawn where it is, and the cells past it, drawn `behind` further on. */ +function bands(panes: number, behind: number) { + return panes > 0 && behind > 0 + ? [ + { start: 0, end: panes, shift: 0 }, + { start: panes, end: Infinity, shift: behind }, + ] + : [{ start: 0, end: Infinity, shift: behind }]; +} + /** * A frame split into `split` tiles a side, each under the engine's cap. A tile past the first along an axis asks for * the frozen panes too, as every viewport has them, so the cells past them start just before its seam. @@ -208,9 +268,8 @@ function tiled( workbook: WorkbookHandle, viewport: SheetViewport, panes: { readonly width: number; readonly height: number }, - grid: GridMeta, split: number, -): Frame | undefined { +): Tile[] | undefined { const columns = segments(viewport.width, panes.width, split); const rows = segments(viewport.height, panes.height, split); const tiles: Tile[] = []; @@ -236,19 +295,11 @@ function tiled( }), ); - if (complete) { - const hyperlinks = tiles.flatMap((tile) => tile.list.hyperlinks ?? []); - - return { - list: { width: viewport.width, height: viewport.height, commands: [], grid, hyperlinks }, - tiles, - viewport, - }; - } + if (complete) return tiles; if (split >= maxSplit) return undefined; - return tiled(workbook, viewport, panes, grid, split + 1); + return tiled(workbook, viewport, panes, split + 1); } /** A viewport's display list, or undefined where the engine refuses it or cuts it short at its cell limit. */ diff --git a/apps/web/src/components/files/office/sheet-resize.browser.test.ts b/apps/web/src/components/files/office/sheet-resize.browser.test.ts index 6029e888e1c20..fc2c6845d7530 100644 --- a/apps/web/src/components/files/office/sheet-resize.browser.test.ts +++ b/apps/web/src/components/files/office/sheet-resize.browser.test.ts @@ -145,6 +145,69 @@ it.each([false, true])( }, ); +it.each([false, true])( + "draws text from cells scrolled out before the frame, frozen: %s", + async (frozen) => { + const archive = new JSZip(); + archive.file( + "xl/workbook.xml", + '', + ); + archive.file( + "xl/_rels/workbook.xml.rels", + '', + ); + archive.file( + "xl/styles.xml", + '', + ); + archive.file( + "xl/worksheets/sheet1.xml", + `${frozen ? '' : ""}${"M".repeat(60)}MMMM`, + ); + const bytes = await archive.generateAsync({ type: "arraybuffer" }); + const client = createWorkerClient( + new Worker(new URL("./spreadsheet.worker.ts", import.meta.url), { type: "module" }), + ); + const inked = async ( + at: { x: number; y: number }, + area: { x: number; y: number; width: number; height: number }, + ) => { + const frame = await client.call("frame", { + sheet: 0, + ...at, + width: 400, + height: 300, + ratio: 1, + offset: { x: 0, y: 0 }, + wider: undefined, + }); + const canvas = new OffscreenCanvas(frame!.bitmap.width, frame!.bitmap.height); + const context = canvas.getContext("2d")!; + context.drawImage(frame!.bitmap, 0, 0); + frame!.bitmap.close(); + const pixels = context.getImageData(area.x, area.y, area.width, area.height).data; + return pixels.some( + (value, index) => index % 4 === 0 && value < 128 && pixels[index + 3]! > 0, + ); + }; + try { + await client.call("open", { + bytes, + view: { hiddenGridlines: [], themeFonts: { major: "Calibri Light", minor: "Calibri" } }, + }); + // B2's text overflows to the right well past B, and the merge centres C4's text far below row 4. + const panes = frozen ? { x: 64, y: 20 } : { x: 0, y: 0 }; + expect( + await inked({ x: 160, y: 0 }, { x: panes.x + 40, y: 20, width: 200, height: 20 }), + ).toBe(true); + expect(await inked({ x: 0, y: 200 }, { x: 128, y: 200, width: 64, height: 80 })).toBe(true); + } finally { + client.close(); + } + }, +); + it("requests current dimensions after resizing and scrolling away and back before a frame arrives", async () => { const archive = new JSZip(); archive.file( 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, + }) + } /> ) : ( { if (!filtersOpen) return NO_LIST_TARGETS; return environmentQueries.map(({ environmentId, projectIds }) => ({ 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/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 99ff61182d626..9d03b7ab72e48 100644 --- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts +++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts @@ -88,7 +88,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"); @@ -96,7 +96,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 { @@ -553,8 +557,9 @@ function titleCaseCommandSegment(segment: string): string { function recordedLayoutShortcutKey( event: Pick, + platform: string, ): string { - const physicalKey = shortcutKeyFromEvent(event); + const physicalKey = shortcutKeyFromEvent(event, platform); const layoutKey = event.key.toLowerCase(); if (event.altKey || layoutKey.length !== 1) return physicalKey; // Normalize only US shifted glyphs at their US position. Other layouts can @@ -601,7 +606,9 @@ export function keybindingFromKeyboardEvent( }, ): string | null { const keyToken = normalizeShortcutKeyToken( - options?.layoutCharacter ? recordedLayoutShortcutKey(event) : shortcutKeyFromEvent(event), + options?.layoutCharacter + ? recordedLayoutShortcutKey(event, platform) + : shortcutKeyFromEvent(event, platform), ); if (!keyToken) return null; diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsx index 6e78c7c1935a6..0b6cc7ed41f81 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, @@ -100,35 +102,34 @@ import { keybindingSearchAnchorId, useSearchableSetting } from "./settingsSearch import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { useAtomCommand } from "../../state/use-atom-command"; -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} ); } @@ -915,7 +916,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/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 4bc2c2a6317e5..3249b67624234 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -168,6 +168,7 @@ describe("searchSettings", () => { "auto-settle-merged-threads", "days-before-auto-settle", "linked-environments", + "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 5fbe163fbf6a9..8e7e1ea194be6 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -72,6 +72,7 @@ export interface SettingsSearchItem { readonly managedTunnelOnly?: boolean; readonly peerLinksOnly?: boolean; readonly fastWorktreeCheckoutOnly?: boolean; + readonly agentFeedbackOnly?: boolean; readonly textGeneratorsOnly?: boolean; readonly secondary?: boolean; readonly requiresThreadAutoSettlement?: boolean; @@ -88,6 +89,7 @@ export interface SettingsSearchAvailability { readonly managedTunnelActive?: boolean; readonly hasPeerLinkHost?: boolean; readonly hasFastWorktreeCheckoutEnvironment?: boolean; + readonly hasAgentFeedbackEnvironment?: boolean; /** An environment without a provider allow-list, which hides text generators. */ readonly hasTextGeneratorsEnvironment?: boolean; readonly hasPrimaryEnvironment?: boolean; @@ -567,6 +569,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"), @@ -1015,6 +1024,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"), @@ -1581,6 +1600,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; } @@ -1673,6 +1693,7 @@ export function filterAvailableSettingsSearchItems( (!item.peerLinksOnly || availability.hasPeerLinkHost === true) && (!item.fastWorktreeCheckoutOnly || availability.hasFastWorktreeCheckoutEnvironment === true) && + (!item.agentFeedbackOnly || availability.hasAgentFeedbackEnvironment === true) && (!item.textGeneratorsOnly || availability.hasTextGeneratorsEnvironment === true) && (!item.secretProvidersOnly || availability.hasSecretProvidersEnvironment === true), ); diff --git a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts index beb5e3c85c52c..279dbd39d51e3 100644 --- a/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts +++ b/apps/web/src/components/settings/useAvailableSettingsSearchItems.ts @@ -45,6 +45,12 @@ export function useAvailableSettingsSearchItems() { environment.connection.phase === "connected" && environment.serverConfig?.environment.capabilities.fastWorktreeCheckout === true, ) === true; + const hasAgentFeedbackEnvironment = + environments.some( + (environment) => + environment.connection.phase === "connected" && + environment.serverConfig?.environment.capabilities.agentFeedback === true, + ) === true; const hasTextGeneratorsEnvironment = environments.some( (environment) => @@ -83,6 +89,7 @@ export function useAvailableSettingsSearchItems() { managedTunnelActive, hasPeerLinkHost, hasFastWorktreeCheckoutEnvironment, + 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} - {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 index 0858fa656e6bb..cca4d8a43fd61 100644 --- a/apps/web/src/components/ui/shared-tooltip.tsx +++ b/apps/web/src/components/ui/shared-tooltip.tsx @@ -11,6 +11,7 @@ import { type ReactElement, type ReactNode, } from "react"; +import { flushSync } from "react-dom"; import { Tooltip, TooltipPopup, TooltipTrigger, useTooltipScrollTracker } from "./tooltip"; @@ -79,6 +80,8 @@ export function SharedTooltipProvider({ children }: { children: ReactNode }) { 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) { diff --git a/apps/web/src/components/ui/tooltip.browser.test.tsx b/apps/web/src/components/ui/tooltip.browser.test.tsx index bcb62ee2fdaf0..344ddcea7f0f1 100644 --- a/apps/web/src/components/ui/tooltip.browser.test.tsx +++ b/apps/web/src/components/ui/tooltip.browser.test.tsx @@ -114,3 +114,25 @@ it("refreshes a pending shared tooltip if its label changes during the open dela await expect.element(page.getByText("Copy code")).toBeVisible(); expect(page.getByText("Copied").query()).toBeNull(); }); + +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/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..d77b54d8dcc11 --- /dev/null +++ b/apps/web/src/components/workflows/WorkflowRunFeed.tsx @@ -0,0 +1,1924 @@ +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/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 063625d0acd0b..730f92862e918 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.", @@ -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", @@ -765,8 +813,13 @@ "166661f94b300f5b": "Fertig", "d4d89c139de812a8": "Fehlgeschlagen", "c1e03a860c856245": "Gestoppt", - "f1d27d127ab27ac6": "Wird gestartet", + "7e5abc299ead1d09": "{provider}-Plugins werden geladen", + "21872f69ccbc711d": "{provider}-MCP-Server werden gestartet", + "fedaa29ff8815a77": "{provider}-Hooks werden geladen", + "57025ae4de5beb57": "{provider}-Regeln und -Skills werden geladen", + "4729a188600f1501": "Verbindung zu {provider} wird hergestellt", "8c8977097681630f": "{provider} wird gestartet", + "f1d27d127ab27ac6": "Wird gestartet", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Wartet", "54002bf654ddbab1": "Abgeschlossen", @@ -1720,6 +1773,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.", @@ -1805,6 +1860,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", @@ -2497,8 +2553,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}", @@ -3580,6 +3635,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.", @@ -3600,7 +3663,6 @@ "abd89e9eefedf11b": "Fertig", "18d166056c1ab6ff": "Freigabe beenden", "7a2d510eac9e4587": "Gastlink abgelaufen", - "653405e4ed498d9f": "Senden", "21888e302219891d": "Vergrößerte Vorschau von {title}", "419719298a7acaea": "Verkleinern", "ed8d5db95359cff4": "Zoom zurücksetzen", @@ -5600,7 +5662,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.", @@ -5610,6 +5671,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.", @@ -5617,8 +5679,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.", @@ -5805,7 +5865,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", @@ -8830,6 +8889,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)", @@ -8838,11 +8903,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", " ", @@ -8926,7 +8996,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.", @@ -9155,7 +9227,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", @@ -10130,7 +10201,6 @@ "16bdc70b858c223f": "Proaktive Panels auf Standard zurücksetzen", "c5424f09d77138ff": "Wann ein inaktiver Claude-Thread über 200.000 Tokens komprimiert wird: nach deiner Rückkehr, kurz bevor sein Prompt-Cache abläuft, oder nie. Jeder Claude-Anbieter kann das überschreiben.", "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", @@ -11032,7 +11102,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.", @@ -11729,7 +11798,6 @@ "4c70e3e7b3e6c493": "Geheimnisse", "79b768229c9ef672": "Wartung", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Info", "af4b7734da1d5ce7": "Spracheingabe", "4ec62c39ca3192bf": "Versionskontrolle & Issues", "f2bf529f85e05494": "Freigabe & Zugriff", @@ -11784,6 +11852,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", @@ -11855,6 +11924,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", @@ -12340,7 +12410,6 @@ "0bd41ff995d36a66": "Cache-Lesen", "3f0dfe0cb15a3272": "Cache-Schreiben", "1c9d860be42b1c02": "Ausgabe", - "78344b60f407928e": "Sonstiges", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Schnell", "66796576034c18ea": "Ultraschnell", @@ -12356,6 +12425,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.", @@ -12475,6 +12800,10 @@ "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", + "99d51127f573296b": "Weiteres Konto", + "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", + "99963c0142e17f00": "Für das neue {tracker}-Konto.", + "6d8e4ebc889bace9": "Konto hinzufügen", "2c4153283b647365": "Claude {account}: {session} des 5-Stunden-Fensters und {weekly} der Woche verbraucht", "0ebc6d14caaaca3b": "Last {one} · {five} · {fifteen} auf {cores} Kernen", "578c5947c810f7b9": "{percent} % ausgelastet", @@ -12495,7 +12824,6 @@ "23c58afe110c0352": "Agent-Limit", "a27d19aa7504f69a": "nur Speicher", "710aada747770581": "{working} von {limit} arbeiten", - "30a5be40eb956663": "arbeitet", "ac2c1a39608fc635": "offen", "8a72bdb53d14db64": "{count, plural, one {# weiterer} other {# weitere}}", "5f2d81b15ca48b42": "Keine Agenten offen.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index c01d1ad85055b..3d63391f73a2e 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.", @@ -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", @@ -765,8 +813,13 @@ "166661f94b300f5b": "Done", "d4d89c139de812a8": "Failed", "c1e03a860c856245": "Stopped", - "f1d27d127ab27ac6": "Starting", + "7e5abc299ead1d09": "Loading {provider} plugins", + "21872f69ccbc711d": "Starting {provider} MCP servers", + "fedaa29ff8815a77": "Loading {provider} hooks", + "57025ae4de5beb57": "Loading {provider} rules and skills", + "4729a188600f1501": "Connecting to {provider}", "8c8977097681630f": "Starting {provider}", + "f1d27d127ab27ac6": "Starting", "86d60d42f6cb4a40": "Idle", "0e8eab930d79d8b4": "Waiting", "54002bf654ddbab1": "Completed", @@ -1721,6 +1774,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.", @@ -1806,6 +1861,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", @@ -2497,8 +2553,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}", @@ -3579,6 +3634,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.", @@ -3599,7 +3662,6 @@ "abd89e9eefedf11b": "Done", "18d166056c1ab6ff": "Stop sharing", "7a2d510eac9e4587": "Guest link expired", - "653405e4ed498d9f": "Send", "21888e302219891d": "Expanded {title} preview", "419719298a7acaea": "Zoom out", "ed8d5db95359cff4": "Reset zoom", @@ -5601,7 +5663,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.", @@ -5611,6 +5672,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.", @@ -5618,8 +5680,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.", @@ -5806,7 +5866,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", @@ -8838,6 +8897,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)", @@ -8846,11 +8911,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", " ", @@ -8934,7 +9004,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.", @@ -9163,7 +9235,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", @@ -10139,7 +10210,6 @@ "16bdc70b858c223f": "Reset proactive panels to default", "c5424f09d77138ff": "When to compact an idle Claude thread over 200,000 tokens: after you return, just before its prompt cache expires, or never. Each Claude provider can override this.", "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", @@ -11041,7 +11111,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.", @@ -11737,7 +11806,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "About", "af4b7734da1d5ce7": "Voice", "4ec62c39ca3192bf": "Source control & issues", "f2bf529f85e05494": "Sharing & access", @@ -11792,6 +11860,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", @@ -11863,6 +11932,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", @@ -12348,7 +12418,6 @@ "0bd41ff995d36a66": "Cache read", "3f0dfe0cb15a3272": "Cache write", "1c9d860be42b1c02": "Output", - "78344b60f407928e": "Other", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Fast", "66796576034c18ea": "Ultrafast", @@ -12364,6 +12433,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.", @@ -12484,6 +12809,10 @@ "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", "9e91e9a77b664e4e": "Could not start a review guide", + "99d51127f573296b": "Another account", + "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", + "99963c0142e17f00": "For the new {tracker} account.", + "6d8e4ebc889bace9": "Add account", "2c4153283b647365": "Claude {account}: {session} of the 5-hour window and {weekly} of the week used", "0ebc6d14caaaca3b": "load {one} · {five} · {fifteen} on {cores} cores", "578c5947c810f7b9": "{percent}% busy", @@ -12504,7 +12833,6 @@ "23c58afe110c0352": "Agent limit", "a27d19aa7504f69a": "memory only", "710aada747770581": "{working} of {limit} working", - "30a5be40eb956663": "working", "ac2c1a39608fc635": "open", "8a72bdb53d14db64": "{count, plural, one {# more} other {# more}}", "5f2d81b15ca48b42": "No agents are open.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 34dfb3afd30fa..a607db3d9daf4 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.", @@ -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", @@ -765,8 +813,13 @@ "166661f94b300f5b": "Terminado", "d4d89c139de812a8": "Falló", "c1e03a860c856245": "Detenido", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Cargando plugins de {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP de {provider}", + "fedaa29ff8815a77": "Cargando hooks de {provider}", + "57025ae4de5beb57": "Cargando reglas y skills de {provider}", + "4729a188600f1501": "Conectando con {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Inactivo", "0e8eab930d79d8b4": "Esperando", "54002bf654ddbab1": "Completado", @@ -1721,6 +1774,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.", @@ -1806,6 +1861,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", @@ -2497,8 +2553,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}", @@ -3579,6 +3634,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.", @@ -3599,7 +3662,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", @@ -5599,7 +5661,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.", @@ -5609,6 +5670,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.", @@ -5616,8 +5678,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.", @@ -5804,7 +5864,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ó", @@ -8828,6 +8887,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)", @@ -8836,11 +8901,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", " ", @@ -8924,7 +8994,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.", @@ -9153,7 +9225,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", @@ -10127,7 +10198,6 @@ "16bdc70b858c223f": "Restablecer los paneles proactivos al valor predeterminado", "c5424f09d77138ff": "Cuándo compactar un hilo inactivo de Claude con más de 200 000 tokens: al volver, justo antes de que caduque su caché de prompts o nunca. Cada proveedor de Claude puede anularlo.", "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", @@ -11026,7 +11096,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.", @@ -11722,7 +11791,6 @@ "4c70e3e7b3e6c493": "Secretos", "79b768229c9ef672": "Mantenimiento", "54b188d65247e42f": "Experimentos", - "f41ea186c275b56e": "Acerca de", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versiones e issues", "f2bf529f85e05494": "Compartir y acceso", @@ -11777,6 +11845,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", @@ -11848,6 +11917,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", @@ -12333,7 +12403,6 @@ "0bd41ff995d36a66": "Lectura de caché", "3f0dfe0cb15a3272": "Escritura de caché", "1c9d860be42b1c02": "Salida", - "78344b60f407928e": "Otros", "684e516076de81fe": "Estándar", "3bbcc1b826fef537": "Rápida", "66796576034c18ea": "Ultrarrápida", @@ -12349,6 +12418,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.", @@ -12470,6 +12795,10 @@ "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", + "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", "2c4153283b647365": "Claude {account}: {session} de la ventana de 5 horas y {weekly} de la semana usados", "0ebc6d14caaaca3b": "carga {one} · {five} · {fifteen} en {cores} núcleos", "578c5947c810f7b9": "{percent} % ocupado", @@ -12490,7 +12819,6 @@ "23c58afe110c0352": "Límite de agentes", "a27d19aa7504f69a": "solo memoria", "710aada747770581": "{working} de {limit} trabajando", - "30a5be40eb956663": "trabajando", "ac2c1a39608fc635": "abierto", "8a72bdb53d14db64": "{count, plural, one {# más} other {# más}}", "5f2d81b15ca48b42": "No hay agentes abiertos.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index d5d1029601092..50aac967f9838 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.", @@ -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", @@ -765,8 +813,13 @@ "166661f94b300f5b": "Terminé", "d4d89c139de812a8": "Échec", "c1e03a860c856245": "Arrêté", - "f1d27d127ab27ac6": "Démarrage", + "7e5abc299ead1d09": "Chargement des plugins de {provider}", + "21872f69ccbc711d": "Démarrage des serveurs MCP de {provider}", + "fedaa29ff8815a77": "Chargement des hooks de {provider}", + "57025ae4de5beb57": "Chargement des règles et des skills de {provider}", + "4729a188600f1501": "Connexion à {provider}", "8c8977097681630f": "Démarrage de {provider}", + "f1d27d127ab27ac6": "Démarrage", "86d60d42f6cb4a40": "Inactif", "0e8eab930d79d8b4": "En attente", "54002bf654ddbab1": "Terminé", @@ -1721,6 +1774,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.", @@ -1806,6 +1861,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", @@ -2497,8 +2553,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}", @@ -3579,6 +3634,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é.", @@ -3599,7 +3662,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", @@ -5600,7 +5662,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.", @@ -5610,6 +5671,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é.", @@ -5617,8 +5679,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é.", @@ -5805,7 +5865,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é", @@ -8829,6 +8888,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)", @@ -8837,11 +8902,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", " ", @@ -8926,7 +8996,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.", @@ -9155,7 +9227,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", @@ -10129,7 +10200,6 @@ "16bdc70b858c223f": "Réinitialiser les panneaux proactifs à la valeur par défaut", "c5424f09d77138ff": "Quand compacter un fil Claude inactif de plus de 200 000 tokens : à votre retour, juste avant l’expiration de son cache de prompt, ou jamais. Chaque fournisseur Claude peut remplacer ce paramètre.", "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", @@ -11031,7 +11101,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.", @@ -11727,7 +11796,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "À propos", "af4b7734da1d5ce7": "Voix", "4ec62c39ca3192bf": "Versions et tickets", "f2bf529f85e05494": "Partage et accès", @@ -11782,6 +11850,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", @@ -11853,6 +11922,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", @@ -12338,7 +12408,6 @@ "0bd41ff995d36a66": "Lecture du cache", "3f0dfe0cb15a3272": "Écriture du cache", "1c9d860be42b1c02": "Sortie", - "78344b60f407928e": "Autre", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Rapide", "66796576034c18ea": "Ultrarapide", @@ -12354,6 +12423,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.", @@ -12475,6 +12800,10 @@ "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", + "99d51127f573296b": "Autre compte", + "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", + "99963c0142e17f00": "Pour le nouveau compte {tracker}.", + "6d8e4ebc889bace9": "Ajouter un compte", "2c4153283b647365": "Claude {account} : {session} de la fenêtre de 5 heures et {weekly} de la semaine utilisés", "0ebc6d14caaaca3b": "charge {one} · {five} · {fifteen} sur {cores} cœurs", "578c5947c810f7b9": "{percent} % occupé", @@ -12495,7 +12824,6 @@ "23c58afe110c0352": "Limite d'agents", "a27d19aa7504f69a": "mémoire seulement", "710aada747770581": "{working} sur {limit} au travail", - "30a5be40eb956663": "au travail", "ac2c1a39608fc635": "ouvert", "8a72bdb53d14db64": "{count, plural, one {# de plus} other {# de plus}}", "5f2d81b15ca48b42": "Aucun agent ouvert.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index c891a9c5a41dd..504f5406e4287 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": "このランタイムではファイルのストリーミングプレビューを利用できません。", @@ -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", @@ -765,8 +813,13 @@ "166661f94b300f5b": "完了", "d4d89c139de812a8": "失敗", "c1e03a860c856245": "停止", - "f1d27d127ab27ac6": "起動中", + "7e5abc299ead1d09": "{provider} のプラグインを読み込み中", + "21872f69ccbc711d": "{provider} の MCP サーバーを起動中", + "fedaa29ff8815a77": "{provider} のフックを読み込み中", + "57025ae4de5beb57": "{provider} のルールとスキルを読み込み中", + "4729a188600f1501": "{provider} に接続中", "8c8977097681630f": "{provider} を起動中", + "f1d27d127ab27ac6": "起動中", "86d60d42f6cb4a40": "アイドル", "0e8eab930d79d8b4": "待機中", "54002bf654ddbab1": "完了", @@ -1720,6 +1773,8 @@ "2e995206e087c3fc": "接続または保留中の入力が解決してから、返信してください。", "604ec3067171a0d7": "会話", "d6182a057ea12624": "親スレッド", + "f2d8537c33cc55a5": "ワークフロー実行のステップ", + "ba8337dca3232880": "実行を開く", "30fa4a764d11ae42": "{name} をダウンロードできませんでした", "4952f87dc98191a7": "添付ファイルを利用できません。", "2fd6d178493fb407": "現在のターンを中断できませんでした。", @@ -1805,6 +1860,7 @@ "04fd71efaa2c3b92": "プルリクエストを開く", "57e875b79b98ab82": "Issue を開く", "f1db0a234c777a1d": "他のアプリで T3 Code を使用 (MCP)", + "6050f22f63e2bcb5": "ワークフローを開く", "a0cc19e60dd99851": "使用量を開く", "46694969044eee98": "次のワークスペース領域にフォーカス", "0a1011328ba42eef": "前のワークスペース領域にフォーカス", @@ -2495,8 +2551,7 @@ "2d1c111e1b4ae0b0": "スレッド「{title}」を削除しますか?", "c568ab8dad798ec5": "このスレッドの会話履歴が完全に消去されます。", "0fd1c746a0e38003": "スレッドを削除できませんでした", - "0ecde875b0dd2f93": "プロジェクトでスレッドを絞り込み: {projects}", - "1ef65b647231ff0b": "プロジェクトでスレッドを絞り込み", + "1c8fc3c4a42949ab": "プロジェクト: {projects}", "165511761be2855c": "プロジェクトを検索", "a46a6467883575a4": "プロジェクトを検索...", "fdc0e086438a3045": "{project} のプロジェクト設定", @@ -3575,6 +3630,14 @@ "c53bc5a4b0314342": "次のメディア", "2950b1424a3cddf5": "この環境に再接続してから、もう一度メディアを開いてください。", "ef638bf1479a5461": "環境から無効なメディア URL が返されました。", + "3ccfbf7e86868c35": "T3 チームへのフィードバック", + "4e0710d19dfc2e7e": "このレポートを T3 チームに送信しますか?", + "87d0ae0723ba75d1": "この内容だけがこのマシンから送信されます。「送信」を押すまで何も送信されません。", + "bf19826f81484328": "会話を含める", + "260c6b45f52d2f27": "直近 {textTurns} ターンでのあなたのメッセージとエージェントの返信の本文を追加します。", + "ddb7e6f8ce99e657": "このマシンでエージェントを実行できる人だけが、送信または拒否できます。", + "03c1eb603c112f47": "送信しない", + "653405e4ed498d9f": "送信", "262955d6eb632f9b": "ゲストリンクをコピーする際にクリップボード API を利用できませんでした。", "f1a4f2b04cdbb4ef": "ゲストリンクをクリップボードにコピーできませんでした。", "cf3490a604e44d31": "ゲストリンクを作成できませんでした。", @@ -3595,7 +3658,6 @@ "abd89e9eefedf11b": "完了", "18d166056c1ab6ff": "共有を停止", "7a2d510eac9e4587": "ゲストリンクの期限が切れました", - "653405e4ed498d9f": "送信", "21888e302219891d": "拡大した {title} のプレビュー", "419719298a7acaea": "縮小", "ed8d5db95359cff4": "ズームをリセット", @@ -5582,7 +5644,6 @@ }, "。リンクのパスを確認するか、[ファイル] でファイルを探してください。" ], - "b9b6bbd1e1ea189f": "ファイル全体", "d715e9494fdbaaf6": "フォントを読み込めませんでした。", "ff17c777a72b4408": "フォントのプレビューは 10 MB までです。", "6bd41ad699e22f10": "フォントを利用できません。", @@ -5592,6 +5653,7 @@ "a9abaaa4220eae21": "{error} 別のアプリで開くには保存してください。", "c508c9000d9656f8": "フォントのプレビュー", "1c416d621d250be8": "いろはにほへと ちりぬるを わかよたれそ つねならむ", + "d7d08260f16b7828": "ファイルはまだ読み込み中です。少し待ってからもう一度お試しください。", "76ebb03de52c92d6": "テキストビューアーが停止しました。", "f48162e8e8c12af7": "テキストビューアーを読み込めませんでした。ファイルを閉じて、もう一度お試しください。", "bc4c5b13d38a5da7": "プレビューを閉じました。", @@ -5599,8 +5661,6 @@ "9450d1827ef336a1": "別のコピーが進行中です。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 バイト", - "f6e9581cba3467fa": "インデックスを作成しています…", - "2d1f293ac12463fc": "ファイルの残りを読み込んでいます…", "b75105bef8f564a4": "最初の 1,024 列を表示しています。ソースと保存ではすべての列が保持されます。", "2a6e1b1f209c3888": "このファイルは空です。", "192fc79eb3b5b2cb": "この図にはリソース URL、マークアップ、ノードのメタデータ、またはカスタム構成が含まれています。安全に確認するには Mermaid のソースを表示してください。", @@ -5787,7 +5847,6 @@ "0061fff77e36bd4f": "サーバーに接続できませんでした。", "04dfdd46e3dd4a2e": "問題が発生しました。もう一度お試しください。", "084bb2d8127a508d": "送信済み", - "e7c59185f8ab3987": "未送信", "77c01a15bd36d17c": "このリンクは終了したか、無効です", "e0e736810f3cbef2": "所有者に新しいリンクを依頼してください。各リンクは 1 つのブラウザーでのみ使用できます。", "c3c53aa46f7330e5": "このリンクは終了しました", @@ -8786,6 +8845,12 @@ "d3866ead082d14e5": "キーボードショートカットを追加", "d4345c90894a3220": "keybindings.json を開く", "e56a8d51219efaa0": "検索に一致するキーボードショートカットはありません。", + "90a258fff61fd77e": "オフ", + "4060244a7079a0d2": "依頼したとき", + "e88c9d8769544731": "自動", + "f29d1dade4dde8aa": "エージェントは T3 チームにフィードバックを送信しません。", + "93c4c53562d30a98": "依頼すると、エージェントが T3 Code についての短いレポートを表示し、承認した場合に T3 チームへ送信します。", + "cd9ee803e8727017": "エージェントが自ら遭遇した T3 Code の問題も報告します。たとえば、T3 ツールの失敗などです。", "45fa271ea0e1ac8e": "ベータ", "3a678332fc7142f7": "サイドバーのスレッドをプロジェクトフォルダーにまとめます。ピン留めしたスレッドは上部に残り、スヌーズ中と対応済みはフォルダーの下に表示されます。", "e4e91d155cb6a9b4": "シンプルなサイドバー(プロジェクトでグループ化)", @@ -8794,11 +8859,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 が必要です。サインインして、", " ", @@ -8882,7 +8952,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": "これで、ここのエージェントがそこでスレッドを起動し、メッセージを送り、完了を待てるようになります。リンクはその環境の「共有とアクセス」の「承認済みクライアント」に表示され、そこで取り消せます。", @@ -9112,7 +9184,6 @@ "0b4779a1825c85bc": "サイドバーとスレッド一覧に表示される、このプロジェクトグループの共通の名前です。", "f68cbda4df83d739": "プロジェクト名をデフォルトにリセット", "56e37b85027e8431": "プロジェクトのアイコン", - "e88c9d8769544731": "自動", "c99736317da5b1fa": "プロジェクトのアイコンをデフォルトにリセット", "6afaa3e3739dc570": "プロジェクトのアイコンを選択", "51651ce45d481a20": "プロジェクトのアイコンファイルを選択", @@ -10082,7 +10153,6 @@ "16bdc70b858c223f": "自動で開くパネルをデフォルトにリセット", "c5424f09d77138ff": "200,000 トークンを超えるアイドル状態の Claude スレッドを圧縮するタイミングです。戻ってきた後、プロンプトキャッシュの有効期限の直前、またはしない、から選びます。Claude プロバイダーごとに上書きできます。", "3e99c5c14f4939c8": "「アイドル状態のスレッドを圧縮」をデフォルトにリセット", - "d52b3d6bf9f2a013": "混在", "cd72fe451ba0d6aa": "新しいプロジェクト", "394c3bd0a1782c8e": "空のままにすると、「プロジェクトを追加」のブラウザーを開いたときに \"~/\" を使用します。", "f9b912a818bd869d": "プロジェクト追加のベースディレクトリをデフォルトにリセット", @@ -10982,7 +11052,6 @@ "4a237f41ce592b7f": "このプロジェクトのワークツリーは、手動で削除するまで保持します。", "00b8ffd8ea6e6a93": "このプロジェクトでこれらのルールを使用します。", "72c279824d15a999": "各マシンのワークツリーのクリーンアップ設定を使用します。", - "90a258fff61fd77e": "オフ", "b5702d0b64866b08": "カスタム", "c009c901f3eefe78": "削除したスレッドのワークツリーを削除", "431c7cd6d50102b7": "アクティブまたはアーカイブ済みのスレッドを削除したときに、使われていないワークツリーを削除します。ローカルの変更があるワークツリーは保持されます。", @@ -11678,7 +11747,6 @@ "4c70e3e7b3e6c493": "シークレット", "79b768229c9ef672": "メンテナンス", "54b188d65247e42f": "試験的機能", - "f41ea186c275b56e": "情報", "af4b7734da1d5ce7": "音声", "4ec62c39ca3192bf": "ソース管理と Issue", "f2bf529f85e05494": "共有とアクセス", @@ -11733,6 +11801,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", @@ -11804,6 +11873,7 @@ "901a823214edc8c4": "テレメトリー 分析 使用状況データ トラッキング 法的事項 オプトアウト telemetry", "82136480255a5106": "OTel OTLP テレメトリー エクスポート エンドポイント ログ トレース メトリクス Grafana", "659d081051faf7ff": "ログ トレース プロセス リソース履歴 失敗 スパン CPU メモリ diagnostics", + "5eaeacfa9f82051a": "報告 不具合 問題 t3 チーム 送信 フィードバック エージェント ツール 自動 依頼したとき", "f537f91e1ee41d47": "キーボードショートカット ホットキー コマンド キーバインド JSON keybindings", "1ba01e7ceed64b95": "ウィンドウ キャプチャ スクリーンショット window capture", "279b1cceb779ff38": "アプリのテキストを含める", @@ -12289,7 +12359,6 @@ "0bd41ff995d36a66": "キャッシュの読み取り", "3f0dfe0cb15a3272": "キャッシュの書き込み", "1c9d860be42b1c02": "出力", - "78344b60f407928e": "その他", "684e516076de81fe": "標準", "3bbcc1b826fef537": "高速", "66796576034c18ea": "超高速", @@ -12305,6 +12374,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": "ブートストラップ後、認証済みセッションの待機がタイムアウトしました。", @@ -12424,6 +12741,10 @@ "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", + "99d51127f573296b": "別のアカウント", + "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", + "99963c0142e17f00": "新しい {tracker} アカウント用です。", + "6d8e4ebc889bace9": "アカウントを追加", "2c4153283b647365": "Claude {account}: 5時間枠の{session}、週間枠の{weekly}を使用済み", "0ebc6d14caaaca3b": "負荷 {one} · {five} · {fifteen}({cores} コア)", "578c5947c810f7b9": "使用率 {percent}%", @@ -12444,7 +12765,6 @@ "23c58afe110c0352": "エージェント上限", "a27d19aa7504f69a": "メモリのみ", "710aada747770581": "{limit} 中 {working} が作業中", - "30a5be40eb956663": "作業中", "ac2c1a39608fc635": "待機中", "8a72bdb53d14db64": "{count, plural, other {他 # 件}}", "5f2d81b15ca48b42": "開いているエージェントはありません。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 7d1ce97fc7bbb..888baf1d5c692 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": "이 런타임에서는 스트리밍 파일 미리 보기를 사용할 수 없습니다.", @@ -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", @@ -765,8 +813,13 @@ "166661f94b300f5b": "완료", "d4d89c139de812a8": "실패", "c1e03a860c856245": "중지됨", - "f1d27d127ab27ac6": "시작 중", + "7e5abc299ead1d09": "{provider} 플러그인 불러오는 중", + "21872f69ccbc711d": "{provider} MCP 서버 시작 중", + "fedaa29ff8815a77": "{provider} 훅 불러오는 중", + "57025ae4de5beb57": "{provider} 규칙 및 스킬 불러오는 중", + "4729a188600f1501": "{provider}에 연결 중", "8c8977097681630f": "{provider} 시작 중", + "f1d27d127ab27ac6": "시작 중", "86d60d42f6cb4a40": "유휴", "0e8eab930d79d8b4": "대기 중", "54002bf654ddbab1": "완료됨", @@ -1720,6 +1773,8 @@ "2e995206e087c3fc": "연결 또는 대기 중인 입력이 해결된 후 답장해 보세요.", "604ec3067171a0d7": "대화", "d6182a057ea12624": "상위 스레드", + "f2d8537c33cc55a5": "워크플로 실행의 단계", + "ba8337dca3232880": "실행 열기", "30fa4a764d11ae42": "{name}을(를) 다운로드할 수 없습니다", "4952f87dc98191a7": "첨부 파일을 사용할 수 없습니다.", "2fd6d178493fb407": "현재 턴을 중단하지 못했습니다.", @@ -1805,6 +1860,7 @@ "04fd71efaa2c3b92": "풀 리퀘스트 열기", "57e875b79b98ab82": "이슈 열기", "f1db0a234c777a1d": "다른 앱에서 T3 Code 사용(MCP)", + "6050f22f63e2bcb5": "워크플로 열기", "a0cc19e60dd99851": "사용량 열기", "46694969044eee98": "다음 작업 영역으로 포커스 이동", "0a1011328ba42eef": "이전 작업 영역으로 포커스 이동", @@ -2496,8 +2552,7 @@ "2d1c111e1b4ae0b0": "스레드 \"{title}\"을(를) 삭제할까요?", "c568ab8dad798ec5": "이 스레드의 대화 기록이 영구적으로 삭제됩니다.", "0fd1c746a0e38003": "스레드를 삭제하지 못했습니다", - "0ecde875b0dd2f93": "프로젝트별 스레드 필터: {projects}", - "1ef65b647231ff0b": "프로젝트별 스레드 필터", + "1c8fc3c4a42949ab": "프로젝트: {projects}", "165511761be2855c": "프로젝트 검색", "a46a6467883575a4": "프로젝트 검색...", "fdc0e086438a3045": "{project} 프로젝트 설정", @@ -3575,6 +3630,14 @@ "c53bc5a4b0314342": "다음 미디어", "2950b1424a3cddf5": "이 환경에 다시 연결한 후 미디어를 다시 여세요.", "ef638bf1479a5461": "환경에서 잘못된 미디어 URL을 반환했습니다.", + "3ccfbf7e86868c35": "T3 팀에 보내는 피드백", + "4e0710d19dfc2e7e": "이 보고서를 T3 팀에 보낼까요?", + "87d0ae0723ba75d1": "이 내용만 이 컴퓨터에서 전송됩니다. 보내기를 누르기 전에는 아무것도 전송되지 않습니다.", + "bf19826f81484328": "대화 포함", + "260c6b45f52d2f27": "최근 {textTurns}개 턴에서 내 메시지와 에이전트 답변의 본문을 추가합니다.", + "ddb7e6f8ce99e657": "이 컴퓨터에서 에이전트를 실행할 수 있는 사람만 보고서를 보내거나 거절할 수 있습니다.", + "03c1eb603c112f47": "보내지 않기", + "653405e4ed498d9f": "보내기", "262955d6eb632f9b": "게스트 링크를 복사하는 중 클립보드 API를 사용할 수 없습니다.", "f1a4f2b04cdbb4ef": "게스트 링크를 클립보드에 복사하지 못했습니다.", "cf3490a604e44d31": "게스트 링크를 만들 수 없습니다.", @@ -3595,7 +3658,6 @@ "abd89e9eefedf11b": "완료", "18d166056c1ab6ff": "공유 중지", "7a2d510eac9e4587": "게스트 링크 만료됨", - "653405e4ed498d9f": "보내기", "21888e302219891d": "확대된 {title} 미리 보기", "419719298a7acaea": "축소", "ed8d5db95359cff4": "확대/축소 초기화", @@ -5580,7 +5642,6 @@ }, ". 링크의 경로를 확인하거나 파일에서 해당 파일을 찾으세요." ], - "b9b6bbd1e1ea189f": "전체 파일", "d715e9494fdbaaf6": "글꼴을 불러올 수 없습니다.", "ff17c777a72b4408": "글꼴 미리 보기는 10MB로 제한됩니다.", "6bd41ad699e22f10": "글꼴을 사용할 수 없습니다.", @@ -5590,6 +5651,7 @@ "a9abaaa4220eae21": "{error} 저장한 후 다른 앱에서 여세요.", "c508c9000d9656f8": "글꼴 미리 보기", "1c416d621d250be8": "다람쥐 헌 쳇바퀴에 타고파.", + "d7d08260f16b7828": "파일을 아직 불러오는 중입니다. 잠시 후 다시 시도하세요.", "76ebb03de52c92d6": "텍스트 뷰어가 중지되었습니다.", "f48162e8e8c12af7": "텍스트 뷰어를 불러올 수 없습니다. 파일을 닫고 다시 시도하세요.", "bc4c5b13d38a5da7": "미리 보기가 닫혔습니다.", @@ -5597,8 +5659,6 @@ "9450d1827ef336a1": "다른 복사가 진행 중입니다.", "8f48999eb6d9e2e3": "{count, plural, other {{formatted}줄}}", "13b14784f8707ddd": "0바이트", - "f6e9581cba3467fa": "색인하는 중…", - "2d1f293ac12463fc": "파일의 나머지를 불러오는 중…", "b75105bef8f564a4": "처음 1,024열을 표시합니다. 소스와 저장에는 모든 열이 유지됩니다.", "2a6e1b1f209c3888": "이 파일은 비어 있습니다.", "192fc79eb3b5b2cb": "이 다이어그램에는 리소스 URL, 마크업, 노드 메타데이터 또는 사용자 지정 구성이 포함되어 있습니다. 안전하게 확인하려면 Mermaid 소스를 표시하세요.", @@ -5785,7 +5845,6 @@ "0061fff77e36bd4f": "서버에 연결할 수 없습니다.", "04dfdd46e3dd4a2e": "문제가 발생했습니다. 다시 시도하세요.", "084bb2d8127a508d": "보냄", - "e7c59185f8ab3987": "보내지 않음", "77c01a15bd36d17c": "이 링크는 종료되었거나 유효하지 않습니다", "e0e736810f3cbef2": "소유자에게 새 링크를 요청하세요. 각 링크는 한 브라우저에서만 작동합니다.", "c3c53aa46f7330e5": "이 링크는 종료되었습니다", @@ -8789,6 +8848,12 @@ "d3866ead082d14e5": "단축키 추가", "d4345c90894a3220": "keybindings.json 열기", "e56a8d51219efaa0": "검색과 일치하는 단축키가 없습니다.", + "90a258fff61fd77e": "끔", + "4060244a7079a0d2": "내가 요청할 때", + "e88c9d8769544731": "자동", + "f29d1dade4dde8aa": "에이전트가 T3 팀에 피드백을 보내지 않습니다.", + "93c4c53562d30a98": "요청하면 에이전트가 T3 Code에 관한 짧은 보고서를 보여주고, 승인하면 T3 팀에 보냅니다.", + "cd9ee803e8727017": "에이전트가 직접 겪은 T3 Code 문제도 보고합니다. 예를 들어 T3 도구가 실패한 경우입니다.", "45fa271ea0e1ac8e": "베타", "3a678332fc7142f7": "사이드바 스레드를 프로젝트 폴더로 묶습니다. 고정된 스레드는 맨 위에, 다시 알림과 정리됨은 폴더 아래에 유지됩니다.", "e4e91d155cb6a9b4": "단순 사이드바(프로젝트별 그룹화)", @@ -8797,11 +8862,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가 필요합니다. 로그인한 뒤", " ", @@ -8885,7 +8955,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": "그러면 이곳의 에이전트가 그곳에서 스레드를 시작하고, 메시지를 보내고, 기다릴 수 있습니다. 해당 환경의 공유 및 액세스에서 승인된 클라이언트에 표시되며 그곳에서 취소할 수 있습니다.", @@ -9114,7 +9186,6 @@ "0b4779a1825c85bc": "사이드바와 스레드 목록에 표시되는 이 프로젝트 그룹의 공유 이름입니다.", "f68cbda4df83d739": "프로젝트 이름 기본값으로 재설정", "56e37b85027e8431": "프로젝트 아이콘", - "e88c9d8769544731": "자동", "c99736317da5b1fa": "프로젝트 아이콘 기본값으로 재설정", "6afaa3e3739dc570": "프로젝트 아이콘 선택", "51651ce45d481a20": "프로젝트 아이콘 파일 선택", @@ -10084,7 +10155,6 @@ "16bdc70b858c223f": "패널 미리 열기 기본값으로 재설정", "c5424f09d77138ff": "200,000 토큰이 넘는 유휴 Claude 스레드를 압축할 시점입니다. 돌아온 뒤, 프롬프트 캐시가 만료되기 직전, 또는 압축 안 함 중에서 선택합니다. 각 Claude 제공자에서 재정의할 수 있습니다.", "3e99c5c14f4939c8": "유휴 스레드 압축 기본값으로 재설정", - "d52b3d6bf9f2a013": "혼합", "cd72fe451ba0d6aa": "새 프로젝트", "394c3bd0a1782c8e": "프로젝트 추가 탐색기가 열릴 때 \"~/\"를 사용하려면 비워 두세요.", "f9b912a818bd869d": "프로젝트 추가 기본 디렉터리 기본값으로 재설정", @@ -10982,7 +11052,6 @@ "4a237f41ce592b7f": "직접 삭제할 때까지 이 프로젝트의 워크트리를 유지합니다.", "00b8ffd8ea6e6a93": "이 프로젝트에 이 규칙을 사용합니다.", "72c279824d15a999": "각 머신의 워크트리 정리 설정을 사용합니다.", - "90a258fff61fd77e": "끔", "b5702d0b64866b08": "사용자 지정", "c009c901f3eefe78": "삭제된 스레드의 워크트리 삭제", "431c7cd6d50102b7": "활성 또는 보관된 스레드가 삭제되면 사용하지 않는 워크트리를 제거합니다. 로컬 변경 사항이 있는 워크트리는 유지됩니다.", @@ -11674,7 +11743,6 @@ "4c70e3e7b3e6c493": "시크릿", "79b768229c9ef672": "유지 관리", "54b188d65247e42f": "실험 기능", - "f41ea186c275b56e": "정보", "af4b7734da1d5ce7": "음성", "4ec62c39ca3192bf": "소스 제어 및 이슈", "f2bf529f85e05494": "공유 및 액세스", @@ -11729,6 +11797,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 풀 임대 게이트웨이", @@ -11800,6 +11869,7 @@ "901a823214edc8c4": "원격 분석 분석 사용 데이터 추적 법적 옵트아웃", "82136480255a5106": "OTel OTLP 원격 분석 내보내기 엔드포인트 로그 추적 메트릭 Grafana", "659d081051faf7ff": "로그 추적 프로세스 리소스 기록 실패 스팬 cpu 메모리", + "5eaeacfa9f82051a": "보고 버그 문제 t3 팀 보내기 피드백 에이전트 도구 자동 내가 요청할 때", "f537f91e1ee41d47": "키보드 단축키 핫키 명령 바인딩 json", "1ba01e7ceed64b95": "창 캡처 스크린샷", "279b1cceb779ff38": "앱 텍스트 포함", @@ -12285,7 +12355,6 @@ "0bd41ff995d36a66": "캐시 읽기", "3f0dfe0cb15a3272": "캐시 쓰기", "1c9d860be42b1c02": "출력", - "78344b60f407928e": "기타", "684e516076de81fe": "표준", "3bbcc1b826fef537": "빠름", "66796576034c18ea": "초고속", @@ -12301,6 +12370,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": "부트스트랩 후 인증된 세션을 기다리다 시간이 초과되었습니다.", @@ -12419,6 +12737,10 @@ "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", + "99d51127f573296b": "다른 계정", + "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", + "99963c0142e17f00": "새 {tracker} 계정용입니다.", + "6d8e4ebc889bace9": "계정 추가", "2c4153283b647365": "Claude {account}: 5시간 창의 {session}, 주간 한도의 {weekly} 사용", "0ebc6d14caaaca3b": "부하 {one} · {five} · {fifteen} ({cores}코어)", "578c5947c810f7b9": "사용률 {percent}%", @@ -12439,7 +12761,6 @@ "23c58afe110c0352": "에이전트 한도", "a27d19aa7504f69a": "메모리만", "710aada747770581": "{limit}개 중 {working}개 작업 중", - "30a5be40eb956663": "작업 중", "ac2c1a39608fc635": "대기 중", "8a72bdb53d14db64": "{count, plural, other {외 #개}}", "5f2d81b15ca48b42": "열려 있는 에이전트가 없습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 78569e8958b0d..d6b02f571d0c2 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.", @@ -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", @@ -765,8 +813,13 @@ "166661f94b300f5b": "Concluído", "d4d89c139de812a8": "Falhou", "c1e03a860c856245": "Parado", - "f1d27d127ab27ac6": "Iniciando", + "7e5abc299ead1d09": "Carregando plugins do {provider}", + "21872f69ccbc711d": "Iniciando servidores MCP do {provider}", + "fedaa29ff8815a77": "Carregando hooks do {provider}", + "57025ae4de5beb57": "Carregando regras e skills do {provider}", + "4729a188600f1501": "Conectando ao {provider}", "8c8977097681630f": "Iniciando {provider}", + "f1d27d127ab27ac6": "Iniciando", "86d60d42f6cb4a40": "Ocioso", "0e8eab930d79d8b4": "Aguardando", "54002bf654ddbab1": "Concluído", @@ -1721,6 +1774,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.", @@ -1806,6 +1861,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", @@ -2071,7 +2127,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?", @@ -2497,8 +2553,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}", @@ -3579,6 +3634,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.", @@ -3599,7 +3662,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", @@ -5599,7 +5661,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.", @@ -5609,6 +5670,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.", @@ -5616,8 +5678,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.", @@ -5804,7 +5864,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", @@ -8828,6 +8887,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)", @@ -8836,11 +8901,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", " ", @@ -8925,7 +8995,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.", @@ -9155,7 +9227,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", @@ -10129,7 +10200,6 @@ "16bdc70b858c223f": "Redefinir os painéis proativos para o padrão", "c5424f09d77138ff": "Quando compactar uma thread do Claude ociosa com mais de 200.000 tokens: depois que você voltar, logo antes de o cache do prompt expirar ou nunca. Cada provedor Claude pode substituir isso.", "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", @@ -11031,7 +11101,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.", @@ -11727,7 +11796,6 @@ "4c70e3e7b3e6c493": "Segredos", "79b768229c9ef672": "Manutenção", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Sobre", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versões e issues", "f2bf529f85e05494": "Compartilhamento", @@ -11782,6 +11850,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", @@ -11853,6 +11922,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", @@ -12338,7 +12408,6 @@ "0bd41ff995d36a66": "Leitura de cache", "3f0dfe0cb15a3272": "Gravação de cache", "1c9d860be42b1c02": "Saída", - "78344b60f407928e": "Outros", "684e516076de81fe": "Padrão", "3bbcc1b826fef537": "Rápido", "66796576034c18ea": "Ultrarrápido", @@ -12354,6 +12423,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.", @@ -12475,6 +12800,10 @@ "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", + "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", "2c4153283b647365": "Claude {account}: {session} da janela de 5 horas e {weekly} da semana usados", "0ebc6d14caaaca3b": "carga {one} · {five} · {fifteen} em {cores} núcleos", "578c5947c810f7b9": "{percent}% ocupado", @@ -12495,7 +12824,6 @@ "23c58afe110c0352": "Limite de agentes", "a27d19aa7504f69a": "apenas memória", "710aada747770581": "{working} de {limit} trabalhando", - "30a5be40eb956663": "trabalhando", "ac2c1a39608fc635": "aberto", "8a72bdb53d14db64": "{count, plural, one {mais #} other {mais #}}", "5f2d81b15ca48b42": "Nenhum agente aberto.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index fedb8be428597..e76e2171ff8c5 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": "Потоковый предпросмотр файлов недоступен в этой среде выполнения.", @@ -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} КБ", @@ -765,8 +813,13 @@ "166661f94b300f5b": "Готово", "d4d89c139de812a8": "Ошибка", "c1e03a860c856245": "Остановлено", - "f1d27d127ab27ac6": "Запуск", + "7e5abc299ead1d09": "Загрузка плагинов {provider}", + "21872f69ccbc711d": "Запуск MCP-серверов {provider}", + "fedaa29ff8815a77": "Загрузка хуков {provider}", + "57025ae4de5beb57": "Загрузка правил и навыков {provider}", + "4729a188600f1501": "Подключение к {provider}", "8c8977097681630f": "Запуск {provider}", + "f1d27d127ab27ac6": "Запуск", "86d60d42f6cb4a40": "Простаивает", "0e8eab930d79d8b4": "Ожидание", "54002bf654ddbab1": "Завершено", @@ -1721,6 +1774,8 @@ "2e995206e087c3fc": "Попробуйте ответить после восстановления подключения или завершения ожидающего ввода.", "604ec3067171a0d7": "Беседа", "d6182a057ea12624": "Родительский тред", + "f2d8537c33cc55a5": "Шаг запуска воркфлоу", + "ba8337dca3232880": "Открыть запуск", "30fa4a764d11ae42": "Не удалось скачать {name}", "4952f87dc98191a7": "Вложение недоступно.", "2fd6d178493fb407": "Не удалось прервать текущий ход.", @@ -1806,6 +1861,7 @@ "04fd71efaa2c3b92": "Открыть пул-реквесты", "57e875b79b98ab82": "Открыть issue", "f1db0a234c777a1d": "Использовать T3 Code в другом приложении (MCP)", + "6050f22f63e2bcb5": "Открыть воркфлоу", "a0cc19e60dd99851": "Открыть использование", "46694969044eee98": "Фокус на следующую панель рабочей области", "0a1011328ba42eef": "Фокус на предыдущую панель рабочей области", @@ -2497,8 +2553,7 @@ "2d1c111e1b4ae0b0": "Удалить тред «{title}»?", "c568ab8dad798ec5": "История беседы этого треда будет удалена безвозвратно.", "0fd1c746a0e38003": "Не удалось удалить тред", - "0ecde875b0dd2f93": "Фильтр тредов по проекту: {projects}", - "1ef65b647231ff0b": "Фильтр тредов по проекту", + "1c8fc3c4a42949ab": "Проекты: {projects}", "165511761be2855c": "Поиск проектов", "a46a6467883575a4": "Поиск проектов...", "fdc0e086438a3045": "Настройки проекта {project}", @@ -3579,6 +3634,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": "Не удалось создать гостевую ссылку.", @@ -3599,7 +3662,6 @@ "abd89e9eefedf11b": "Готово", "18d166056c1ab6ff": "Прекратить общий доступ", "7a2d510eac9e4587": "Срок гостевой ссылки истёк", - "653405e4ed498d9f": "Отправить", "21888e302219891d": "Развёрнутый предпросмотр: {title}", "419719298a7acaea": "Уменьшить", "ed8d5db95359cff4": "Сбросить масштаб", @@ -5599,7 +5661,6 @@ }, ". Проверьте путь в ссылке или найдите файл в «Файлах»." ], - "b9b6bbd1e1ea189f": "Файл целиком", "d715e9494fdbaaf6": "Не удалось загрузить шрифт.", "ff17c777a72b4408": "Предпросмотр шрифтов ограничен 10 МБ.", "6bd41ad699e22f10": "Шрифт недоступен.", @@ -5609,6 +5670,7 @@ "a9abaaa4220eae21": "{error} Сохраните его, чтобы открыть в другом приложении.", "c508c9000d9656f8": "Предпросмотр шрифта", "1c416d621d250be8": "Съешь же ещё этих мягких французских булок, да выпей чаю.", + "d7d08260f16b7828": "Файл ещё загружается. Повторите попытку через мгновение.", "76ebb03de52c92d6": "Просмотрщик текста остановился.", "f48162e8e8c12af7": "Не удалось загрузить просмотрщик текста. Закройте файл и повторите попытку.", "bc4c5b13d38a5da7": "Предпросмотр закрыт.", @@ -5616,8 +5678,6 @@ "9450d1827ef336a1": "Уже идёт другое копирование.", "8f48999eb6d9e2e3": "{count, plural, one {{formatted} строка} few {{formatted} строки} many {{formatted} строк} other {{formatted} строки}}", "13b14784f8707ddd": "0 байт", - "f6e9581cba3467fa": "Индексация…", - "2d1f293ac12463fc": "Загрузка остальной части файла…", "b75105bef8f564a4": "Показаны первые 1 024 столбца. «Исходник» и «Сохранить» сохраняют все столбцы.", "2a6e1b1f209c3888": "Этот файл пуст.", "192fc79eb3b5b2cb": "Эта диаграмма содержит URL ресурсов, разметку, метаданные узлов или собственную конфигурацию. Откройте исходник Mermaid, чтобы безопасно её изучить.", @@ -5804,7 +5864,6 @@ "0061fff77e36bd4f": "Не удалось связаться с сервером.", "04dfdd46e3dd4a2e": "Что-то пошло не так. Повторите попытку.", "084bb2d8127a508d": "Отправлено", - "e7c59185f8ab3987": "Не отправлено", "77c01a15bd36d17c": "Срок действия ссылки истёк или она недействительна", "e0e736810f3cbef2": "Попросите владельца прислать новую ссылку. Каждая ссылка работает в одном браузере.", "c3c53aa46f7330e5": "Срок действия ссылки истёк", @@ -8830,6 +8889,12 @@ "d3866ead082d14e5": "Добавить сочетание клавиш", "d4345c90894a3220": "Открыть keybindings.json", "e56a8d51219efaa0": "Нет сочетаний клавиш по вашему запросу.", + "90a258fff61fd77e": "Выкл.", + "4060244a7079a0d2": "По моему запросу", + "e88c9d8769544731": "Автоматически", + "f29d1dade4dde8aa": "Агенты не отправляют обратную связь команде T3.", + "93c4c53562d30a98": "По вашему запросу агенты показывают краткий отчёт о T3 Code и с вашего одобрения отправляют его команде T3.", + "cd9ee803e8727017": "Агенты также сообщают о проблемах T3 Code, с которыми сталкиваются самостоятельно, например о сбое инструмента T3.", "45fa271ea0e1ac8e": "Бета", "3a678332fc7142f7": "Группирует треды боковой панели по папкам проектов. Закреплённые треды остаются наверху, а отложенные и разобранные — под папками.", "e4e91d155cb6a9b4": "Простая боковая панель (группировка по проектам)", @@ -8838,11 +8903,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: войдите и привяжите эту машину в разделе", " ", @@ -8926,7 +8996,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": "После этого агенты отсюда смогут запускать треды там, писать в них и ждать их. Связь появится в разделе «Авторизованные клиенты» в «Общем доступе» того окружения, где её можно отозвать.", @@ -9156,7 +9228,6 @@ "0b4779a1825c85bc": "Общее название этой группы проектов на боковой панели и в списках тредов.", "f68cbda4df83d739": "Сбросить название проекта к значению по умолчанию", "56e37b85027e8431": "Значок проекта", - "e88c9d8769544731": "Автоматически", "c99736317da5b1fa": "Сбросить значок проекта к значению по умолчанию", "6afaa3e3739dc570": "Выберите значок проекта", "51651ce45d481a20": "Выберите файл значка проекта", @@ -10132,7 +10203,6 @@ "16bdc70b858c223f": "Сбросить заблаговременные панели к значению по умолчанию", "c5424f09d77138ff": "Когда сжимать неактивный тред Claude больше 200 000 токенов: после вашего возвращения, перед самым истечением его кеша промптов или никогда. Каждый провайдер Claude может это переопределить.", "3e99c5c14f4939c8": "Сбросить сжатие простаивающих тредов к значению по умолчанию", - "d52b3d6bf9f2a013": "Разные", "cd72fe451ba0d6aa": "Новые проекты", "394c3bd0a1782c8e": "Оставьте пустым, чтобы при открытии «Добавить проект» использовался «~/».", "f9b912a818bd869d": "Сбросить базовый каталог для добавления проектов к значению по умолчанию", @@ -11032,7 +11102,6 @@ "4a237f41ce592b7f": "Хранить рабочие деревья этого проекта, пока вы не удалите их вручную.", "00b8ffd8ea6e6a93": "Использовать эти правила для этого проекта.", "72c279824d15a999": "Использовать настройки очистки рабочих деревьев каждой машины.", - "90a258fff61fd77e": "Выкл.", "b5702d0b64866b08": "Свои", "c009c901f3eefe78": "Удалять рабочие деревья вместе с удалёнными тредами", "431c7cd6d50102b7": "Удалять неиспользуемые рабочие деревья при удалении активных или архивных тредов. Рабочие деревья с локальными изменениями сохраняются.", @@ -11728,7 +11797,6 @@ "4c70e3e7b3e6c493": "Секреты", "79b768229c9ef672": "Обслуживание", "54b188d65247e42f": "Эксперименты", - "f41ea186c275b56e": "О приложении", "af4b7734da1d5ce7": "Голос", "4ec62c39ca3192bf": "Контроль версий и issue", "f2bf529f85e05494": "Общий доступ", @@ -11783,6 +11851,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 пул аренда шлюз", @@ -11854,6 +11923,7 @@ "901a823214edc8c4": "телеметрия аналитика данные об использовании отслеживание юридическое отказ", "82136480255a5106": "OTel OTLP телеметрия экспорт конечные точки логи трассировки метрики Grafana", "659d081051faf7ff": "логи трассировки процессы история ресурсов сбои спаны cpu память", + "5eaeacfa9f82051a": "отчёт ошибка проблема t3 команда отправить обратная связь агенты инструменты автоматически по моему запросу", "f537f91e1ee41d47": "сочетания клавиш горячие клавиши команды привязки json", "1ba01e7ceed64b95": "окно захват снимок экрана", "279b1cceb779ff38": "Включать текст приложения", @@ -12339,7 +12409,6 @@ "0bd41ff995d36a66": "Чтение кеша", "3f0dfe0cb15a3272": "Запись кеша", "1c9d860be42b1c02": "Вывод", - "78344b60f407928e": "Другое", "684e516076de81fe": "Стандартная", "3bbcc1b826fef537": "Быстрая", "66796576034c18ea": "Сверхбыстрая", @@ -12355,6 +12424,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": "Истекло время ожидания аутентифицированного сеанса после начальной загрузки.", @@ -12475,6 +12800,10 @@ "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", + "99d51127f573296b": "Другой аккаунт", + "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", + "99963c0142e17f00": "Для нового аккаунта {tracker}.", + "6d8e4ebc889bace9": "Добавить аккаунт", "2c4153283b647365": "Claude {account}: использовано {session} 5-часового окна и {weekly} недельного лимита", "0ebc6d14caaaca3b": "нагрузка {one} · {five} · {fifteen} на {cores} ядрах", "578c5947c810f7b9": "занято {percent}%", @@ -12495,7 +12824,6 @@ "23c58afe110c0352": "Лимит агентов", "a27d19aa7504f69a": "только память", "710aada747770581": "работают {working} из {limit}", - "30a5be40eb956663": "работает", "ac2c1a39608fc635": "открыт", "8a72bdb53d14db64": "{count, plural, one {ещё #} few {ещё #} many {ещё #} other {ещё #}}", "5f2d81b15ca48b42": "Открытых агентов нет.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index aab6a07b96a1b..b226ef1022d82 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.", @@ -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", @@ -765,8 +813,13 @@ "166661f94b300f5b": "Klar", "d4d89c139de812a8": "Misslyckades", "c1e03a860c856245": "Stoppad", - "f1d27d127ab27ac6": "Startar", + "7e5abc299ead1d09": "Läser in plugins för {provider}", + "21872f69ccbc711d": "Startar MCP-servrar för {provider}", + "fedaa29ff8815a77": "Läser in hooks för {provider}", + "57025ae4de5beb57": "Läser in regler och färdigheter för {provider}", + "4729a188600f1501": "Ansluter till {provider}", "8c8977097681630f": "Startar {provider}", + "f1d27d127ab27ac6": "Startar", "86d60d42f6cb4a40": "Inaktiv", "0e8eab930d79d8b4": "Väntar", "54002bf654ddbab1": "Slutförd", @@ -1721,6 +1774,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.", @@ -1806,6 +1861,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", @@ -2497,8 +2553,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}", @@ -3579,6 +3634,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.", @@ -3599,7 +3662,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", @@ -5600,7 +5662,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.", @@ -5610,6 +5671,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.", @@ -5617,8 +5679,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.", @@ -5805,7 +5865,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", @@ -8836,6 +8895,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)", @@ -8844,11 +8909,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", " ", @@ -8932,7 +9002,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.", @@ -9161,7 +9233,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", @@ -9511,9 +9582,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", @@ -10137,7 +10208,6 @@ "16bdc70b858c223f": "Återställ proaktiva paneler till standard", "c5424f09d77138ff": "När en inaktiv Claude-tråd på över 200 000 token ska komprimeras: när du kommer tillbaka, precis innan dess promptcache går ut, eller aldrig. Varje Claude-leverantör kan åsidosätta detta.", "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", @@ -11039,7 +11109,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.", @@ -11735,7 +11804,6 @@ "4c70e3e7b3e6c493": "Hemligheter", "79b768229c9ef672": "Underhåll", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Om", "af4b7734da1d5ce7": "Röst", "4ec62c39ca3192bf": "Versioner och ärenden", "f2bf529f85e05494": "Delning och åtkomst", @@ -11790,6 +11858,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", @@ -11861,6 +11930,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", @@ -12346,7 +12416,6 @@ "0bd41ff995d36a66": "Cacheläsning", "3f0dfe0cb15a3272": "Cacheskrivning", "1c9d860be42b1c02": "Utdata", - "78344b60f407928e": "Övrigt", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Snabb", "66796576034c18ea": "Ultrasnabb", @@ -12362,6 +12431,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.", @@ -12482,6 +12807,10 @@ "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", + "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", "2c4153283b647365": "Claude {account}: {session} av 5-timmarsfönstret och {weekly} av veckan använt", "0ebc6d14caaaca3b": "last {one} · {five} · {fifteen} på {cores} kärnor", "578c5947c810f7b9": "{percent} % upptagen", @@ -12502,7 +12831,6 @@ "23c58afe110c0352": "Agentgräns", "a27d19aa7504f69a": "endast minne", "710aada747770581": "{working} av {limit} arbetar", - "30a5be40eb956663": "arbetar", "ac2c1a39608fc635": "öppen", "8a72bdb53d14db64": "{count, plural, one {# till} other {# till}}", "5f2d81b15ca48b42": "Inga agenter är öppna.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 57a935cbcd470..69f7d49fb0d4e 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": "此运行时不支持流式文件预览。", @@ -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", @@ -765,8 +813,13 @@ "166661f94b300f5b": "完成", "d4d89c139de812a8": "失败", "c1e03a860c856245": "已停止", - "f1d27d127ab27ac6": "正在启动", + "7e5abc299ead1d09": "正在加载 {provider} 插件", + "21872f69ccbc711d": "正在启动 {provider} MCP 服务器", + "fedaa29ff8815a77": "正在加载 {provider} 钩子", + "57025ae4de5beb57": "正在加载 {provider} 规则和技能", + "4729a188600f1501": "正在连接 {provider}", "8c8977097681630f": "正在启动 {provider}", + "f1d27d127ab27ac6": "正在启动", "86d60d42f6cb4a40": "闲置", "0e8eab930d79d8b4": "等待中", "54002bf654ddbab1": "已完成", @@ -1721,6 +1774,8 @@ "2e995206e087c3fc": "请在连接恢复或待处理的输入完成后重试回复。", "604ec3067171a0d7": "对话", "d6182a057ea12624": "父会话", + "f2d8537c33cc55a5": "工作流运行的步骤", + "ba8337dca3232880": "打开运行", "30fa4a764d11ae42": "无法下载 {name}", "4952f87dc98191a7": "附件不可用。", "2fd6d178493fb407": "无法中断当前这一轮。", @@ -1806,6 +1861,7 @@ "04fd71efaa2c3b92": "打开 PR", "57e875b79b98ab82": "打开 issue", "f1db0a234c777a1d": "在其他应用中使用 T3 Code(MCP)", + "6050f22f63e2bcb5": "打开工作流", "a0cc19e60dd99851": "打开用量", "46694969044eee98": "聚焦下一个工作区区域", "0a1011328ba42eef": "聚焦上一个工作区区域", @@ -2501,8 +2557,7 @@ "2d1c111e1b4ae0b0": "删除会话“{title}”?", "c568ab8dad798ec5": "这将永久清除此会话的对话历史。", "0fd1c746a0e38003": "删除会话失败", - "0ecde875b0dd2f93": "按项目筛选会话:{projects}", - "1ef65b647231ff0b": "按项目筛选会话", + "1c8fc3c4a42949ab": "项目:{projects}", "165511761be2855c": "搜索项目", "a46a6467883575a4": "搜索项目…", "fdc0e086438a3045": "{project} 的项目设置", @@ -3584,6 +3639,14 @@ "c53bc5a4b0314342": "下一个媒体", "2950b1424a3cddf5": "请重新连接这个环境,然后再打开媒体。", "ef638bf1479a5461": "环境返回了无效的媒体 URL。", + "3ccfbf7e86868c35": "给 T3 团队的反馈", + "4e0710d19dfc2e7e": "将这份报告发送给 T3 团队?", + "87d0ae0723ba75d1": "只有这些内容会从你的机器发送出去。点击“发送”前,不会发送任何内容。", + "bf19826f81484328": "包含对话", + "260c6b45f52d2f27": "添加你在最近 {textTurns} 轮中的消息和智能体回复的文本。", + "ddb7e6f8ce99e657": "只有能在这台机器上运行智能体的人,才能发送或拒绝这份报告。", + "03c1eb603c112f47": "不发送", + "653405e4ed498d9f": "发送", "262955d6eb632f9b": "复制访客链接时剪贴板 API 不可用。", "f1a4f2b04cdbb4ef": "无法将访客链接复制到剪贴板。", "cf3490a604e44d31": "无法创建访客链接。", @@ -3604,7 +3667,6 @@ "abd89e9eefedf11b": "完成", "18d166056c1ab6ff": "停止分享", "7a2d510eac9e4587": "访客链接已过期", - "653405e4ed498d9f": "发送", "21888e302219891d": "展开的 {title} 预览", "419719298a7acaea": "缩小", "ed8d5db95359cff4": "重置缩放", @@ -5606,7 +5668,6 @@ }, "。请检查链接的路径,或在“文件”中找到该文件。" ], - "b9b6bbd1e1ea189f": "完整文件", "d715e9494fdbaaf6": "无法加载该字体。", "ff17c777a72b4408": "字体预览限制为 10 MB。", "6bd41ad699e22f10": "该字体不可用。", @@ -5616,6 +5677,7 @@ "a9abaaa4220eae21": "{error} 保存后可在其他应用中打开。", "c508c9000d9656f8": "字体预览", "1c416d621d250be8": "敏捷的棕色狐狸跳过了那只懒狗。", + "d7d08260f16b7828": "文件仍在加载中。请稍后重试。", "76ebb03de52c92d6": "文本查看器已停止。", "f48162e8e8c12af7": "无法加载文本查看器。请关闭文件后重试。", "bc4c5b13d38a5da7": "预览已关闭。", @@ -5623,8 +5685,6 @@ "9450d1827ef336a1": "另一个复制操作正在进行。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 字节", - "f6e9581cba3467fa": "正在建立索引…", - "2d1f293ac12463fc": "正在加载文件的其余部分…", "b75105bef8f564a4": "仅显示前 1,024 列。查看源码或保存文件时会保留所有列。", "2a6e1b1f209c3888": "此文件为空。", "192fc79eb3b5b2cb": "此图表包含资源 URL、标记、节点元数据或自定义配置。请显示 Mermaid 源码以安全查看。", @@ -5811,7 +5871,6 @@ "0061fff77e36bd4f": "无法连接到服务器。", "04dfdd46e3dd4a2e": "出了点问题。请重试。", "084bb2d8127a508d": "已发送", - "e7c59185f8ab3987": "未发送", "77c01a15bd36d17c": "此链接已结束或无效", "e0e736810f3cbef2": "请向所有者索取新链接。每个链接只能在一个浏览器中使用。", "c3c53aa46f7330e5": "此链接已结束", @@ -8846,6 +8905,12 @@ "d3866ead082d14e5": "添加快捷键", "d4345c90894a3220": "打开 keybindings.json", "e56a8d51219efaa0": "没有匹配的快捷键。", + "90a258fff61fd77e": "关闭", + "4060244a7079a0d2": "当我要求时", + "e88c9d8769544731": "自动", + "f29d1dade4dde8aa": "智能体不会向 T3 团队发送反馈。", + "93c4c53562d30a98": "当你要求时,智能体会向你展示一份关于 T3 Code 的简短报告,经你批准后发送给 T3 团队。", + "cd9ee803e8727017": "智能体还会主动报告自己遇到的 T3 Code 问题,例如 T3 工具运行失败。", "45fa271ea0e1ac8e": "测试版", "3a678332fc7142f7": "将侧边栏会话按项目文件夹分组。置顶会话保留在顶部,已暂缓和已收尾会话显示在文件夹下方。", "e4e91d155cb6a9b4": "简洁侧边栏(按项目分组)", @@ -8854,11 +8919,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:请登录并在", " ", @@ -8942,7 +9012,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": "这里的智能体随后就能在该环境中启动会话、发送消息并等待结果。此连接将显示在该环境“共享与访问”的“已授权客户端”中,可在那里撤销。", @@ -9172,7 +9244,6 @@ "0b4779a1825c85bc": "此项目组在侧边栏和会话列表中共用的名称。", "f68cbda4df83d739": "重置项目名称为默认值", "56e37b85027e8431": "项目图标", - "e88c9d8769544731": "自动", "c99736317da5b1fa": "重置项目图标为默认值", "6afaa3e3739dc570": "选择项目图标", "51651ce45d481a20": "选择项目图标文件", @@ -10145,7 +10216,6 @@ "16bdc70b858c223f": "重置主动面板为默认值", "c5424f09d77138ff": "空闲且超过 200,000 token 的 Claude 会话何时压缩:在你回来后、提示缓存即将过期前,或从不压缩。每个 Claude 提供方都可以单独覆盖此设置。", "3e99c5c14f4939c8": "重置压缩空闲会话为默认值", - "d52b3d6bf9f2a013": "各不相同", "cd72fe451ba0d6aa": "新项目", "394c3bd0a1782c8e": "留空时,“添加项目”浏览器从“~/”打开。", "f9b912a818bd869d": "重置添加项目基础目录为默认值", @@ -11053,7 +11123,6 @@ "4a237f41ce592b7f": "保留此项目的工作树,直到你手动删除。", "00b8ffd8ea6e6a93": "此项目使用以下规则。", "72c279824d15a999": "使用各机器的工作树清理设置。", - "90a258fff61fd77e": "关闭", "b5702d0b64866b08": "自定义", "c009c901f3eefe78": "删除会话时删除工作树", "431c7cd6d50102b7": "删除活跃或已归档会话时,移除不再使用的工作树。保留有本地改动的工作树。", @@ -11752,7 +11821,6 @@ "4c70e3e7b3e6c493": "凭据", "79b768229c9ef672": "维护", "54b188d65247e42f": "实验功能", - "f41ea186c275b56e": "关于", "af4b7734da1d5ce7": "语音", "4ec62c39ca3192bf": "版本控制与 issue", "f2bf529f85e05494": "共享与访问", @@ -11807,6 +11875,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 池 租用 网关", @@ -11878,6 +11947,7 @@ "901a823214edc8c4": "遥测 分析 用量数据 跟踪 法律 退出", "82136480255a5106": "OTel OTLP 遥测 导出 端点 日志 追踪 指标 Grafana", "659d081051faf7ff": "日志 追踪 进程 资源历史 失败 span cpu 内存", + "5eaeacfa9f82051a": "报告 错误 问题 t3 团队 发送 反馈 智能体 工具 自动 当我要求时", "f537f91e1ee41d47": "键盘 快捷键 热键 命令 绑定 json", "1ba01e7ceed64b95": "窗口 捕获 截图", "279b1cceb779ff38": "包含应用文本", @@ -12364,7 +12434,6 @@ "0bd41ff995d36a66": "缓存读取", "3f0dfe0cb15a3272": "缓存写入", "1c9d860be42b1c02": "输出", - "78344b60f407928e": "其他", "684e516076de81fe": "标准", "3bbcc1b826fef537": "快速", "66796576034c18ea": "极速", @@ -12380,6 +12449,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": "引导完成后等待登录状态超时。", @@ -12501,6 +12819,10 @@ "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", "9e91e9a77b664e4e": "无法开始生成审查导览", + "99d51127f573296b": "其他账号", + "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", + "99963c0142e17f00": "用于新的 {tracker} 账号。", + "6d8e4ebc889bace9": "添加账号", "2c4153283b647365": "Claude {account}:已用 5 小时窗口的 {session},本周额度的 {weekly}", "0ebc6d14caaaca3b": "负载 {one} · {five} · {fifteen}({cores} 核)", "578c5947c810f7b9": "占用 {percent}%", @@ -12521,7 +12843,6 @@ "23c58afe110c0352": "智能体上限", "a27d19aa7504f69a": "仅看内存", "710aada747770581": "{limit} 个中 {working} 个在工作", - "30a5be40eb956663": "工作中", "ac2c1a39608fc635": "空闲中", "8a72bdb53d14db64": "{count, plural, other {另有 # 个}}", "5f2d81b15ca48b42": "没有打开的智能体。", diff --git a/apps/web/src/index.css b/apps/web/src/index.css index d1c43862f2020..2cd9be1d6251f 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -233,6 +233,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); @@ -347,6 +351,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 diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index fb6f719bb2346..84463efc3abfd 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -758,6 +758,77 @@ describe("resolveShortcutCommand", () => { ); }); + it("matches Option symbols against the active Latin layout rather than the US position", () => { + const keybindings = compile([ + { shortcut: modShortcut("a", { altKey: true, shiftKey: true }), command: "appearance.cycle" }, + { shortcut: modShortcut("q", { altKey: true, shiftKey: true }), command: "sidebar.toggle" }, + ]); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "Æ", code: "KeyQ", metaKey: true, altKey: true, shiftKey: true }), + keybindings, + { platform: "MacIntel", keyboardLayoutMap: new Map([["KeyQ", "a"]]) }, + ), + "appearance.cycle", + ); + }); + + it("preserves physical punctuation alongside an Option-modified mapped letter", () => { + for (const key of [";", "m"]) { + const keybindings = compile([ + { shortcut: modShortcut(key, { altKey: true }), command: "diff.toggle" }, + ]); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "µ", code: "Semicolon", metaKey: true, altKey: true }), + keybindings, + { platform: "MacIntel", keyboardLayoutMap: new Map([["Semicolon", "m"]]) }, + ), + "diff.toggle", + ); + } + }); + + it("keeps Latin event keys and unsupported layout fallbacks", () => { + const keybindings = compile([ + { shortcut: modShortcut("a", { altKey: true }), command: "appearance.cycle" }, + { shortcut: modShortcut("q", { altKey: true }), command: "sidebar.toggle" }, + ]); + const options = { platform: "MacIntel", keyboardLayoutMap: new Map([["KeyQ", "a"]]) }; + assert.strictEqual( + resolveShortcutCommand( + event({ key: "q", code: "KeyQ", metaKey: true, altKey: true }), + keybindings, + options, + ), + "sidebar.toggle", + ); + for (const keyboardLayoutMap of [new Map(), new Map([["KeyQ", "й"]])]) { + assert.strictEqual( + resolveShortcutCommand( + event({ key: "Æ", code: "KeyQ", metaKey: true, altKey: true }), + keybindings, + { ...options, keyboardLayoutMap }, + ), + "sidebar.toggle", + ); + } + assert.strictEqual( + resolveShortcutCommand( + event({ + key: "Æ", + code: "KeyQ", + ctrlKey: true, + altKey: true, + getModifierState: () => true, + }), + keybindings, + { ...options, platform: "Win32" }, + ), + null, + ); + }); + it("matches non-Latin layout letters using the physical key code", () => { const keybindings = compile([{ shortcut: modShortcut("d"), command: "diff.toggle" }]); diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index f05067a2e53bc..117847faa95bb 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -17,13 +17,24 @@ import { resolveEventKeys, type ShortcutEventLike as SharedShortcutEventLike, type ShortcutModifierStateLike, + type ShortcutKeyboardLayoutMap, + shortcutKeyFromEvent as sharedShortcutKeyFromEvent, } from "@t3tools/shared/keybindings"; import { isElectron } from "./env"; import { isEditableFocused } from "./lib/editableFocus"; import { projectScriptIdFromCommand } from "./projectScripts"; +import { getKeyboardLayoutMap } from "./keyboardLayout"; export type { ShortcutModifierStateLike } from "@t3tools/shared/keybindings"; -export { shortcutKeyFromEvent } from "@t3tools/shared/keybindings"; +export function shortcutKeyFromEvent( + event: Pick, + platform: string, +) { + return sharedShortcutKeyFromEvent( + event, + isMacPlatform(platform) && event.altKey ? getKeyboardLayoutMap() : undefined, + ); +} export interface ShortcutEventLike extends SharedShortcutEventLike { target?: EventTarget | null; @@ -42,6 +53,7 @@ export interface ShortcutMatchContext { interface ShortcutMatchOptions { platform?: string; + keyboardLayoutMap?: ShortcutKeyboardLayoutMap; context?: Partial; } @@ -194,7 +206,15 @@ export function resolveShortcutCommand( const binding = keybindings[index]; if (!binding) continue; if (!matchesWhenClause(binding.whenAst, context)) continue; - if (!matchesKeybindingShortcut(event, shortcutForContext(binding, context), platform)) continue; + if ( + !matchesKeybindingShortcut( + event, + shortcutForContext(binding, context), + platform, + options?.keyboardLayoutMap ?? getKeyboardLayoutMap(), + ) + ) + continue; return binding.command; } return null; diff --git a/apps/web/src/keyboardLayout.test.ts b/apps/web/src/keyboardLayout.test.ts new file mode 100644 index 0000000000000..b33ef3218041d --- /dev/null +++ b/apps/web/src/keyboardLayout.test.ts @@ -0,0 +1,81 @@ +import { afterEach, assert, it } from "vite-plus/test"; +import { getKeyboardLayoutMap, trackKeyboardLayout } from "./keyboardLayout"; +import { keybindingFromKeyboardEvent } from "./components/settings/KeybindingsSettings.logic"; + +let stop: (() => void) | undefined; +afterEach(() => stop?.()); + +function pendingLayout() { + let resolve!: (layout: Map) => void; + const promise = new Promise>((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +it.each([true, false])( + "records Option symbols and refreshes the current layout (keyboard events: %s)", + async (supportsEvents) => { + let layout = Promise.resolve(new Map([["KeyQ", "a"]])); + const keyboard = Object.assign(supportsEvents ? new EventTarget() : {}, { + getLayoutMap: () => layout, + }); + const focusTarget = new EventTarget(); + stop = trackKeyboardLayout(keyboard, focusTarget); + await keyboard.getLayoutMap(); + const event = { + key: "Æ", + code: "KeyQ", + metaKey: true, + ctrlKey: false, + altKey: true, + shiftKey: true, + }; + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+a"); + assert.strictEqual( + keybindingFromKeyboardEvent(event, "MacIntel", { layoutCharacter: true }), + "mod+alt+shift+a", + ); + const pending = pendingLayout(); + layout = pending.promise; + focusTarget.dispatchEvent(new Event("focus")); + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+a"); + pending.resolve(new Map([["KeyQ", "q"]])); + await layout; + assert.strictEqual(keybindingFromKeyboardEvent(event, "MacIntel"), "mod+alt+shift+q"); + layout = Promise.reject(new Error("Permission denied")); + focusTarget.dispatchEvent(new Event("focus")); + assert.strictEqual(getKeyboardLayoutMap()?.get("KeyQ"), "q"); + await layout.catch(() => undefined); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + layout = Promise.resolve(new Map([["KeyQ", "a"]])); + stop(); + focusTarget.dispatchEvent(new Event("focus")); + await keyboard.getLayoutMap(); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + }, +); + +it("ignores an obsolete layout result", async () => { + const pending = pendingLayout(); + let result = pending.promise; + const keyboard = Object.assign(new EventTarget(), { getLayoutMap: () => result }); + stop = trackKeyboardLayout(keyboard); + result = Promise.resolve(new Map([["KeyQ", "q"]])); + keyboard.dispatchEvent(new Event("layoutchange")); + assert.strictEqual(getKeyboardLayoutMap(), undefined); + await result; + pending.resolve(new Map([["KeyQ", "a"]])); + await pending.promise; + assert.strictEqual(getKeyboardLayoutMap()?.get("KeyQ"), "q"); +}); + +it("does not publish a pending result after disposal", async () => { + const pending = pendingLayout(); + const keyboard = Object.assign(new EventTarget(), { getLayoutMap: () => pending.promise }); + stop = trackKeyboardLayout(keyboard); + stop(); + pending.resolve(new Map([["KeyQ", "a"]])); + await pending.promise; + assert.strictEqual(getKeyboardLayoutMap(), undefined); +}); diff --git a/apps/web/src/keyboardLayout.ts b/apps/web/src/keyboardLayout.ts new file mode 100644 index 0000000000000..61fd6e24a1b57 --- /dev/null +++ b/apps/web/src/keyboardLayout.ts @@ -0,0 +1,44 @@ +import type { ShortcutKeyboardLayoutMap } from "@t3tools/shared/keybindings"; + +interface KeyboardLayoutSource extends Partial< + Pick +> { + getLayoutMap(): Promise; +} + +let keyboardLayoutMap: ShortcutKeyboardLayoutMap | undefined; + +export function getKeyboardLayoutMap() { + return keyboardLayoutMap; +} + +// Option changes event.key to a symbol on macOS; the layout map recovers the +// letter printed on that key without assuming a US physical layout. +export function trackKeyboardLayout( + keyboard = (navigator as Navigator & { keyboard?: KeyboardLayoutSource }).keyboard, + focusTarget: EventTarget | undefined = typeof window === "undefined" ? undefined : window, +) { + let revision = 0; + const refresh = async (clearMap: boolean) => { + const request = ++revision; + if (clearMap) keyboardLayoutMap = undefined; + try { + const layout = await keyboard?.getLayoutMap(); + if (request === revision) keyboardLayoutMap = layout; + } catch { + // Unsupported or permission-blocked browsers keep the existing fallback. + if (request === revision) keyboardLayoutMap = undefined; + } + }; + const onLayoutChange = () => void refresh(true); + const onFocus = () => void refresh(false); + void refresh(true); + keyboard?.addEventListener?.("layoutchange", onLayoutChange); + focusTarget?.addEventListener("focus", onFocus); + return () => { + revision++; + keyboardLayoutMap = undefined; + keyboard?.removeEventListener?.("layoutchange", onLayoutChange); + focusTarget?.removeEventListener("focus", onFocus); + }; +} diff --git a/apps/web/src/lib/chunkReloadGuard.ts b/apps/web/src/lib/chunkReloadGuard.ts index 10f4dc8be191c..43034ccb578b3 100644 --- a/apps/web/src/lib/chunkReloadGuard.ts +++ b/apps/web/src/lib/chunkReloadGuard.ts @@ -34,3 +34,15 @@ 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(); + } + }); +} 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/preserveReadingPosition.ts b/apps/web/src/lib/preserveReadingPosition.ts new file mode 100644 index 0000000000000..2c6f576519911 --- /dev/null +++ b/apps/web/src/lib/preserveReadingPosition.ts @@ -0,0 +1,115 @@ +import { observeResize } from "./observeResize"; + +/** Native anchoring keeps a paragraph's start fixed, losing the visible line in a long paragraph. */ +export function preserveReadingPosition( + scroller: HTMLElement, + enabled: () => boolean = () => true, +): () => void { + let width = scroller.clientWidth; + let anchor: { range: Range; top: number } | null = null; + let frame: number | null = null; + + const capture = () => { + if (frame !== null || scroller.clientWidth !== width) return; + anchor = null; + if (!enabled() || scroller.scrollTop === 0) return; + const box = scroller.getBoundingClientRect(); + const selection = + scroller.isContentEditable && document.activeElement === scroller + ? document.getSelection() + : null; + if (selection?.isCollapsed && selection.rangeCount > 0) { + const range = selection.getRangeAt(0).cloneRange(); + const rect = range.getBoundingClientRect(); + if ( + scroller.contains(range.startContainer) && + rect.top >= box.top && + rect.bottom <= box.bottom + ) { + anchor = { range, top: rect.top - box.top }; + return; + } + } + // A point near the top captures text rather than the paragraph's bounding box. + const x = box.left + box.width / 2; + // The first point can land in paragraph spacing. Look only within the first few lines. + for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) { + const y = box.top + inset; + const position = document.caretPositionFromPoint?.(x, y); + const range = document.createRange(); + if (position) { + range.setStart(position.offsetNode, position.offset); + } else { + const fallback = document.caretRangeFromPoint?.(x, y); + if (!fallback) continue; + range.setStart(fallback.startContainer, fallback.startOffset); + } + range.collapse(true); + if ( + !scroller.contains(range.startContainer) || + range.startContainer.nodeType !== Node.TEXT_NODE + ) + continue; + const top = range.getBoundingClientRect().top - box.top; + if (top >= 0 && top < scroller.clientHeight) { + anchor = { range, top }; + break; + } + } + }; + const restore = () => { + if ( + !enabled() || + !anchor || + anchor.range.startContainer.nodeType !== Node.TEXT_NODE || + !scroller.contains(anchor.range.startContainer) + ) + return; + const delta = + anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top; + if (Math.abs(delta) > 0.5) scroller.scrollTop += delta; + }; + const stop = observeResize(scroller, () => { + const nextWidth = scroller.clientWidth; + if (nextWidth === width) { + capture(); + return; + } + width = nextWidth; + restore(); + if (frame !== null) cancelAnimationFrame(frame); + // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then. + frame = requestAnimationFrame(() => { + restore(); + frame = null; + capture(); + }); + }); + scroller.addEventListener("scroll", capture, { passive: true }); + scroller.addEventListener("input", capture); + const captureSelection = () => { + if (document.activeElement === scroller) capture(); + }; + if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection); + const interrupt = () => { + if (frame !== null) cancelAnimationFrame(frame); + anchor = null; + // Scrolling wins over a pending resize correction; the next frame captures the reader's new place. + frame = requestAnimationFrame(() => { + frame = null; + width = scroller.clientWidth; + capture(); + }); + }; + scroller.addEventListener("wheel", interrupt, { passive: true }); + scroller.addEventListener("touchmove", interrupt, { passive: true }); + return () => { + stop(); + if (frame !== null) cancelAnimationFrame(frame); + scroller.removeEventListener("scroll", capture); + scroller.removeEventListener("input", capture); + document.removeEventListener("selectionchange", captureSelection); + scroller.removeEventListener("wheel", interrupt); + scroller.removeEventListener("touchmove", interrupt); + }; +} 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 56be08671e331..11b9b68c867d1 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"); @@ -20,8 +20,8 @@ async function bootThenFailLazyChunk(sessionStorage: Map) { vi.stubGlobal("window", page); vi.stubGlobal("document", { getElementById: () => ({}) }); 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..2640ca1e167d0 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -4,25 +4,21 @@ import ReactDOM from "react-dom/client"; import "@fontsource-variable/inter"; import "./index.css"; +import { trackKeyboardLayout } from "./keyboardLayout"; import { hasCloudPublicConfig } from "./cloud/publicConfig"; 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 stopTrackingKeyboardLayout = trackKeyboardLayout(); +import.meta.hot?.dispose(stopTrackingKeyboardLayout); 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 +36,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 +48,6 @@ export const startup = Promise.all([ ); }) .catch((error: unknown) => { - if (reloadScheduled) return; + if (chunkLoadState.reloadScheduled) return; throw error; }); diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 2d2e74ab58ef2..b1cc1b86c29ba 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' @@ -99,6 +100,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', @@ -302,6 +308,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 @@ -347,6 +354,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 @@ -395,6 +403,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 @@ -444,6 +453,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/$environmentId/$threadId' | '/draft/$draftId' @@ -489,6 +499,7 @@ export interface FileRouteTypes { | '/pull-requests' | '/settings' | '/usage' + | '/workflows' | '/projects/$projectKey' | '/' | '/$environmentId/$threadId' @@ -536,6 +547,7 @@ export interface FileRouteTypes { | '/_chat/pull-requests' | '/_chat/settings' | '/_chat/usage' + | '/_chat/workflows' | '/projects/$projectKey' | '/_chat/' | '/_chat/$environmentId/$threadId' @@ -648,6 +660,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' @@ -973,6 +992,7 @@ interface ChatRouteChildren { ChatPullRequestsRoute: typeof ChatPullRequestsRoute ChatSettingsRoute: typeof ChatSettingsRouteWithChildren ChatUsageRoute: typeof ChatUsageRoute + ChatWorkflowsRoute: typeof ChatWorkflowsRoute ChatIndexRoute: typeof ChatIndexRoute ChatEnvironmentIdThreadIdRoute: typeof ChatEnvironmentIdThreadIdRoute ChatDraftDraftIdRoute: typeof ChatDraftDraftIdRoute @@ -985,6 +1005,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.ts b/apps/web/src/session-logic.ts index 5196ee43458d8..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 { 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 71e8875bb56db..734fe38dad33b 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 005e828202bda..e107c9a7e7491 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -111,6 +111,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/performance-regressions.md b/docs/internals/performance-regressions.md index 25ecabd80c5a4..e67ff30a85e6a 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -97,6 +97,29 @@ catalog digests and status deltas gets the provider list of its first config in provider with 250 slash commands and 200 skills. The lists load with the first cwd snapshot, and a machine refresh sends back an empty provider list. +## Server process metrics + +`node scripts/server-metrics.ts run --out ` starts a checkout's server against throwaway +state, a fake Anthropic API and the real `claude` CLI, and records server CPU, wakeups, RSS and +heap at rest, with quiet Claude threads and with 5 streaming, plus how long a new thread takes to +reach the API. Only the server process is measured. + +- Compare refs with `ab `, not with two files from different times. It + alternates the two on one machine, and `compare` flags a metric only when the bootstrap interval + of the median difference clears both the threshold and the noise floor. Single runs on a busy + machine differ by more than most regressions. +- Read per-thread cost from `scaling`, a fit over 5 to 20 open threads. It separates what each + open thread costs from the fixed cost of the server, which the absolute numbers mix. +- `--soak ` reports heap and RSS slopes in MB per hour and the constructors that grew. + A rising heap floor is a leak; a high but flat one is not. +- The quiet and streaming windows save a CPU and an allocation profile, so a regression comes with + the functions that cost it. + +Run it on macOS and Windows too, and on Linux with `--no-agent-scope`. Only Linux has agent +scopes, so other platforms take per-process paths a Linux server with a systemd user manager never +runs. A one-second `ps -A` poll per Claude session cost 0.1.11 about 18% of a core with 20 open +threads on macOS and went unnoticed on Linux. + ## Event store and startup Sequence cursors must seek an index rather than scan retained history. The application sequence 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 2b9ab85f40f22..b5b33d0650f9d 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -492,6 +492,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/progress.md b/docs/progress.md index d8c825422f51f..543f4db2d7bd9 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -324,3 +324,19 @@ - Review: one independent read-only review found no bugs. It confirmed that in `ProviderTurnStartService.ts` the merge differs from upstream by exactly the fork's three changes (`continueInstead`, the dropped refusal, `resume: false` for it), that `resume: false` keeps upstream's new delivery-session `resumeTurn` and resume `operation` branch unreachable for these sessions, that pending context is delivered once, and that the other shared files differ from fork main by exactly upstream's lines. - Switching the hubs: these 17 commits add no migrations and change no lockfile or package manifests; hub2's live database is still at 102, so its switch applies 103-105 from earlier syncs. - Next: Tomáš merges the PR, then switches hub2 and hub to the new build. + +## 2026-11-23: Fork synced with upstream `ba588ef663` by a merge + +- What: upstream main `ba588ef663`, 163 commits newer than the last sync base `c198f73b37` (696 files, +58498/-3997), was merged into `tomas/sync-upstream-2026-11-23` at fork main `0830f64a0f` (#33) with a real merge (`658ba99ae7`), as in the last eight syncs. Fork main is the first parent and was the branch head, so no `-s ours` merge was needed and the PR needs no force-push. The upstream commits bring durable workflows (#38882, #38884), milestones over MCP (#40774, #41141), more Linear accounts (#39179) and agent feedback (#35871). +- Why: fork main was 156 upstream commits behind when the sync was asked for. Seven more landed during the checks (#41263, #25208, #41256, #41264, #26965, #41258, #24034). They touch none of the fork's files, so the unpushed merge was redone on `ba588ef663` with the same resolutions: `git merge-tree` of the first merge (`d67b02a55c`) and the new head, committed with fork main and `ba588ef663` as parents. Its tree differs from the first merge by exactly those seven commits, and the fork's diff against upstream is byte-identical. +- Conflicts: four code files and the 10 web catalogs, each resolved by keeping both sides. `useSidebarRowThreadKey.ts` (mobile): upstream #41143 moved the lookup into an atom family, and the fork's `nestLaunchedThreads: false` moved with it. MCP project `handlers.ts`: the fork's computed `delegatedFrom` (a local launch's caller is its parent) beside upstream's link-only `workflowRun`. `Orchestrator.ts` `thread.create`: the fork's unconditional `delegatedFrom` beside upstream's `workflowRun`; `withCreationProvenance` strips both from client commands. `server.ts`: the fork's `LaunchedThreadNoticeReactor` beside upstream's `MilestoneHub` and `OrchestrationMilestones` reactor. The web catalogs conflicted at their tails: upstream's 4 tracker-account keys come first, then the fork's keys. +- Shared catalog key: upstream's workflow feed added `gt("working")`, and the fork's machine bar had already appended the same key (`30a5be40eb956663`; a key is the hash of its source text). Git kept both copies, so the fork's tail copy was dropped and upstream's entry, in source order, serves both. The values match in 9 locales; fr now reads upstream's "en cours" instead of the fork's "au travail". Each of the 20 catalogs parses to base plus the fork's key changes (+64/-3 per web catalog, +1/-1 per mobile catalog) plus upstream's (+210/-6 per web catalog, +133/-1 per mobile catalog), with no duplicate keys and no other key changed by both sides. +- Fork behavior kept: the fork's diff against upstream is 121 files before (`c198f73b37..0830f64a0f`, +7064/-319) and after the merge (`ba588ef663..658ba99ae7`, +7054/-319). The added and removed lines are identical in 110 files. The other 11 are the mobile hook (the same change, one level deeper) and the 10 web catalogs (the comma anchor moved to upstream's last key, and the shared key left the fork's tail). In the other direction, `0830f64a0f..658ba99ae7` carries upstream's change line for line in all but those 11 files. +- Follow-ups, one commit each after the merge. `fix(server): Auto failover leaves workflow steps to their workflow`: a workflow retries a step whose turn died, on a new thread or the same one, and the fork's failover would also have sent "Continue where you left off" to the dead step's thread 1.5 s later, so the step ran twice and a step model the workflow pinned moved to Auto. `autoFailoverPlan` now returns null for `lineage.workflowStep`; the new row in `AutoFailoverService.test.ts` failed before the fix and the file passes 8/8 after. `test(mobile)`: upstream's new `useSidebarRowThreadKey.test.tsx` (#41143) uses a delegated child whose parent is in the same environment. In the fork that is a launched thread, which keeps its own row on mobile, so the test failed on the merge (the child's key instead of the parent's). Its parent now lives in a linked environment, the case upstream's `delegatedFrom` stands for; 1/1. +- Checked and left alone: #41086 restarts the updated Claude CLI on a model change and #41174 releases idle sessions after 2 minutes; the fork's Auto level is part of the query identity and of `canApplyClaudeSelectionLive`, so a new process gets it from the selection again. #30261 (slash commands go verbatim) and #34499 (a stopped parent hears which tasks its Stop interrupted) sit beside `continueInstead`, whose resume prompt and dropped refusal are unchanged. #25537's new "no child asks" short-circuit in `threadShell.ts` uses `asksParent`, which already counts launched threads through `delegatedFrom`. In ChatView, the workflow-run parent link takes precedence over `delegatedFrom`, and `ThreadForkService` strips both from forks. `OrchestratorV2Shape` did not change, so Auto routing still wraps every dispatch, and workflow step launches go through `ThreadLaunchService` and get Auto-routed. Upstream did not touch `autoModel.ts`, `AutoFailoverService.ts`, `KeepAwake.ts`, `MachineStatus.ts`, `ThreadMessageIntake.ts`, `LaunchedThreadNoticeReactor.ts` or the usage-limit helpers. +- Review: one read-only review on the Auto instance (the Codex reviewer was unavailable) confirmed all five resolutions and found the failover bug above. Its second point was left as is: a thread launched by a workflow step's agent nests under that step thread, which lives in the run's view, not the sidebar. That is the fork's nesting rule (a launched thread shows under its launcher, as under a subagent launcher). The thread stays reachable from the run's step thread, and its notice waking the step is wanted, since a workflow step may end its turn and be woken to submit its result. +- Agent context: `mcpToolListJsonBytes` grows 59192 -> 61724 (+2532), all from upstream: #35871 agent feedback +1206, #38882 workflows +1350, #40806 and #41005 -24. The fork's tool text is unchanged: `AgentContextBudget.test.ts` passes 2/2 against upstream's budget file. The PR needs the `agent-context-increase` label for the Agent context budget check. +- Numbers: `vp run check:changed upstream/main --timeout 2700` on the first merge (the fork's 121 files): unused patches, format, lint, knip, graphql, typecheck (43 packages) and react compiler (27 files) pass; tests 1641/1642 in 59 files in 11m39s. The one failure was the mobile test above. `vp run check:changed origin/main --timeout 3600` on the final head (upstream's 696 files and the two follow-ups): unused patches, format, lint, knip, graphql (2), typecheck (43 packages) and react compiler (166 files) pass; tests 8600/8601 in 293 files (8 skipped) in 30m08s of a 34m36s run. The one failure, upstream's "a mounted thread view lets go of the thread structures it has replaced" in `ChatView.browser.test.tsx`, hit its 15 s timeout under the parallel run; that file alone passes 19/19. `vp run check:changed upstream/main --timeout 2700` on the final head (the fork's 122 files, the follow-ups included): every step passes, tests 1642/1642 in 59 files, in 7m34s. `vp run i18n:check` passes. +- Real run: a copy of the live database was taken through a read-only connection (`VACUUM INTO`, 472 MB, under the worktree's ignored `.t3` and deleted after seeding). `vp run migrate-dev-db --base-dir .t3/verify --source ` seeded a scratch data dir from it (49.7 MB, 5 projects, 26 threads), applying migrations 103-105 from earlier syncs and upstream's new 106-110 (`WorktreePathKeyIndex`, `DeferredSlashCommandIndex`, `AgentFeedback`, `IssueTrackerAccounts`, `Workflows`). `vp run dev:server --home-dir .t3/verify --no-seed` booted on that dir on port 16306, completed V2 orchestration recovery and answered HTTP 302. The harness stopped its task; the port was released. No agent turn was sent. Warnings: the expected two (no Rust build for the resource monitor, the scratch home inside the Git repo), and on stop the keep-awake run event stream logged its interrupt, as in the last sync. +- Switching the hubs: hub2's live database is at migration 102, so its switch applies 103-110. The lockfile and package manifests changed (`pnpm-lock.yaml`, `pnpm-workspace.yaml`, client-runtime and shared `package.json`), so the new build needs `vp i`. Workflows stay off until **Settings → Labs** turns them on. +- Next: Tomáš adds the `agent-context-increase` label and merges the PR, then switches hub2 and hub to the new build. 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 9c164f91c9962..30c8aba13ffb1 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/project-settings.md b/docs/user/project-settings.md index 775adeb67d900..fe367c7b45b3a 100644 --- a/docs/user/project-settings.md +++ b/docs/user/project-settings.md @@ -103,6 +103,9 @@ project starts a new thread there on its next run. Deleting a thread also deletes tasks that post into that thread. Tasks that start a new thread on each run survive deletion of their previous threads. +An archived thread refuses messages, so a task that posts into one stays on and fails +each run until you unarchive the thread or pick another destination. To set a task's thread +aside without breaking it, settle the thread; see [Settle or archive](thread-sidebar.md#settle-or-archive). You can edit, pause, resume, run immediately, or delete a task from the list. Webhook tasks only run when their URL is called, so they can't be run 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 b6702c13de5d9..ba951c3fe9bda 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -416,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/thread-sidebar.md b/docs/user/thread-sidebar.md index 8029c547abe1e..31331d15bdd07 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -213,6 +213,19 @@ rules to connected environments that support shared settings. Offline environmen and older servers keep their previous values. Changing a rule does not reopen already settled threads. +### Settle or archive + +Settle is for work that is done for now. A settled thread stays in the sidebar's Settled +section and in search, and a message to it, from you, an agent, or a scheduled task, makes it +active again. Archive is for work you want out of the way. An archived thread leaves the +sidebar and search and shows only in **Settings → Archive**, where you can unarchive or +delete it. It refuses new messages, including ones from agents and scheduled tasks, until you +unarchive it. Removing a project deletes its threads either way. + +A scheduled task that posts into one thread keeps running after you archive that thread, and +each run fails. Settle the thread instead, or move or pause the task in **Settings → Scheduled +tasks**. + ## Link a pull request The server finds the PR for each unsettled thread's saved branch, even when your 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, @@ -554,6 +567,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); /** @@ -574,12 +589,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)), ); @@ -589,7 +606,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; @@ -600,6 +622,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, }; @@ -607,8 +630,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; } @@ -698,6 +726,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; }, ) => { @@ -724,7 +754,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. @@ -794,6 +827,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 => { @@ -829,7 +864,11 @@ const buildCodexBase = ( return [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( @@ -2101,6 +2140,8 @@ const savedSecretFile = ( } }; +const decodeFeedbackInput = Schema.decodeUnknownResult(FeedbackInput); + /** The result for one tool call. */ const FORGE_WRITE_TOOLS = new Set([ "pull_request_create", @@ -2257,6 +2298,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); @@ -3217,6 +3291,7 @@ const main = Effect.gen(function* () { browserAccess: boolean, links: boolean, forge: boolean, + agentFeedback: Contracts.AgentFeedbackMode = "off", ): Effect.Effect => codex ? decodeCodexCapture(template).pipe( @@ -3230,6 +3305,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }), ), @@ -3245,6 +3321,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }); return role === "native-subagent" @@ -3256,18 +3333,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, @@ -3277,6 +3355,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 `