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/ipc/methods/window.test.ts b/apps/desktop/src/ipc/methods/window.test.ts index b256025eff844..9c50501a1bdfd 100644 --- a/apps/desktop/src/ipc/methods/window.test.ts +++ b/apps/desktop/src/ipc/methods/window.test.ts @@ -4,6 +4,7 @@ import type { ManagedPolicyLimits } from "@t3tools/contracts"; import { EDITORS, REMOTE_CAPABLE_EDITOR_IDS } from "@t3tools/contracts"; import { resolveEditorCommand } from "@t3tools/shared/editor"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { makePathDirectoryListings, PathDirectoryListings } from "@t3tools/shared/shell"; import { ManagedPolicyFileError } from "@t3tools/shared/managedPolicyFile"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; @@ -11,6 +12,7 @@ import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { vi } from "vite-plus/test"; import type * as Electron from "electron"; @@ -550,6 +552,7 @@ it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( ); describe("probeRemoteEditors PATH scan", () => { + const FIXTURE_MTIME = 1_767_225_600; const platform = HostProcess.Platform.defaultValue(); const launcherName = (command: string) => (platform === "win32" ? `${command}.cmd` : command); @@ -570,6 +573,9 @@ describe("probeRemoteEditors PATH scan", () => { yield* fs.writeFileString(file, "#!/bin/sh\n"); if (platform !== "win32") yield* fs.chmod(file, 0o755); } + // A listing of a directory changed moments ago is not kept, so age them past that window. + for (const dir of dirs) yield* fs.utimes(dir, FIXTURE_MTIME, FIXTURE_MTIME); + yield* TestClock.setTime((FIXTURE_MTIME + 60) * 1000); return { root, env: { @@ -581,19 +587,15 @@ describe("probeRemoteEditors PATH scan", () => { }; }); - const countingFileSystem = (counter: { stat: number; reads: Map }) => + const countingFileSystem = (reads: Map) => Layer.effect( FileSystem.FileSystem, Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; return FileSystem.FileSystem.of({ ...fs, - stat: (target) => { - counter.stat += 1; - return fs.stat(target); - }, readDirectory: (target, options) => { - counter.reads.set(target, (counter.reads.get(target) ?? 0) + 1); + reads.set(target, (reads.get(target) ?? 0) + 1); return fs.readDirectory(target, options); }, }); @@ -612,44 +614,38 @@ describe("probeRemoteEditors PATH scan", () => { return available; }); - it.effect("reads each PATH directory once instead of stat-ing every candidate per editor", () => + it.effect("finds the editors a serial scan finds, listing each PATH directory at most once", () => Effect.gen(function* () { const { env: baseEnv } = yield* makeFakePath(); const delimiter = platform === "win32" ? ";" : ":"; - const uncachedCounter = { stat: 0, reads: new Map() }; - const cachedCounter = { stat: 0, reads: new Map() }; - const uncachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; - const cachedEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; - const uncached = yield* serialReference(uncachedEnv).pipe( - Effect.provide(countingFileSystem(uncachedCounter)), + const reads = new Map(); + // Distinct PATH values keep one scan from answering the other out of the resolution cache. + const serialEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x1` }; + const probeEnv = { ...baseEnv, PATH: `${baseEnv.PATH}${delimiter}${baseEnv.HOME}x2` }; + const serial = yield* serialReference(serialEnv).pipe( + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ); - const cached = yield* probeRemoteEditors + const probed = yield* probeRemoteEditors .handler(undefined) .pipe( - Effect.provideService(HostProcess.Environment, cachedEnv), + Effect.provideService(HostProcess.Environment, probeEnv), Effect.provideService(HostProcess.Platform, platform), - Effect.provide(countingFileSystem(cachedCounter)), + Effect.provide(countingFileSystem(reads)), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ); // The host can add editors from app folders the fixture can't redirect (e.g. /Applications). const fixtureEditors = ["cursor", "vscode", "zed", "webstorm"]; assert.deepStrictEqual( - uncached.filter((id) => fixtureEditors.includes(id)), + serial.filter((id) => fixtureEditors.includes(id)), fixtureEditors, ); - assert.deepStrictEqual(cached, uncached); - assert.isAbove(uncachedCounter.stat, 0); - // On every platform the probe lists each PATH directory at most once. Only PATH entries count: - // resolveEditorCommand also reads app folders such as /Applications on macOS. - const pathReads = cachedEnv.PATH.split(delimiter) + assert.deepStrictEqual(probed, serial); + // Only PATH entries count: resolveEditorCommand also reads app folders such as /Applications + // on macOS. PATH directories are listed on Windows only, once even for concurrent probes. + const pathReads = probeEnv.PATH.split(delimiter) .filter((entry) => entry.length > 0) - .map((entry) => cachedCounter.reads.get(entry) ?? 0); - assert.isAbove(Math.max(...pathReads), 0); - assert.isAtMost(Math.max(...pathReads), 1); - // Without the listings, Windows stats every PATH entry x PATHEXT candidate for each editor; - // elsewhere there is no PATHEXT, so the stat count is about the same either way. - if (platform === "win32") { - assert.isBelow(cachedCounter.stat, uncachedCounter.stat / 2); - } + .map((entry) => reads.get(entry) ?? 0); + assert.strictEqual(Math.max(...pathReads), platform === "win32" ? 1 : 0); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); }); diff --git a/apps/desktop/src/ipc/methods/window.ts b/apps/desktop/src/ipc/methods/window.ts index abf4ec929a7b7..c6ad0bef18c81 100644 --- a/apps/desktop/src/ipc/methods/window.ts +++ b/apps/desktop/src/ipc/methods/window.ts @@ -17,7 +17,6 @@ import { } from "@t3tools/contracts"; import { PROJECT_FAVICON_EXTENSIONS } from "@t3tools/shared/projectFavicon"; import { resolveEditorCommand } from "@t3tools/shared/editor"; -import { withPathDirectoryListings } from "@t3tools/shared/shell"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { isRelayTracingEnabled } from "@t3tools/shared/otelEnvironment"; import * as FileSystem from "effect/FileSystem"; @@ -446,7 +445,6 @@ export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ result: Schema.Array(EditorId), handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () { const env = yield* HostProcess.Environment; - // Shared listings stop each editor re-stating every PATH entry x PATHEXT candidate on Windows. const resolved = yield* Effect.forEach( REMOTE_CAPABLE_EDITOR_IDS, (editorId) => { @@ -456,7 +454,7 @@ export const probeRemoteEditors = DesktopIpc.makeIpcMethod({ : Effect.succeed(false); }, { concurrency: REMOTE_EDITOR_PROBE_CONCURRENCY }, - ).pipe(withPathDirectoryListings); + ); return REMOTE_CAPABLE_EDITOR_IDS.filter((_, index) => resolved[index]); }), }); 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-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/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/ProviderIcon.tsx b/apps/mobile/src/components/ProviderIcon.tsx index 62a64102265de..f4bdf2f388ba6 100644 --- a/apps/mobile/src/components/ProviderIcon.tsx +++ b/apps/mobile/src/components/ProviderIcon.tsx @@ -197,7 +197,8 @@ export function ProviderInstanceIcon(props: { borderRadius: 999, borderWidth: 1, ...(props.surfaceColor ? { borderColor: props.surfaceColor } : {}), - backgroundColor: accentColor, + // An undefined inline key still overrides the className color when styles merge. + ...(accentColor ? { backgroundColor: accentColor } : {}), alignItems: "center", justifyContent: "center", }} @@ -208,7 +209,7 @@ export function ProviderInstanceIcon(props: { fontSize: 7, fontWeight: "600", lineHeight: 9, - color: accentColor ? providerAccentForegroundColor(accentColor) : undefined, + ...(accentColor ? { color: providerAccentForegroundColor(accentColor) } : {}), }} > {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 ab43b514ed3d9..634b7a9389e93 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -203,6 +203,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 +1129,7 @@ function ComposerPromptEditorTiptapInner( suppressTrigger, contextIds, previousSnapshot.value !== nextValue, + isHistoryTransaction(transaction), ); }; @@ -1924,12 +1927,13 @@ function ComposerPromptEditorTiptapInner(
{ if ( event.key === "Control" || @@ -1974,7 +1978,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
diff --git a/apps/web/src/components/CustomSnoozeDialog.tsx b/apps/web/src/components/CustomSnoozeDialog.tsx index 727a55f96fd23..f9c5c9423cbbf 100644 --- a/apps/web/src/components/CustomSnoozeDialog.tsx +++ b/apps/web/src/components/CustomSnoozeDialog.tsx @@ -13,6 +13,7 @@ import { CalendarIcon, Settings2Icon } from "lucide-react"; import { Calendar } from "./ui/calendar"; import { weekStartsOn } from "../timestampFormat"; import { useNowMinute } from "../hooks/useNowMinute"; +import { useFormattingLocale } from "../i18n/I18nProvider"; import { Popover, PopoverTrigger, PopoverPopup } from "./ui/popover"; import { Input } from "./ui/input"; import { Label } from "./ui/label"; @@ -65,6 +66,7 @@ export function CustomSnoozeDialogHost() { function CustomSnoozeDialog() { const gt = useGT(); + const locale = useFormattingLocale(); const id = useId(); const navigate = useNavigate(); const [initial] = useState(() => new Date(Date.now() + 3_600_000)); @@ -148,7 +150,7 @@ function CustomSnoozeDialog() { /> } > - {date.toLocaleDateString(undefined, { + {date.toLocaleDateString(locale, { month: "short", day: "numeric", year: "numeric", diff --git a/apps/web/src/components/ProjectCloneToastCoordinator.tsx b/apps/web/src/components/ProjectCloneToastCoordinator.tsx index 846644c537a12..778c195e2d29e 100644 --- a/apps/web/src/components/ProjectCloneToastCoordinator.tsx +++ b/apps/web/src/components/ProjectCloneToastCoordinator.tsx @@ -45,6 +45,8 @@ interface TrackedToast { readonly toastId: ReturnType; readonly renderedKey: string; readonly phase: ProjectCloneSnapshot["phase"]; + readonly startedAt: ProjectCloneSnapshot["startedAt"]; + readonly closed?: true; } function renderKey(clone: ProjectCloneSnapshot): string { @@ -98,6 +100,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI seen.add(clone.projectId); const key = renderKey(clone); const tracked = toasts.current.get(clone.projectId); + const sameAttempt = tracked?.startedAt === clone.startedAt; const name = projectCloneDisplayName(clone); const closeToast = () => { const current = toasts.current.get(clone.projectId); @@ -111,7 +114,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } - if (tracked?.renderedKey === key) continue; + if (sameAttempt && tracked.renderedKey === key) continue; if ( isProjectCloneToastSilenced(ref) && (clone.phase === "running" || clone.phase === "done") @@ -119,6 +122,34 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } + if ( + sameAttempt && + tracked.closed && + (tracked.phase !== "running" || clone.phase !== "failed") + ) { + continue; + } + + const showToast = (options: ReturnType) => { + const rendered = { renderedKey: key, phase: clone.phase, startedAt: clone.startedAt }; + if (tracked && !tracked.closed) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { toastId: tracked.toastId, ...rendered }); + return; + } + + const toastId = toastManager.add({ + ...options, + // Updates to a closing toast are ignored, even before it has been removed. + onClose: () => { + const current = toasts.current.get(clone.projectId); + if (current?.toastId === toastId) { + toasts.current.set(clone.projectId, { ...current, closed: true }); + } + }, + }); + toasts.current.set(clone.projectId, { toastId, ...rendered }); + }; if (clone.phase === "running") { const options = stackedThreadToast({ @@ -136,13 +167,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" }); - } + showToast(options); continue; } @@ -161,13 +186,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" }); - } + showToast(options); continue; } @@ -199,13 +218,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase }); - } + showToast(options); } for (const [projectId, tracked] of toasts.current) { diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index af006833c8134..a17427fcdb54e 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -7,6 +7,8 @@ import { describe, expect, it } from "vite-plus/test"; import * as Cause from "effect/Cause"; import { AsyncResult } from "effect/reactivity"; import { + ADD_PROJECT_SCOPE_ITEM_VALUE, + filterSidebarProjectScopeItems, shouldCreateNewThreadInCurrentProject, resolveScopedNewThreadProjectRef, deleteSelectedThreadEntries, @@ -1811,3 +1813,22 @@ describe("resolveScopedNewThreadProjectRef", () => { ).toBeNull(); }); }); + +describe("filterSidebarProjectScopeItems", () => { + it("hides Add project and All projects while searching", () => { + const items = [ + { value: ADD_PROJECT_SCOPE_ITEM_VALUE, label: "Add project" }, + { value: "all", label: "All projects" }, + { value: "p1", label: "project" }, + ]; + const filter = (query: string) => + filterSidebarProjectScopeItems({ + items, + query, + matches: (item, q) => item.label.includes(q), + }).map((item) => item.value); + + expect(filter("")).toEqual([ADD_PROJECT_SCOPE_ITEM_VALUE, "all", "p1"]); + expect(filter("project")).toEqual(["p1"]); + }); +}); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 49109eb4ac2b0..0771ea2e33d5d 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -1183,6 +1183,8 @@ export function pullRequestMatchesSearchQuery( return normalizedQuery.split(" ").every((token) => haystack.includes(token)); } +export const ADD_PROJECT_SCOPE_ITEM_VALUE = "add-project"; + export function filterSidebarProjectScopeItems(input: { items: readonly TItem[]; query: string; @@ -1190,7 +1192,12 @@ export function filterSidebarProjectScopeItems item.value !== "all" && input.matches(item, query)); + return input.items.filter( + (item) => + item.value !== "all" && + item.value !== ADD_PROJECT_SCOPE_ITEM_VALUE && + input.matches(item, query), + ); } interface SidebarProjectScopeMenuState { diff --git a/apps/web/src/components/Sidebar.motion.browser.test.ts b/apps/web/src/components/Sidebar.motion.browser.test.ts new file mode 100644 index 0000000000000..2eae3d4f83fb9 --- /dev/null +++ b/apps/web/src/components/Sidebar.motion.browser.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vite-plus/test"; +import { render } from "../../test/render"; +import { createSidebarListMotion } from "./Sidebar.motion"; + +describe("sidebar list motion", () => { + it("slides rows above a removal at the bottom instead of jumping with the scroll clamp", async () => { + await using screen = await render(null); + const viewport = document.createElement("div"); + viewport.dataset.slot = "scroll-area-viewport"; + viewport.style.cssText = "height: 200px; overflow-y: auto; overflow-anchor: none"; + const list = document.createElement("ul"); + list.style.cssText = "position: relative; margin: 0; padding: 0; list-style: none"; + const rows = Array.from({ length: 10 }, () => { + const row = document.createElement("li"); + row.style.height = "64px"; + list.append(row); + return row; + }); + viewport.append(list); + screen.container.append(viewport); + const motion = createSidebarListMotion(list); + using _motion = { [Symbol.dispose]: () => motion.dispose() }; + motion.update(false); + viewport.scrollTop = viewport.scrollHeight; + viewport.dispatchEvent(new Event("scroll")); + const above = rows[7]!; + const before = above.getBoundingClientRect().top; + + rows[8]!.remove(); + motion.update(true); + for (const animation of above.getAnimations()) animation.pause(); + + expect(above.getBoundingClientRect().top).toBe(before); + }); +}); diff --git a/apps/web/src/components/Sidebar.motion.ts b/apps/web/src/components/Sidebar.motion.ts index 0e86c3c9a0e94..da0e7de3201b2 100644 --- a/apps/web/src/components/Sidebar.motion.ts +++ b/apps/web/src/components/Sidebar.motion.ts @@ -22,6 +22,12 @@ export function createSidebarListMotion(parent: HTMLUListElement) { const entering = new Map(); const exiting = new Map(); let released: Map | null = null; + const scroller = parent.closest('[data-slot="scroll-area-viewport"]'); + let scrollTop = scroller?.scrollTop ?? 0; + const trackScroll = () => { + scrollTop = scroller?.scrollTop ?? 0; + }; + scroller?.addEventListener("scroll", trackScroll, { passive: true }); const remainingOffset = (node: HTMLElement) => { const current = running.get(node); @@ -37,7 +43,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { entering.clear(); exiting.clear(); }; - const fadeOut = (node: HTMLElement, position: RowPosition, travel: number) => { + const fadeOut = (node: HTMLElement, position: RowPosition, travel: number, shift: number) => { if (position.height === 0) return; const clone = node.cloneNode(true) as HTMLElement; for (const element of [clone, ...clone.querySelectorAll("*")]) { @@ -56,7 +62,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { clone.inert = true; Object.assign(clone.style, { position: "absolute", - top: `${position.top + remainingOffset(node)}px`, + top: `${position.top + remainingOffset(node) + shift}px`, left: `${position.left}px`, width: `${position.width}px`, height: `${position.height}px`, @@ -153,6 +159,14 @@ export function createSidebarListMotion(parent: HTMLUListElement) { positions !== null && !reducedMotion?.matches && fadeCount <= MAX_FADED_ROWS_PER_UPDATE; + // A removal near the bottom shrinks the list and the browser clamps scrollTop, moving + // every row on screen; offsets include that shift so those rows slide instead of jump. + let shift = 0; + if (scroller !== null) { + const max = scroller.scrollHeight - scroller.clientHeight; + if (scrollTop > max && scroller.scrollTop >= max - 1) + shift = scroller.scrollTop - scrollTop; + } const movedDelta = new Map(); const nextOrder = [...next.keys()]; const oldOrder = positions === null ? [] : [...positions.keys()]; @@ -173,13 +187,13 @@ export function createSidebarListMotion(parent: HTMLUListElement) { else { for (const [node, position] of next) { const previousTop = positions!.get(node)?.top; - if (previousTop === undefined || previousTop === position.top) continue; - movedDelta.set(node, previousTop + remainingOffset(node) - position.top); + if (previousTop === undefined || previousTop + shift === position.top) continue; + movedDelta.set(node, previousTop + remainingOffset(node) - position.top + shift); } for (const [node, position] of positions!) { if (next.has(node)) continue; const delta = ridingDelta(oldOrder, oldOrder.indexOf(node), (n) => next.has(n)); - fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta); + fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta, shift); } } for (const [node, entry] of entering) { @@ -233,6 +247,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { released = null; } positions = next; + if (scroller !== null) scrollTop = scroller.scrollTop; }, release() { suspend(); @@ -246,6 +261,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { suspend, dispose() { suspend(); + scroller?.removeEventListener("scroll", trackScroll); disposed = true; }, }; diff --git a/apps/web/src/components/Sidebar.snooze.ts b/apps/web/src/components/Sidebar.snooze.ts index 34cdc0077cd3d..abe2e3934659d 100644 --- a/apps/web/src/components/Sidebar.snooze.ts +++ b/apps/web/src/components/Sidebar.snooze.ts @@ -9,6 +9,7 @@ import { } from "@t3tools/client-runtime/state/thread-settled"; import { m, type MessageResolver } from "../i18n/messages"; +import { getFormattingLocale } from "../i18n/runtime"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { serverEnvironment } from "../state/server"; import { formatShortTimestamp } from "../timestampFormat"; @@ -52,11 +53,13 @@ export function pickSnoozePreset( } function snoozeOptions(timestampFormat: TimestampFormat, environmentId: EnvironmentId) { + const locale = getFormattingLocale(); const presets = appAtomRegistry.get( serverEnvironment.settingsValueAtom(environmentId), )?.snoozePresets; return { ...(presets ? { presets } : {}), - formatTime: (date: Date) => formatShortTimestamp(date.toISOString(), timestampFormat), + formatTime: (date: Date) => formatShortTimestamp(date.toISOString(), timestampFormat, locale), + locale, }; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 45e00246e2c6d..e9d45a5c1fd84 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -72,7 +72,7 @@ import { CheckIcon, ChevronDownIcon, FolderIcon, - ListFilterIcon, + FolderPlusIcon, PlusIcon, SettingsIcon, } from "lucide-react"; @@ -171,7 +171,6 @@ import { resolveThreadRouteTarget, } from "../threadRoutes"; import type { SidebarThreadSummary } from "../types"; -import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { cn } from "~/lib/utils"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; import { ProjectRowActions } from "./ProjectComboboxRow"; @@ -188,6 +187,7 @@ import { buildBulkTitleRegenerationContextMenuItem, buildBulkUnpinContextMenuItem, deleteSelectedThreadEntries, + ADD_PROJECT_SCOPE_ITEM_VALUE, filterSidebarProjectScopeItems, firstValidTimestampMs, isSidebarNestedLinkClick, @@ -272,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, @@ -431,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. @@ -445,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; @@ -513,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); } @@ -525,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); @@ -836,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, @@ -1161,20 +1170,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve setPersistedProjectScopeKeys([]); }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]); const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace); + const [departingThreadKey, setDepartingThreadKey] = useState(null); + if (departingThreadKey !== null && departingThreadKey !== routeThreadKey) { + setDepartingThreadKey(null); + } + const departRouteThread = (threadKey: string) => setDepartingThreadKey(threadKey); + const stayOnRouteThread = (threadKey: string) => + setDepartingThreadKey((current) => (current === threadKey ? null : current)); const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups); - const scratchMachineLabelFor = ( - thread: Pick, - ) => { - if (!showProjectEnvironments) return null; - const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`); - if ( - !project || - !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot) - ) { - return null; - } - return environmentLabelById.get(thread.environmentId) ?? null; - }; // Pinning from a row keeps rows in place while the menu is open. const projectScopeItems = useOrderWhileOpen( lookupProjectScopeItems, @@ -1185,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, @@ -1203,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 ( @@ -1354,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. @@ -1443,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; @@ -1640,9 +1652,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( @@ -1665,6 +1679,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSettle?.(); + } else { + stayOnRouteThread(threadKey); } })(); }; @@ -2198,6 +2214,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), ); @@ -2212,6 +2229,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) navigateAfterSettle?.(); + else stayOnRouteThread(activeKey); return; } case "move-active": @@ -2267,9 +2285,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); @@ -2284,6 +2304,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSnooze?.(); + } else { + stayOnRouteThread(threadKey); } return { status: "success" } as const; }; @@ -3061,7 +3083,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 && @@ -3080,12 +3105,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") } /> } @@ -3110,7 +3135,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve ) : ( - + )} {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} @@ -3172,6 +3197,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) @@ -3247,7 +3282,6 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } - onNewProject={openAddProjectCommandPalette} onNewThread={handleNewThreadClick} newThreadDisabled={projects.length === 0} newThreadShortcutLabel={newThreadShortcutLabel} @@ -3523,14 +3557,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve jumpLabel={ showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null } - currentEnvironmentId={primaryEnvironmentId} environmentLabel={ environmentLabelById.get(thread.environmentId) ?? null } environmentMachine={ environmentMachineById.get(thread.environmentId) ?? "server" } - scratchMachineLabel={scratchMachineLabelFor(thread)} project={ projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null @@ -3571,6 +3603,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve key="draft-sessions" draftIds={draftIds} routeDraftComposer={routeDraftComposer} + terminalLabels={draftTerminalLabels} jumpLabelByDraftId={draftJumpLabelById} projectByKey={projectByKey} projectDisplayNameByKey={projectDisplayNameByKey} diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 9c5e7fa3d830d..905d9cb2131fe 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -19,7 +19,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; import { msg, T, useGT, useMessages } from "gt-react"; -import { FolderGit2Icon, TerminalIcon } from "lucide-react"; +import { TerminalIcon } from "lucide-react"; import { m, type MessageResolver } from "../i18n/messages"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; @@ -53,7 +53,6 @@ import { } from "./Sidebar.logic"; import type { SidebarThreadSummary } from "../types"; -import { formatWorktreePathForDisplay } from "../worktreeCleanup"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { PULL_REQUEST_STATE_PRESENTATION, @@ -770,41 +769,6 @@ export function ThreadTerminalStatusButton({ ); } -export function ThreadWorktreeIndicator({ - thread, -}: { - thread: Pick; -}) { - const gt = useGT(); - const worktreePath = thread.worktreePath?.trim(); - if (!worktreePath) { - return null; - } - - const displayPath = formatWorktreePathForDisplay(worktreePath); - const tooltip = thread.branch - ? gt("Worktree: {path} ({branch})", { path: displayPath, branch: thread.branch }) - : gt("Worktree: {path}", { path: displayPath }); - - return ( - - - } - > - - - {tooltip} - - ); -} - function ThreadStatusLabel({ status, compact = false, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 2c3bc34529ffd..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,6 +135,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -212,6 +216,7 @@ import { } from "./ComposerCommandMenu"; import { ComposerAttachButton, + ComposerAttachInput, ComposerAttachmentFileList, ComposerAttachmentMediaRow, ComposerFilePreviewDialog, @@ -251,6 +256,7 @@ import { useNavigate } from "@tanstack/react-router"; import { assistantCitationLabel } from "@t3tools/shared/assistantCitations"; import { assistantCitationNavigation } from "../../lib/assistantCitationNavigation"; import { Button } from "../ui/button"; +import { Spinner } from "../ui/spinner"; import { useManagedPolicy } from "../../state/managedPolicy"; import { hasProviderSetup } from "./ProviderStatusBanner"; import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; @@ -284,11 +290,15 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; import { + cancelHeldComposerSend, countPreparingComposerImages, + useComposerSendHeld, usePreparingComposerImages, useSubmitAfterPreparingImages, } from "./preparingComposerImages"; +import { HELD_COMPOSER_SEND_BANNER_ID } from "./ComposerHeldSendBanner"; import { ComposerControlsBar } from "./ComposerControlsBar"; import { composerCommandKeyHandler } from "./composerCommandKey"; import { promptSuggestionToAccept, usePromptSuggestion } from "./usePromptSuggestion"; @@ -451,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: ( @@ -593,7 +606,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onExpandImage, onFileOpen, editingQueuedAttachments, + removedEditingQueuedAttachments, onRemoveEditingQueuedAttachment, + onRestoreEditingQueuedAttachment, } = props; const { activePendingProgress: incomingPendingProgress, @@ -651,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 = @@ -728,8 +749,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) uncommittedSnapShotIds, standaloneComposerImages, } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); - const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( - (image) => !image.hidden, + const allPreparingComposerImages = usePreparingComposerImages(attachmentTargetKey); + const preparingComposerImages = allPreparingComposerImages.filter((image) => !image.hidden); + // A message send waits for these itself; an answer waits in the composer below. + const messageHasPreparingImages = + questionAttachmentTarget === null && allPreparingComposerImages.length > 0; + const composerSendHeld = useComposerSendHeld(composerDraftTargetKey); + const cancelHeldSend = () => cancelHeldComposerSend(composerDraftTargetKey); + const handleMultipleModelSelectionsChangeStable = useStableCallback( + (next: React.SetStateAction | null>) => { + cancelHeldSend(); + setMultipleModelSelections(next); + }, ); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); @@ -741,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) => { @@ -782,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; @@ -1065,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); @@ -1266,21 +1322,28 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isComplete: Boolean(activePendingResolvedAnswers), } : null; + const hasMessageToSend = composerSendState.hasSendableContent || messageHasPreparingImages; const showResumeAction = - canResume && !composerDraftHasUserContent(composerDraft) && !isEditingQueuedMessage; + canResume && + !composerDraftHasUserContent(composerDraft) && + !messageHasPreparingImages && + !isEditingQueuedMessage; const collapsedComposerPrimaryActionDisabled = phase === "running" || isSendBusy || + composerSendHeld || isSendDisabled || noProviderAvailable || projectSelectionRequired || environmentUnavailable !== null || - (!composerSendState.hasSendableContent && !showResumeAction); - const collapsedComposerPrimaryActionLabel = showResumeAction - ? gt("Resume thread") - : props.resumeCompactionTokens !== null && !props.keepFullHistory - ? gt("Open composer to compact and send") - : gt("Send message"); + (!hasMessageToSend && !showResumeAction); + const collapsedComposerPrimaryActionLabel = composerSendHeld + ? gt("Sending when ready") + : showResumeAction + ? gt("Resume thread") + : props.resumeCompactionTokens !== null && !props.keepFullHistory + ? gt("Open composer to compact and send") + : gt("Send message"); const showMobilePendingAnswerActions = isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null; @@ -1370,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({ @@ -1424,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 @@ -1629,6 +1702,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], textChanged: boolean, + fromHistory = false, ) => { refreshWorkspaceSnapshotOnTyping(); const trigger = cursorAdjacentToMention @@ -1739,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, @@ -1758,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); }; @@ -2195,7 +2283,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (activePendingProgress) { return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); } - return composerSendState.hasSendableContent; + return hasMessageToSend; }; const submitComposerRef = useRef< @@ -2281,9 +2369,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) event?.preventDefault(); return false; } - // Sending now would leave a still-compressing image out of the turn, so wait for it. + if (composerSendHeld) { + event?.preventDefault(); + return false; + } + // Sending now would leave a still-compressing image out of the answer, so wait for it. if ( activeThreadId && + questionAttachmentTarget && submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) ) { event?.preventDefault(); @@ -2466,8 +2559,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) ? promptSuggestion : null; - const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => - composerCommandKeyHandler({ + const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => { + if (key === "Escape" && composerSendHeld && !event.isComposing) { + cancelHeldSend(); + return true; + } + return composerCommandKeyHandler({ keybindings, getShortcutContext, sendShortcut: settings.sendShortcut, @@ -2506,6 +2603,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptSuggestion: offeredPromptSuggestion, dismissPromptSuggestion, })(key, event, isTaskItem); + }; const { stashQueue, @@ -2614,7 +2712,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isSendBusy={isSendBusy} multipleModelsEnabled={routeKind === "draft" && supportsMultipleModels} multipleModelSelections={multipleModelSelections} - onMultipleModelSelectionsChange={setMultipleModelSelections} + onMultipleModelSelectionsChange={handleMultipleModelSelectionsChangeStable} selectedModelSelection={selectedModelSelection} onProviderModelSelect={onProviderModelSelect} activeThreadModelSelection={activeThreadModelSelection} @@ -2712,7 +2810,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const shelfItems = hasBlockingComposerTopDrawer ? bannerItems.filter( (item) => - item.group === "environment" && (item.variant === "error" || item.variant === "warning"), + item.id === HELD_COMPOSER_SEND_BANNER_ID || + (item.group === "environment" && + (item.variant === "error" || item.variant === "warning")), ) : bannerItems; @@ -2913,12 +3013,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const pastedContext = !isLiteralPendingAnswer && (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; + const canAttachFiles = !pastedContext && activeThreadId !== null && files.length > 0; + const htmlImageContent = + canAttachFiles && plainText.length > 0 + ? clipboardHtmlImageContent(event.clipboardData.getData("text/html")) + : "none"; if ( folders.length > 0 || - (!pastedContext && - activeThreadId && - files.length > 0 && - shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment })) + (canAttachFiles && + shouldHandleComposerAttachmentPaste({ + files, + plainText, + bypassAutoAttachment, + htmlIsOnlyImage: htmlImageContent === "only-image", + })) ) { event.preventDefault(); event.stopPropagation(); @@ -2930,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; } @@ -3501,15 +3616,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) /> ) : null; const composerAttachButton = showComposerAttachAction ? ( - + composerAttachInputRef.current?.click()} /> ) : null; return (
{ + if ( + event.key === "Escape" && + composerSendHeld && + !event.defaultPrevented && + !event.nativeEvent.isComposing + ) { + event.preventDefault(); + cancelHeldSend(); + } + }} onFocusCapture={(event) => { const activeElement = event.target; if ( @@ -3594,6 +3717,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onToggleMenu={toggleStashMenuStable} /> + {showComposerAttachAction ? ( + + ) : null}
@@ -3654,6 +3784,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-64" disabled={collapsedComposerPrimaryActionDisabled} aria-label={collapsedComposerPrimaryActionLabel} + aria-busy={composerSendHeld || isSendBusy || undefined} onPointerDown={(event) => event.preventDefault()} onClick={(event) => { event.stopPropagation(); @@ -3663,7 +3794,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) else submitComposer(); }} > - {showResumeAction ? ( + {composerSendHeld || isSendBusy ? ( +
- + {selectedEnvironments.length === 0 ? (

diff --git a/apps/web/src/composer-editor-mentions.ts b/apps/web/src/composer-editor-mentions.ts index 7f3e93b821488..6608d3b2a0439 100644 --- a/apps/web/src/composer-editor-mentions.ts +++ b/apps/web/src/composer-editor-mentions.ts @@ -7,6 +7,7 @@ import { composerMathRanges, type ComposerInlineToken, } from "@t3tools/shared/composerInlineTokens"; +import { markdownMathRanges } from "~/markdown/wordsHast"; export type ComposerPromptSegment = | { @@ -89,7 +90,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray !taken.some((range) => mention.start < range.end && mention.end > range.start), @@ -98,7 +99,7 @@ function collectModelTokens(text: string, inlineTokens: ReadonlyArray = []; for (const formula of formulas) { diff --git a/apps/web/src/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 c7095b8536469..ecdb3d4220e67 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installiere {fj} 0.6 oder neuer von {fjUrl} und führe {fjLogin} aus, oder installiere {tea} 0.16 oder neuer von {teaUrl} und führe {teaLogin} für jeden Forgejo- oder Gitea-Server aus.", "d026a85e2e50e675": "Installiere die GitCafe CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", "22d3c0c48a34b5b3": "Installiere die TanStack Source CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", + "756c80ad262ef315": "Wartet im ursprünglichen Thread", + "d8df14f9905f38eb": "Gesendet", + "e7c59185f8ab3987": "Nicht gesendet", + "b54ddec9084fa955": "Ohne Senden geschlossen", + "fbaa7ab5da716e50": "Fehler", + "01bac997ea55272e": "Unverständlich", + "0f53bc8f74dfe56a": "Fehlende Funktion", + "055560f307e15e30": "Falsche Dokumentation", + "78344b60f407928e": "Sonstiges", + "f653846a95cd6e8f": "Art", + "f41ea186c275b56e": "Info", + "2f6e4f7cd364da73": "Erwartet", + "9d11c93d4035de3e": "Tatsächlich passiert", + "c87d0595693704f9": "Stattdessen getan", + "d7a4ea6ce5af44e0": "{speaker} · {count} Zeichen", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Runde {turn} · {what}", + "dfdaa6255a416140": "Übersicht über {turns, plural, one {{turns} letzte Runde} other {{turns} letzte Runden}}, {textTurns, plural, =0 {ohne Nachrichtentext} one {mit dem Nachrichtentext der letzten Runde} other {mit den Nachrichtentexten der letzten {textTurns} Runden}}{truncated, select, yes {, passend gekürzt} other {}}", + "afac52a5cc2dc801": "Deine Antwort konnte nicht gesendet werden. Versuche es erneut.", "79d776428f4d0650": "Die Datei konnte nicht geladen werden. Verbinde dich erneut und versuch es noch einmal.", "3ea34cbb1ca5ba9b": "Vorschau abgebrochen.", "7c0af279ecb3da3a": "Streamende Dateivorschauen sind in dieser Laufzeitumgebung nicht verfügbar.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} an", "77cc5f738cb7d459": "{label} aus", - "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", "aba3bb73ce212f0c": "{names} erfordert {providerName} {version} oder neuer, aber der Homebrew-Cask claude-code hat nur {latestVersion}. Wechsle zum Cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", "d887bea446534de5": "Kein Projekt in dieser Umgebung kann {host}/{repository} lesen.", "4e466d60e2f7736b": "Füge die vollständige Pull-Request-URL ein. Dieser Thread hat kein Repository, in dem die Nummer aufgelöst werden kann.", "302625058bacbe38": "Füge eine vollständige URL ein. Für den Host dieses Projekts ist kein {changeRequest}-URL-Format bekannt.", @@ -637,6 +657,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", @@ -2497,8 +2520,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}", @@ -2561,10 +2583,9 @@ }, " installieren" ], + "b4b98a0287c282e2": "Auf einem anderen Rechner, daher kann der Agent dieses Rechners es nicht lesen. Entferne es oder wechsle zum Senden zurück.", "5bbac0e5afeec779": "Aktueller Thread", "33c7e68fca089036": "Thread, {title}", - "b4b98a0287c282e2": "Auf einem anderen Rechner, daher kann der Agent dieses Rechners es nicht lesen. Entferne es oder wechsle zum Senden zurück.", - "c6196d99000642b4": "Thread öffnen", "34cc63390ad793cc": "Thread wählen", "8f12309ead62e38a": "Threads oder Projekte durchsuchen...", "2f664754d005d9a7": "Keine aktiven Threads gefunden.", @@ -2574,6 +2595,7 @@ "a3178769f8308cbc": "Thread fehlgeschlagen", "89b5e8f3887812da": "Gastanfrage", "62e626804919b294": "Eingabe nötig", + "c6196d99000642b4": "Thread öffnen", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", @@ -2597,8 +2619,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminal-Prozess läuft", "fc2c9a91f498ad6b": "{count, plural, one {{count} Terminal-Prozess läuft. Terminal öffnen} other {{count} Terminal-Prozesse laufen. Terminal öffnen}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "Stack", "6831e9a46cbd8939": "Kette", "9aa9e74a3b7eee91": "Zum Chat hinzufügen", @@ -3035,8 +3055,8 @@ "6f85f14f35b3f547": "{provider} über {environment}", "7c59a888a062a8bd": "Die Spracheingabe hat keinen Entwurf, in den sie aufnehmen kann.", "62450481c00d2ef3": "Die Umgebung des Entwurfs ist für die Transkriptbereinigung nicht verfügbar.", - "c64cb58d9cecbcd2": "Transkriptbereinigung fehlgeschlagen", "0674544195fcdc39": "Das ursprüngliche Transkript wurde eingefügt.", + "c64cb58d9cecbcd2": "Transkriptbereinigung fehlgeschlagen", "296496693cdac0db": "Der t3-Befehl ist nicht verfügbar.", "efbcef7bc9bbda01": "Der Status des t3-Befehls konnte nicht geladen werden.", "1bf6910332426e62": "Netzwerkzugriff des Desktops ist nicht verfügbar.", @@ -3279,6 +3299,7 @@ "4d493d0bda4d403d": "Hänge die unterbrochene Datei erneut an oder entferne sie", "c9cad1d84d5f1a32": "Hänge die unterbrochenen Dateien erneut an oder entferne sie", "536a820f2ff726da": "Wähle mindestens ein Modell.", + "48d6389202ad6754": "Wird gesendet, sobald bereit", "fbafbe78b5e37966": "Thread fortsetzen", "bcd7eb979dd38dae": "Eingabefeld öffnen, um zu komprimieren und zu senden", "95ee62a0d6968b89": "Nachricht senden", @@ -3455,6 +3476,9 @@ "e778e4f446fdf873": "Deine nächste Nachricht startet eine neue Sitzung", "0e2f2da4f2d94785": "Der Agent sieht frühere Nachrichten in diesem Thread nicht.", "e1189d2e582b008d": "Aktuelle Sitzung behalten", + "2bb448d605877a22": "Zum Abbrechen bearbeiten oder Esc drücken", + "1a1f128d70c62304": "{count, plural, one {Wird gesendet, sobald das Bild bereit ist} other {Wird gesendet, sobald {count} Bilder bereit sind}}", + "5af3ab719a9725fb": "Nachricht wird gesendet", "461c9f865f2e9b92": "{option} an", "f2aa17b5c620f2a4": "{option} aus", "f59314a884aae1ff": "Standard", @@ -3578,6 +3602,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.", @@ -3598,7 +3630,6 @@ "abd89e9eefedf11b": "Fertig", "18d166056c1ab6ff": "Freigabe beenden", "7a2d510eac9e4587": "Gastlink abgelaufen", - "653405e4ed498d9f": "Senden", "21888e302219891d": "Vergrößerte Vorschau von {title}", "419719298a7acaea": "Verkleinern", "ed8d5db95359cff4": "Zoom zurücksetzen", @@ -3694,7 +3725,6 @@ "7c1923203049d602": "Code kopieren", "637817e4ff79c90e": "Aktionen für Codeblock", "ebf3a2b1e314aa5f": "Im Terminal ausführen", - "fe219642547fa0bf": "Im Terminal ausführen", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Vollständiger Pfad", "f37e7d36b51c5b28": "Relativen Pfad kopieren", @@ -3706,10 +3736,6 @@ "4967584e8d0fb1c2": "Medienvorschau", "67589dd912eacb7c": "Im integrierten Browser öffnen", "a3c98d4c4b24cecb": "Dateioptionen für {label}", - "b4fe8a076e9fd2f8": "Abgesetzte Formel", - "085d1407e8c92cce": "Formel im Text", - "a2ef393fa7b48ae8": "Abgesetzte Formel scrollen", - "e94685ea5642e088": "Formel im Text scrollen", "3a04583c8500e23d": "Diagramm anzeigen", "16d64f650840fe06": "Code anzeigen", "6d329f7d3a50c7e7": "Tabelle kopieren", @@ -3988,9 +4014,11 @@ "973e99fa86d7f531": "Eingereihte Nachricht {position} von {total}, nicht gesendet", "0f6087c4f53c7f17": "Eine Runde mit dieser Nachricht starten ({shortcut})", "adab89933af02669": "Komprimierung überspringen und diese Nachricht senden ({shortcut})", + "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", "3de4016452e8d2bd": "In die aktuelle Runde senden ({shortcut})", "259cc9568148e8ad": "Eine Runde mit dieser Nachricht starten", "bb7fddb812d5d29e": "Komprimierung überspringen und diese Nachricht senden", + "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben", "a5fe1ee609b29a9f": "In die aktuelle Runde senden", "2b7fd345e4f4fd6e": "Bearbeiten der eingereihten Nachricht abbrechen", "47f1726bf106d2c8": "Eingereihte Nachricht bearbeiten", @@ -5600,7 +5628,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 +5637,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 +5645,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 +5831,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 +8855,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)", @@ -8843,6 +8874,9 @@ "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 +8960,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 +9191,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 +10165,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 +11066,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 +11762,6 @@ "4c70e3e7b3e6c493": "Geheimnisse", "79b768229c9ef672": "Wartung", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Info", "af4b7734da1d5ce7": "Spracheingabe", "4ec62c39ca3192bf": "Versionskontrolle & Issues", "f2bf529f85e05494": "Freigabe & Zugriff", @@ -11855,6 +11887,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", @@ -12324,7 +12357,6 @@ "0bd41ff995d36a66": "Cache-Lesen", "3f0dfe0cb15a3272": "Cache-Schreiben", "1c9d860be42b1c02": "Ausgabe", - "78344b60f407928e": "Sonstiges", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Schnell", "66796576034c18ea": "Ultraschnell", @@ -12459,6 +12491,8 @@ "faa3bb26abb39c93": "Review-Leitfaden fehlgeschlagen", "b7df38b7d8792d78": "Leitfaden öffnen", "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", - "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", - "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben" + "99d51127f573296b": "Weiteres Konto", + "8ec2c57414669b79": "Verbinde einen zweiten {tracker}-Workspace oder -Nutzer.", + "99963c0142e17f00": "Für das neue {tracker}-Konto.", + "6d8e4ebc889bace9": "Konto hinzufügen" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 2ff8148bb7329..0cc2d503fd620 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Install {fj} 0.6 or later from {fjUrl} and run {fjLogin}, or install {tea} 0.16 or later from {teaUrl} and run {teaLogin} for each Forgejo or Gitea server.", "d026a85e2e50e675": "Install the GitCafe CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", "22d3c0c48a34b5b3": "Install the TanStack Source CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", + "756c80ad262ef315": "Waiting in the original thread", + "d8df14f9905f38eb": "Sent", + "e7c59185f8ab3987": "Not sent", + "b54ddec9084fa955": "Closed without sending", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confusing", + "0f53bc8f74dfe56a": "Missing capability", + "055560f307e15e30": "Wrong docs", + "78344b60f407928e": "Other", + "f653846a95cd6e8f": "Kind", + "f41ea186c275b56e": "About", + "2f6e4f7cd364da73": "Expected", + "9d11c93d4035de3e": "Happened", + "c87d0595693704f9": "Did instead", + "d7a4ea6ce5af44e0": "{speaker} · {count} characters", + "f5114fb9c40fd929": "You", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Turn {turn} · {what}", + "dfdaa6255a416140": "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + "afac52a5cc2dc801": "Could not send your answer. Try again.", "79d776428f4d0650": "The file could not be loaded. Reconnect and try again.", "3ea34cbb1ca5ba9b": "Preview cancelled.", "7c0af279ecb3da3a": "Streaming file previews are unavailable in this runtime.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} On", "77cc5f738cb7d459": "{label} Off", - "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", "aba3bb73ce212f0c": "Using {names} requires {providerName} {version} or newer, but the claude-code Homebrew cask only has {latestVersion}. Switch to the claude-code@latest cask: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", "d887bea446534de5": "No project in this environment can read {host}/{repository}.", "4e466d60e2f7736b": "Paste the full pull request URL; this thread has no repository to resolve the number against.", "302625058bacbe38": "Paste a full URL; this project's host has no known {changeRequest} URL.", @@ -637,6 +657,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", @@ -2497,8 +2520,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}", @@ -2560,10 +2582,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "On another machine, so this machine's agent can't read it. Remove it or switch back to send.", "5bbac0e5afeec779": "Current thread", "33c7e68fca089036": "Thread, {title}", - "b4b98a0287c282e2": "On another machine, so this machine's agent can't read it. Remove it or switch back to send.", - "c6196d99000642b4": "Open thread", "34cc63390ad793cc": "Choose a thread", "8f12309ead62e38a": "Search threads or projects...", "2f664754d005d9a7": "No active threads found.", @@ -2573,6 +2594,7 @@ "a3178769f8308cbc": "Thread failed", "89b5e8f3887812da": "Guest request", "62e626804919b294": "Input needed", + "c6196d99000642b4": "Open thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "You:", "a1fbf2422c588292": "Agent:", @@ -2596,8 +2618,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminal process running", "fc2c9a91f498ad6b": "{count, plural, one {{count} terminal process running. Open terminal} other {{count} terminal processes running. Open terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "stack", "6831e9a46cbd8939": "chain", "9aa9e74a3b7eee91": "Add to chat", @@ -3034,8 +3054,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "Voice input has no draft to record into.", "62450481c00d2ef3": "The draft's environment is unavailable for transcript cleanup.", - "c64cb58d9cecbcd2": "Transcript cleanup failed", "0674544195fcdc39": "The original transcript was added.", + "c64cb58d9cecbcd2": "Transcript cleanup failed", "296496693cdac0db": "The t3 command is unavailable.", "efbcef7bc9bbda01": "Failed to load the t3 command state.", "1bf6910332426e62": "Desktop network access is unavailable.", @@ -3278,6 +3298,7 @@ "4d493d0bda4d403d": "Attach the interrupted file again or remove it", "c9cad1d84d5f1a32": "Attach the interrupted files again or remove them", "536a820f2ff726da": "Select at least one model.", + "48d6389202ad6754": "Sending when ready", "fbafbe78b5e37966": "Resume thread", "bcd7eb979dd38dae": "Open composer to compact and send", "95ee62a0d6968b89": "Send message", @@ -3454,6 +3475,9 @@ "e778e4f446fdf873": "Your next message starts a fresh session", "0e2f2da4f2d94785": "The agent won't see earlier messages in this thread.", "e1189d2e582b008d": "Keep the current session", + "2bb448d605877a22": "Edit or press Esc to cancel", + "1a1f128d70c62304": "{count, plural, one {Sending once image is ready} other {Sending once {count} images are ready}}", + "5af3ab719a9725fb": "Sending message", "461c9f865f2e9b92": "{option} On", "f2aa17b5c620f2a4": "{option} Off", "f59314a884aae1ff": "Default", @@ -3577,6 +3601,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.", @@ -3597,7 +3629,6 @@ "abd89e9eefedf11b": "Done", "18d166056c1ab6ff": "Stop sharing", "7a2d510eac9e4587": "Guest link expired", - "653405e4ed498d9f": "Send", "21888e302219891d": "Expanded {title} preview", "419719298a7acaea": "Zoom out", "ed8d5db95359cff4": "Reset zoom", @@ -3693,7 +3724,6 @@ "7c1923203049d602": "Copy code", "637817e4ff79c90e": "Code block actions", "ebf3a2b1e314aa5f": "Run in terminal", - "fe219642547fa0bf": "Run in terminal", "122a8512abc51180": "Details", "58c38c65c2783c5d": "Full path", "f37e7d36b51c5b28": "Copy relative path", @@ -3705,10 +3735,6 @@ "4967584e8d0fb1c2": "Preview media", "67589dd912eacb7c": "Open in integrated browser", "a3c98d4c4b24cecb": "File options for {label}", - "b4fe8a076e9fd2f8": "Display equation", - "085d1407e8c92cce": "Inline equation", - "a2ef393fa7b48ae8": "Scroll display equation", - "e94685ea5642e088": "Scroll inline equation", "3a04583c8500e23d": "Show diagram", "16d64f650840fe06": "Show code", "6d329f7d3a50c7e7": "Copy table", @@ -3986,9 +4012,11 @@ "973e99fa86d7f531": "Queued message {position} of {total}, not sent", "0f6087c4f53c7f17": "Start a turn with this message ({shortcut})", "adab89933af02669": "Skip compaction and send this message ({shortcut})", + "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", "3de4016452e8d2bd": "Send into the current turn ({shortcut})", "259cc9568148e8ad": "Start a turn with this message", "bb7fddb812d5d29e": "Skip compaction and send this message", + "425ab15036aec8a4": "Move this command to the front of the queue", "a5fe1ee609b29a9f": "Send into the current turn", "2b7fd345e4f4fd6e": "Cancel editing queued message", "47f1726bf106d2c8": "Edit queued message", @@ -5601,7 +5629,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 +5638,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 +5646,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 +5832,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 +8863,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)", @@ -8851,6 +8882,9 @@ "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 +8968,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 +9199,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 +10174,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 +11075,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 +11770,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "About", "af4b7734da1d5ce7": "Voice", "4ec62c39ca3192bf": "Source control & issues", "f2bf529f85e05494": "Sharing & access", @@ -11863,6 +11895,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", @@ -12332,7 +12365,6 @@ "0bd41ff995d36a66": "Cache read", "3f0dfe0cb15a3272": "Cache write", "1c9d860be42b1c02": "Output", - "78344b60f407928e": "Other", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Fast", "66796576034c18ea": "Ultrafast", @@ -12468,6 +12500,8 @@ "faa3bb26abb39c93": "Review guide failed", "b7df38b7d8792d78": "Open guide", "9e91e9a77b664e4e": "Could not start a review guide", - "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", - "425ab15036aec8a4": "Move this command to the front of the queue" + "99d51127f573296b": "Another account", + "8ec2c57414669b79": "Connect a second {tracker} workspace or user.", + "99963c0142e17f00": "For the new {tracker} account.", + "6d8e4ebc889bace9": "Add account" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 78c68c4c0dc2f..daf936020ff3a 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Instala {fj} 0.6 o posterior desde {fjUrl} y ejecuta {fjLogin}, o instala {tea} 0.16 o posterior desde {teaUrl} y ejecuta {teaLogin} para cada servidor de Forgejo o Gitea.", "d026a85e2e50e675": "Instala la CLI de GitCafe con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", "22d3c0c48a34b5b3": "Instala la CLI de TanStack Source con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", + "756c80ad262ef315": "En espera en el hilo original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "No enviado", + "b54ddec9084fa955": "Cerrado sin enviar", + "fbaa7ab5da716e50": "Error", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Función ausente", + "055560f307e15e30": "Documentación incorrecta", + "78344b60f407928e": "Otros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Acerca de", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "Lo que ocurrió", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Tú", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumen de {turns, plural, one {{turns} turno reciente} other {{turns} turnos recientes}}, {textTurns, plural, =0 {sin texto de mensajes} one {con el texto de los mensajes del último turno} other {con el texto de los mensajes de los últimos {textTurns} turnos}}{truncated, select, yes {, acortado para ajustarse} other {}}", + "afac52a5cc2dc801": "No se pudo enviar tu respuesta. Inténtalo de nuevo.", "79d776428f4d0650": "No se pudo cargar el archivo. Vuelve a conectarte e inténtalo de nuevo.", "3ea34cbb1ca5ba9b": "Vista previa cancelada.", "7c0af279ecb3da3a": "Las vistas previas de archivos en streaming no están disponibles en este entorno de ejecución.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activado", "77cc5f738cb7d459": "{label} desactivado", - "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", "aba3bb73ce212f0c": "Usar {names} requiere {providerName} {version} o posterior, pero el cask de Homebrew claude-code solo tiene {latestVersion}. Cambia al cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", "d887bea446534de5": "Ningún proyecto de este entorno puede leer {host}/{repository}.", "4e466d60e2f7736b": "Pega la URL completa de la pull request; este hilo no tiene ningún repositorio con el que resolver el número.", "302625058bacbe38": "Pega una URL completa; el host de este proyecto no tiene una URL de {changeRequest} conocida.", @@ -637,6 +657,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", @@ -2497,8 +2520,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}", @@ -2560,10 +2582,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Está en otra máquina, así que el agente de esta máquina no puede leerlo. Quítalo o vuelve a cambiar para enviar.", "5bbac0e5afeec779": "Hilo actual", "33c7e68fca089036": "Hilo, {title}", - "b4b98a0287c282e2": "Está en otra máquina, así que el agente de esta máquina no puede leerlo. Quítalo o vuelve a cambiar para enviar.", - "c6196d99000642b4": "Abrir hilo", "34cc63390ad793cc": "Elige un hilo", "8f12309ead62e38a": "Buscar hilos o proyectos...", "2f664754d005d9a7": "No se encontraron hilos activos.", @@ -2573,6 +2594,7 @@ "a3178769f8308cbc": "El hilo falló", "89b5e8f3887812da": "Solicitud de invitado", "62e626804919b294": "Se necesita una respuesta", + "c6196d99000642b4": "Abrir hilo", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Tú:", "a1fbf2422c588292": "Agente:", @@ -2596,8 +2618,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Proceso de terminal en ejecución", "fc2c9a91f498ad6b": "{count, plural, one {{count} proceso de terminal en ejecución. Abrir terminal} other {{count} procesos de terminal en ejecución. Abrir terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "pila", "6831e9a46cbd8939": "cadena", "9aa9e74a3b7eee91": "Añadir al chat", @@ -3034,8 +3054,8 @@ "6f85f14f35b3f547": "{provider} a través de {environment}", "7c59a888a062a8bd": "La entrada de voz no tiene ningún borrador en el que grabar.", "62450481c00d2ef3": "El entorno del borrador no está disponible para limpiar la transcripción.", - "c64cb58d9cecbcd2": "Falló la limpieza de la transcripción", "0674544195fcdc39": "Se añadió la transcripción original.", + "c64cb58d9cecbcd2": "Falló la limpieza de la transcripción", "296496693cdac0db": "El comando t3 no está disponible.", "efbcef7bc9bbda01": "No se pudo cargar el estado del comando t3.", "1bf6910332426e62": "El acceso a la red del escritorio no está disponible.", @@ -3278,6 +3298,7 @@ "4d493d0bda4d403d": "Vuelve a adjuntar el archivo interrumpido o quítalo", "c9cad1d84d5f1a32": "Vuelve a adjuntar los archivos interrumpidos o quítalos", "536a820f2ff726da": "Selecciona al menos un modelo.", + "48d6389202ad6754": "Se enviará cuando esté listo", "fbafbe78b5e37966": "Reanudar hilo", "bcd7eb979dd38dae": "Abrir el cuadro de mensaje para compactar y enviar", "95ee62a0d6968b89": "Enviar mensaje", @@ -3454,6 +3475,9 @@ "e778e4f446fdf873": "Tu próximo mensaje inicia una sesión nueva", "0e2f2da4f2d94785": "El agente no verá los mensajes anteriores de este hilo.", "e1189d2e582b008d": "Mantener la sesión actual", + "2bb448d605877a22": "Edita o pulsa Esc para cancelar", + "1a1f128d70c62304": "{count, plural, one {Se enviará cuando la imagen esté lista} other {Se enviará cuando {count} imágenes estén listas}}", + "5af3ab719a9725fb": "Enviando mensaje", "461c9f865f2e9b92": "{option} activado", "f2aa17b5c620f2a4": "{option} desactivado", "f59314a884aae1ff": "Predeterminado", @@ -3577,6 +3601,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.", @@ -3597,7 +3629,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", @@ -3693,7 +3724,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Acciones del bloque de código", "ebf3a2b1e314aa5f": "Ejecutar en la terminal", - "fe219642547fa0bf": "Ejecutar en la terminal", "122a8512abc51180": "Detalles", "58c38c65c2783c5d": "Ruta completa", "f37e7d36b51c5b28": "Copiar ruta relativa", @@ -3705,10 +3735,6 @@ "4967584e8d0fb1c2": "Vista previa del contenido", "67589dd912eacb7c": "Abrir en el navegador integrado", "a3c98d4c4b24cecb": "Opciones de archivo de {label}", - "b4fe8a076e9fd2f8": "Ecuación en bloque", - "085d1407e8c92cce": "Ecuación en línea", - "a2ef393fa7b48ae8": "Desplazar la ecuación en bloque", - "e94685ea5642e088": "Desplazar la ecuación en línea", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabla", @@ -3984,9 +4010,11 @@ "973e99fa86d7f531": "Mensaje en cola {position} de {total}, sin enviar", "0f6087c4f53c7f17": "Iniciar un turno con este mensaje ({shortcut})", "adab89933af02669": "Omitir la compactación y enviar este mensaje ({shortcut})", + "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", "3de4016452e8d2bd": "Enviar al turno actual ({shortcut})", "259cc9568148e8ad": "Iniciar un turno con este mensaje", "bb7fddb812d5d29e": "Omitir la compactación y enviar este mensaje", + "425ab15036aec8a4": "Mover este comando al principio de la cola", "a5fe1ee609b29a9f": "Enviar al turno actual", "2b7fd345e4f4fd6e": "Cancelar la edición del mensaje en cola", "47f1726bf106d2c8": "Editar mensaje en cola", @@ -5599,7 +5627,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 +5636,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 +5644,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 +5830,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 +8853,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)", @@ -8841,6 +8872,9 @@ "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 +8958,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 +9189,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 +10162,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 +11060,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 +11755,6 @@ "4c70e3e7b3e6c493": "Secretos", "79b768229c9ef672": "Mantenimiento", "54b188d65247e42f": "Experimentos", - "f41ea186c275b56e": "Acerca de", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versiones e issues", "f2bf529f85e05494": "Compartir y acceso", @@ -11848,6 +11880,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", @@ -12317,7 +12350,6 @@ "0bd41ff995d36a66": "Lectura de caché", "3f0dfe0cb15a3272": "Escritura de caché", "1c9d860be42b1c02": "Salida", - "78344b60f407928e": "Otros", "684e516076de81fe": "Estándar", "3bbcc1b826fef537": "Rápida", "66796576034c18ea": "Ultrarrápida", @@ -12454,6 +12486,8 @@ "faa3bb26abb39c93": "Falló la guía de revisión", "b7df38b7d8792d78": "Abrir guía", "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", - "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", - "425ab15036aec8a4": "Mover este comando al principio de la cola" + "99d51127f573296b": "Otra cuenta", + "8ec2c57414669b79": "Conecta un segundo espacio de trabajo o usuario de {tracker}.", + "99963c0142e17f00": "Para la nueva cuenta de {tracker}.", + "6d8e4ebc889bace9": "Añadir cuenta" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 873767a296ba5..713eca77f3127 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installez {fj} 0.6 ou version ultérieure depuis {fjUrl} et exécutez {fjLogin}, ou installez {tea} 0.16 ou version ultérieure depuis {teaUrl} et exécutez {teaLogin} pour chaque serveur Forgejo ou Gitea.", "d026a85e2e50e675": "Installez la CLI GitCafe avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", "22d3c0c48a34b5b3": "Installez la CLI TanStack Source avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", + "756c80ad262ef315": "En attente dans le fil d'origine", + "d8df14f9905f38eb": "Envoyé", + "e7c59185f8ab3987": "Non envoyé", + "b54ddec9084fa955": "Fermé sans envoi", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Peu clair", + "0f53bc8f74dfe56a": "Fonctionnalité manquante", + "055560f307e15e30": "Documentation incorrecte", + "78344b60f407928e": "Autre", + "f653846a95cd6e8f": "Type", + "f41ea186c275b56e": "À propos", + "2f6e4f7cd364da73": "Résultat attendu", + "9d11c93d4035de3e": "Résultat obtenu", + "c87d0595693704f9": "Solution de repli", + "d7a4ea6ce5af44e0": "{speaker} · {count} caractères", + "f5114fb9c40fd929": "Vous", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Tour {turn} · {what}", + "dfdaa6255a416140": "Résumé de {turns, plural, one {{turns} tour récent} other {{turns} tours récents}}, {textTurns, plural, =0 {sans texte des messages} one {avec le texte des messages du dernier tour} other {avec le texte des messages des {textTurns} derniers tours}}{truncated, select, yes {, raccourci pour tenir dans la limite} other {}}", + "afac52a5cc2dc801": "Impossible d'envoyer votre réponse. Réessayez.", "79d776428f4d0650": "Le fichier n’a pas pu être chargé. Reconnectez-vous et réessayez.", "3ea34cbb1ca5ba9b": "Aperçu annulé.", "7c0af279ecb3da3a": "Les aperçus de fichiers en streaming ne sont pas disponibles dans cet environnement d’exécution.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activé", "77cc5f738cb7d459": "{label} désactivé", - "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", "aba3bb73ce212f0c": "{names} nécessite {providerName} {version} ou une version plus récente, mais le cask Homebrew claude-code ne propose que {latestVersion}. Passe au cask claude-code@latest : {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", "d887bea446534de5": "Aucun projet de cet environnement ne peut lire {host}/{repository}.", "4e466d60e2f7736b": "Collez l’URL complète de la pull request ; ce fil n’a pas de dépôt auquel rattacher le numéro.", "302625058bacbe38": "Collez une URL complète ; l’hôte de ce projet n’a pas de format d’URL connu pour {changeRequest}.", @@ -637,6 +657,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", @@ -2497,8 +2520,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}", @@ -2560,10 +2582,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Sur une autre machine, l’agent de cette machine ne peut donc pas le lire. Retirez-le ou revenez en arrière pour envoyer.", "5bbac0e5afeec779": "Fil actuel", "33c7e68fca089036": "Fil, {title}", - "b4b98a0287c282e2": "Sur une autre machine, l’agent de cette machine ne peut donc pas le lire. Retirez-le ou revenez en arrière pour envoyer.", - "c6196d99000642b4": "Ouvrir le fil", "34cc63390ad793cc": "Choisir un fil", "8f12309ead62e38a": "Rechercher des fils ou des projets...", "2f664754d005d9a7": "Aucun fil actif trouvé.", @@ -2573,6 +2594,7 @@ "a3178769f8308cbc": "Échec du fil", "89b5e8f3887812da": "Demande d’invité", "62e626804919b294": "Réponse requise", + "c6196d99000642b4": "Ouvrir le fil", "826cb862b4a11fb3": "{label} :", "3e597ec938e7551b": "Vous :", "a1fbf2422c588292": "Agent :", @@ -2596,8 +2618,6 @@ "3260b22f72f7effb": "{tooltipLead} : {title}", "feac8e54b30c5a03": "Processus du terminal en cours", "fc2c9a91f498ad6b": "{count, plural, one {{count} processus de terminal en cours. Ouvrir le terminal} other {{count} processus de terminal en cours. Ouvrir le terminal}}", - "643c4b50feadc874": "Worktree : {path} ({branch})", - "fb7c44da0f0825ea": "Worktree : {path}", "56f37ff8ca568059": "pile", "6831e9a46cbd8939": "chaîne", "9aa9e74a3b7eee91": "Ajouter à la discussion", @@ -3034,8 +3054,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "La saisie vocale n’a aucun brouillon dans lequel enregistrer.", "62450481c00d2ef3": "L’environnement du brouillon n’est pas disponible pour nettoyer la transcription.", - "c64cb58d9cecbcd2": "Échec du nettoyage de la transcription", "0674544195fcdc39": "La transcription d’origine a été ajoutée.", + "c64cb58d9cecbcd2": "Échec du nettoyage de la transcription", "296496693cdac0db": "La commande t3 n’est pas disponible.", "efbcef7bc9bbda01": "Échec du chargement de l’état de la commande t3.", "1bf6910332426e62": "L’accès réseau de l’app desktop n’est pas disponible.", @@ -3278,6 +3298,7 @@ "4d493d0bda4d403d": "Joignez à nouveau le fichier interrompu ou retirez-le", "c9cad1d84d5f1a32": "Joignez à nouveau les fichiers interrompus ou retirez-les", "536a820f2ff726da": "Sélectionnez au moins un modèle.", + "48d6389202ad6754": "Envoi dès que prêt", "fbafbe78b5e37966": "Reprendre le fil", "bcd7eb979dd38dae": "Ouvrir la zone de saisie pour compacter et envoyer", "95ee62a0d6968b89": "Envoyer le message", @@ -3454,6 +3475,9 @@ "e778e4f446fdf873": "Votre prochain message démarre une nouvelle session", "0e2f2da4f2d94785": "L’agent ne verra pas les messages précédents de ce fil.", "e1189d2e582b008d": "Garder la session actuelle", + "2bb448d605877a22": "Modifiez ou appuyez sur Échap pour annuler", + "1a1f128d70c62304": "{count, plural, one {Envoi dès que l’image est prête} other {Envoi dès que les {count} images sont prêtes}}", + "5af3ab719a9725fb": "Envoi du message", "461c9f865f2e9b92": "{option} activé", "f2aa17b5c620f2a4": "{option} désactivé", "f59314a884aae1ff": "Par défaut", @@ -3577,6 +3601,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é.", @@ -3597,7 +3629,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", @@ -3693,7 +3724,6 @@ "7c1923203049d602": "Copier le code", "637817e4ff79c90e": "Actions du bloc de code", "ebf3a2b1e314aa5f": "Exécuter dans le terminal", - "fe219642547fa0bf": "Exécuter dans le terminal", "122a8512abc51180": "Détails", "58c38c65c2783c5d": "Chemin complet", "f37e7d36b51c5b28": "Copier le chemin relatif", @@ -3705,10 +3735,6 @@ "4967584e8d0fb1c2": "Aperçu du média", "67589dd912eacb7c": "Ouvrir dans le navigateur intégré", "a3c98d4c4b24cecb": "Options du fichier {label}", - "b4fe8a076e9fd2f8": "Équation en bloc", - "085d1407e8c92cce": "Équation en ligne", - "a2ef393fa7b48ae8": "Faire défiler l’équation en bloc", - "e94685ea5642e088": "Faire défiler l’équation en ligne", "3a04583c8500e23d": "Afficher le diagramme", "16d64f650840fe06": "Afficher le code", "6d329f7d3a50c7e7": "Copier le tableau", @@ -3985,9 +4011,11 @@ "973e99fa86d7f531": "Message en file d’attente {position} sur {total}, non envoyé", "0f6087c4f53c7f17": "Démarrer un tour avec ce message ({shortcut})", "adab89933af02669": "Passer le compactage et envoyer ce message ({shortcut})", + "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", "3de4016452e8d2bd": "Envoyer dans le tour en cours ({shortcut})", "259cc9568148e8ad": "Démarrer un tour avec ce message", "bb7fddb812d5d29e": "Passer le compactage et envoyer ce message", + "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente", "a5fe1ee609b29a9f": "Envoyer dans le tour en cours", "2b7fd345e4f4fd6e": "Annuler la modification du message en file d’attente", "47f1726bf106d2c8": "Modifier le message en file d’attente", @@ -5600,7 +5628,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 +5637,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 +5645,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 +5831,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 +8854,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)", @@ -8842,6 +8873,9 @@ "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 +8960,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 +9191,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 +10164,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 +11065,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 +11760,6 @@ "4c70e3e7b3e6c493": "Secrets", "79b768229c9ef672": "Maintenance", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "À propos", "af4b7734da1d5ce7": "Voix", "4ec62c39ca3192bf": "Versions et tickets", "f2bf529f85e05494": "Partage et accès", @@ -11853,6 +11885,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", @@ -12322,7 +12355,6 @@ "0bd41ff995d36a66": "Lecture du cache", "3f0dfe0cb15a3272": "Écriture du cache", "1c9d860be42b1c02": "Sortie", - "78344b60f407928e": "Autre", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Rapide", "66796576034c18ea": "Ultrarapide", @@ -12459,6 +12491,8 @@ "faa3bb26abb39c93": "Échec du guide de revue", "b7df38b7d8792d78": "Ouvrir le guide", "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", - "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", - "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente" + "99d51127f573296b": "Autre compte", + "8ec2c57414669b79": "Connectez un second espace de travail ou utilisateur {tracker}.", + "99963c0142e17f00": "Pour le nouveau compte {tracker}.", + "6d8e4ebc889bace9": "Ajouter un compte" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 69ac82ad8a247..2b44f05d584e1 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Forgejo または Gitea のサーバーごとに、{fjUrl} から {fj} 0.6 以降をインストールして {fjLogin} を実行するか、{teaUrl} から {tea} 0.16 以降をインストールして {teaLogin} を実行してください。", "d026a85e2e50e675": "{install} で GitCafe CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", "22d3c0c48a34b5b3": "{install} で TanStack Source CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", + "756c80ad262ef315": "元のスレッドで待機中", + "d8df14f9905f38eb": "送信済み", + "e7c59185f8ab3987": "未送信", + "b54ddec9084fa955": "送信せずに閉じました", + "fbaa7ab5da716e50": "不具合", + "01bac997ea55272e": "分かりにくい", + "0f53bc8f74dfe56a": "機能の不足", + "055560f307e15e30": "ドキュメントの誤り", + "78344b60f407928e": "その他", + "f653846a95cd6e8f": "種類", + "f41ea186c275b56e": "情報", + "2f6e4f7cd364da73": "期待した動作", + "9d11c93d4035de3e": "実際の動作", + "c87d0595693704f9": "代わりに行ったこと", + "d7a4ea6ce5af44e0": "{speaker} · {count} 文字", + "f5114fb9c40fd929": "あなた", + "cd03eb1b84271c02": "エージェント", + "bfe1a60f3f9c60fb": "ターン {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {直近 {turns} ターン} other {直近 {turns} ターン}}の概要、{textTurns, plural, =0 {メッセージ本文なし} one {最後のターンのメッセージ本文} other {直近 {textTurns} ターンのメッセージ本文}}{truncated, select, yes {、収まる長さに短縮済み} other {}}", + "afac52a5cc2dc801": "回答を送信できませんでした。もう一度お試しください。", "79d776428f4d0650": "ファイルを読み込めませんでした。再接続してもう一度お試しください。", "3ea34cbb1ca5ba9b": "プレビューをキャンセルしました。", "7c0af279ecb3da3a": "このランタイムではファイルのストリーミングプレビューを利用できません。", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "標準", "f42c2a36b3507308": "{label} オン", "77cc5f738cb7d459": "{label} オフ", - "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", "aba3bb73ce212f0c": "{names} を使うには {providerName} {version} 以降が必要ですが、Homebrew の claude-code cask には {latestVersion} までしかありません。claude-code@latest cask に切り替えてください: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", "d887bea446534de5": "この環境には {host}/{repository} を読み取れるプロジェクトがありません。", "4e466d60e2f7736b": "プルリクエストの完全な URL を貼り付けてください。このスレッドには番号を解決するためのリポジトリがありません。", "302625058bacbe38": "完全な URL を貼り付けてください。このプロジェクトのホストには既知の {changeRequest} URL がありません。", @@ -637,6 +657,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2495,8 +2518,7 @@ "2d1c111e1b4ae0b0": "スレッド「{title}」を削除しますか?", "c568ab8dad798ec5": "このスレッドの会話履歴が完全に消去されます。", "0fd1c746a0e38003": "スレッドを削除できませんでした", - "0ecde875b0dd2f93": "プロジェクトでスレッドを絞り込み: {projects}", - "1ef65b647231ff0b": "プロジェクトでスレッドを絞り込み", + "1c8fc3c4a42949ab": "プロジェクト: {projects}", "165511761be2855c": "プロジェクトを検索", "a46a6467883575a4": "プロジェクトを検索...", "fdc0e086438a3045": "{project} のプロジェクト設定", @@ -2558,10 +2580,9 @@ }, " にインストール" ], + "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", "5bbac0e5afeec779": "現在のスレッド", "33c7e68fca089036": "スレッド、{title}", - "b4b98a0287c282e2": "別のマシン上にあるため、このマシンのエージェントは読み取れません。削除するか、元に戻してから送信してください。", - "c6196d99000642b4": "スレッドを開く", "34cc63390ad793cc": "スレッドを選択", "8f12309ead62e38a": "スレッドまたはプロジェクトを検索...", "2f664754d005d9a7": "アクティブなスレッドが見つかりません。", @@ -2571,6 +2592,7 @@ "a3178769f8308cbc": "スレッドが失敗しました", "89b5e8f3887812da": "ゲストのリクエスト", "62e626804919b294": "入力が必要です", + "c6196d99000642b4": "スレッドを開く", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "あなた:", "a1fbf2422c588292": "エージェント:", @@ -2594,8 +2616,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "ターミナルのプロセスが実行中", "fc2c9a91f498ad6b": "{count, plural, other {{count} 個のターミナルプロセスが実行中。ターミナルを開く}}", - "643c4b50feadc874": "ワークツリー: {path} ({branch})", - "fb7c44da0f0825ea": "ワークツリー: {path}", "56f37ff8ca568059": "スタック", "6831e9a46cbd8939": "チェーン", "9aa9e74a3b7eee91": "チャットに追加", @@ -3032,8 +3052,8 @@ "6f85f14f35b3f547": "{provider} ({environment} 経由)", "7c59a888a062a8bd": "音声入力を記録する下書きがありません。", "62450481c00d2ef3": "下書きの環境を利用できないため、文字起こしを整形できません。", - "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "0674544195fcdc39": "元の文字起こしを追加しました。", + "c64cb58d9cecbcd2": "文字起こしの整形に失敗しました", "296496693cdac0db": "t3 コマンドを利用できません。", "efbcef7bc9bbda01": "t3 コマンドの状態を読み込めませんでした。", "1bf6910332426e62": "デスクトップのネットワークアクセスを利用できません。", @@ -3276,6 +3296,7 @@ "4d493d0bda4d403d": "中断されたファイルをもう一度添付するか、削除してください", "c9cad1d84d5f1a32": "中断されたファイルをもう一度添付するか、削除してください", "536a820f2ff726da": "モデルを少なくとも 1 つ選択してください。", + "48d6389202ad6754": "準備ができたら送信", "fbafbe78b5e37966": "スレッドを再開", "bcd7eb979dd38dae": "入力欄を開いて圧縮して送信", "95ee62a0d6968b89": "メッセージを送信", @@ -3450,6 +3471,9 @@ "e778e4f446fdf873": "次のメッセージで新しいセッションが始まります", "0e2f2da4f2d94785": "エージェントはこのスレッドの以前のメッセージを参照できません。", "e1189d2e582b008d": "現在のセッションを維持", + "2bb448d605877a22": "編集または Esc でキャンセル", + "1a1f128d70c62304": "{count, plural, other {画像の準備ができたら送信}}", + "5af3ab719a9725fb": "メッセージを送信中", "461c9f865f2e9b92": "{option} オン", "f2aa17b5c620f2a4": "{option} オフ", "f59314a884aae1ff": "デフォルト", @@ -3573,6 +3597,14 @@ "c53bc5a4b0314342": "次のメディア", "2950b1424a3cddf5": "この環境に再接続してから、もう一度メディアを開いてください。", "ef638bf1479a5461": "環境から無効なメディア URL が返されました。", + "3ccfbf7e86868c35": "T3 チームへのフィードバック", + "4e0710d19dfc2e7e": "このレポートを T3 チームに送信しますか?", + "87d0ae0723ba75d1": "この内容だけがこのマシンから送信されます。「送信」を押すまで何も送信されません。", + "bf19826f81484328": "会話を含める", + "260c6b45f52d2f27": "直近 {textTurns} ターンでのあなたのメッセージとエージェントの返信の本文を追加します。", + "ddb7e6f8ce99e657": "このマシンでエージェントを実行できる人だけが、送信または拒否できます。", + "03c1eb603c112f47": "送信しない", + "653405e4ed498d9f": "送信", "262955d6eb632f9b": "ゲストリンクをコピーする際にクリップボード API を利用できませんでした。", "f1a4f2b04cdbb4ef": "ゲストリンクをクリップボードにコピーできませんでした。", "cf3490a604e44d31": "ゲストリンクを作成できませんでした。", @@ -3593,7 +3625,6 @@ "abd89e9eefedf11b": "完了", "18d166056c1ab6ff": "共有を停止", "7a2d510eac9e4587": "ゲストリンクの期限が切れました", - "653405e4ed498d9f": "送信", "21888e302219891d": "拡大した {title} のプレビュー", "419719298a7acaea": "縮小", "ed8d5db95359cff4": "ズームをリセット", @@ -3688,7 +3719,6 @@ "7c1923203049d602": "コードをコピー", "637817e4ff79c90e": "コードブロックの操作", "ebf3a2b1e314aa5f": "ターミナルで実行", - "fe219642547fa0bf": "ターミナルで実行", "122a8512abc51180": "詳細", "58c38c65c2783c5d": "フルパス", "f37e7d36b51c5b28": "相対パスをコピー", @@ -3700,10 +3730,6 @@ "4967584e8d0fb1c2": "メディアをプレビュー", "67589dd912eacb7c": "統合ブラウザーで開く", "a3c98d4c4b24cecb": "{label} のファイルオプション", - "b4fe8a076e9fd2f8": "ディスプレイ数式", - "085d1407e8c92cce": "インライン数式", - "a2ef393fa7b48ae8": "ディスプレイ数式をスクロール", - "e94685ea5642e088": "インライン数式をスクロール", "3a04583c8500e23d": "図を表示", "16d64f650840fe06": "コードを表示", "6d329f7d3a50c7e7": "表をコピー", @@ -3975,9 +4001,11 @@ "973e99fa86d7f531": "キュー内のメッセージ {position}/{total}、未送信", "0f6087c4f53c7f17": "このメッセージでターンを開始 ({shortcut})", "adab89933af02669": "圧縮をスキップしてこのメッセージを送信 ({shortcut})", + "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", "3de4016452e8d2bd": "現在のターンに送信 ({shortcut})", "259cc9568148e8ad": "このメッセージでターンを開始", "bb7fddb812d5d29e": "圧縮をスキップしてこのメッセージを送信", + "425ab15036aec8a4": "このコマンドをキューの先頭に移動", "a5fe1ee609b29a9f": "現在のターンに送信", "2b7fd345e4f4fd6e": "キュー内のメッセージの編集をキャンセル", "47f1726bf106d2c8": "キュー内のメッセージを編集", @@ -5582,7 +5610,6 @@ }, "。リンクのパスを確認するか、[ファイル] でファイルを探してください。" ], - "b9b6bbd1e1ea189f": "ファイル全体", "d715e9494fdbaaf6": "フォントを読み込めませんでした。", "ff17c777a72b4408": "フォントのプレビューは 10 MB までです。", "6bd41ad699e22f10": "フォントを利用できません。", @@ -5592,6 +5619,7 @@ "a9abaaa4220eae21": "{error} 別のアプリで開くには保存してください。", "c508c9000d9656f8": "フォントのプレビュー", "1c416d621d250be8": "いろはにほへと ちりぬるを わかよたれそ つねならむ", + "d7d08260f16b7828": "ファイルはまだ読み込み中です。少し待ってからもう一度お試しください。", "76ebb03de52c92d6": "テキストビューアーが停止しました。", "f48162e8e8c12af7": "テキストビューアーを読み込めませんでした。ファイルを閉じて、もう一度お試しください。", "bc4c5b13d38a5da7": "プレビューを閉じました。", @@ -5599,8 +5627,6 @@ "9450d1827ef336a1": "別のコピーが進行中です。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 バイト", - "f6e9581cba3467fa": "インデックスを作成しています…", - "2d1f293ac12463fc": "ファイルの残りを読み込んでいます…", "b75105bef8f564a4": "最初の 1,024 列を表示しています。ソースと保存ではすべての列が保持されます。", "2a6e1b1f209c3888": "このファイルは空です。", "192fc79eb3b5b2cb": "この図にはリソース URL、マークアップ、ノードのメタデータ、またはカスタム構成が含まれています。安全に確認するには Mermaid のソースを表示してください。", @@ -5787,7 +5813,6 @@ "0061fff77e36bd4f": "サーバーに接続できませんでした。", "04dfdd46e3dd4a2e": "問題が発生しました。もう一度お試しください。", "084bb2d8127a508d": "送信済み", - "e7c59185f8ab3987": "未送信", "77c01a15bd36d17c": "このリンクは終了したか、無効です", "e0e736810f3cbef2": "所有者に新しいリンクを依頼してください。各リンクは 1 つのブラウザーでのみ使用できます。", "c3c53aa46f7330e5": "このリンクは終了しました", @@ -8786,6 +8811,12 @@ "d3866ead082d14e5": "キーボードショートカットを追加", "d4345c90894a3220": "keybindings.json を開く", "e56a8d51219efaa0": "検索に一致するキーボードショートカットはありません。", + "90a258fff61fd77e": "オフ", + "4060244a7079a0d2": "依頼したとき", + "e88c9d8769544731": "自動", + "f29d1dade4dde8aa": "エージェントは T3 チームにフィードバックを送信しません。", + "93c4c53562d30a98": "依頼すると、エージェントが T3 Code についての短いレポートを表示し、承認した場合に T3 チームへ送信します。", + "cd9ee803e8727017": "エージェントが自ら遭遇した T3 Code の問題も報告します。たとえば、T3 ツールの失敗などです。", "45fa271ea0e1ac8e": "ベータ", "3a678332fc7142f7": "サイドバーのスレッドをプロジェクトフォルダーにまとめます。ピン留めしたスレッドは上部に残り、スヌーズ中と対応済みはフォルダーの下に表示されます。", "e4e91d155cb6a9b4": "シンプルなサイドバー(プロジェクトでグループ化)", @@ -8799,6 +8830,9 @@ "298c7150a7621c80": "Simlock デバイスホスト", "67937aa49179285e": "Mac では、すべてのファイルを書き込む代わりに、T3 ホームフォルダーにキャッシュしたチェックアウトから新しいワークツリーを複製します。できない場合は Git の通常のチェックアウトを使います。オフにするとキャッシュは削除されます。", "f9904f78d3003f58": "高速ワークツリーチェックアウト", + "9c2f647882522302": "選択したマシンでは、エージェントのフィードバックモードが異なります。", + "31bbf7bf8c0a5279": "エージェントのフィードバック", + "d52b3d6bf9f2a013": "混在", "ec7623deed751c05": [ "スレッドをゲストと共有します。ゲストはブラウザーでライブで閲覧し、あなたが承認したメッセージを送信できます。T3 Connect が必要です。サインインして、", " ", @@ -8882,7 +8916,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 +9148,6 @@ "0b4779a1825c85bc": "サイドバーとスレッド一覧に表示される、このプロジェクトグループの共通の名前です。", "f68cbda4df83d739": "プロジェクト名をデフォルトにリセット", "56e37b85027e8431": "プロジェクトのアイコン", - "e88c9d8769544731": "自動", "c99736317da5b1fa": "プロジェクトのアイコンをデフォルトにリセット", "6afaa3e3739dc570": "プロジェクトのアイコンを選択", "51651ce45d481a20": "プロジェクトのアイコンファイルを選択", @@ -10082,7 +10117,6 @@ "16bdc70b858c223f": "自動で開くパネルをデフォルトにリセット", "c5424f09d77138ff": "200,000 トークンを超えるアイドル状態の Claude スレッドを圧縮するタイミングです。戻ってきた後、プロンプトキャッシュの有効期限の直前、またはしない、から選びます。Claude プロバイダーごとに上書きできます。", "3e99c5c14f4939c8": "「アイドル状態のスレッドを圧縮」をデフォルトにリセット", - "d52b3d6bf9f2a013": "混在", "cd72fe451ba0d6aa": "新しいプロジェクト", "394c3bd0a1782c8e": "空のままにすると、「プロジェクトを追加」のブラウザーを開いたときに \"~/\" を使用します。", "f9b912a818bd869d": "プロジェクト追加のベースディレクトリをデフォルトにリセット", @@ -10982,7 +11016,6 @@ "4a237f41ce592b7f": "このプロジェクトのワークツリーは、手動で削除するまで保持します。", "00b8ffd8ea6e6a93": "このプロジェクトでこれらのルールを使用します。", "72c279824d15a999": "各マシンのワークツリーのクリーンアップ設定を使用します。", - "90a258fff61fd77e": "オフ", "b5702d0b64866b08": "カスタム", "c009c901f3eefe78": "削除したスレッドのワークツリーを削除", "431c7cd6d50102b7": "アクティブまたはアーカイブ済みのスレッドを削除したときに、使われていないワークツリーを削除します。ローカルの変更があるワークツリーは保持されます。", @@ -11678,7 +11711,6 @@ "4c70e3e7b3e6c493": "シークレット", "79b768229c9ef672": "メンテナンス", "54b188d65247e42f": "試験的機能", - "f41ea186c275b56e": "情報", "af4b7734da1d5ce7": "音声", "4ec62c39ca3192bf": "ソース管理と Issue", "f2bf529f85e05494": "共有とアクセス", @@ -11804,6 +11836,7 @@ "901a823214edc8c4": "テレメトリー 分析 使用状況データ トラッキング 法的事項 オプトアウト telemetry", "82136480255a5106": "OTel OTLP テレメトリー エクスポート エンドポイント ログ トレース メトリクス Grafana", "659d081051faf7ff": "ログ トレース プロセス リソース履歴 失敗 スパン CPU メモリ diagnostics", + "5eaeacfa9f82051a": "報告 不具合 問題 t3 チーム 送信 フィードバック エージェント ツール 自動 依頼したとき", "f537f91e1ee41d47": "キーボードショートカット ホットキー コマンド キーバインド JSON keybindings", "1ba01e7ceed64b95": "ウィンドウ キャプチャ スクリーンショット window capture", "279b1cceb779ff38": "アプリのテキストを含める", @@ -12273,7 +12306,6 @@ "0bd41ff995d36a66": "キャッシュの読み取り", "3f0dfe0cb15a3272": "キャッシュの書き込み", "1c9d860be42b1c02": "出力", - "78344b60f407928e": "その他", "684e516076de81fe": "標準", "3bbcc1b826fef537": "高速", "66796576034c18ea": "超高速", @@ -12408,6 +12440,8 @@ "faa3bb26abb39c93": "レビューガイドの作成に失敗しました", "b7df38b7d8792d78": "ガイドを開く", "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", - "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", - "425ab15036aec8a4": "このコマンドをキューの先頭に移動" + "99d51127f573296b": "別のアカウント", + "8ec2c57414669b79": "2つ目の {tracker} ワークスペースまたはユーザーを接続します。", + "99963c0142e17f00": "新しい {tracker} アカウント用です。", + "6d8e4ebc889bace9": "アカウントを追加" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 10782b2ca6166..48dc094c371ad 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "{fjUrl}에서 {fj} 0.6 이상을 설치하고 {fjLogin}을(를) 실행하거나, {teaUrl}에서 {tea} 0.16 이상을 설치하고 Forgejo 또는 Gitea 서버마다 {teaLogin}을(를) 실행하세요.", "d026a85e2e50e675": "{install}로 GitCafe CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", "22d3c0c48a34b5b3": "{install}로 TanStack Source CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", + "756c80ad262ef315": "원래 스레드에서 대기 중", + "d8df14f9905f38eb": "보냄", + "e7c59185f8ab3987": "보내지 않음", + "b54ddec9084fa955": "보내지 않고 닫음", + "fbaa7ab5da716e50": "버그", + "01bac997ea55272e": "이해하기 어려움", + "0f53bc8f74dfe56a": "기능 부족", + "055560f307e15e30": "잘못된 문서", + "78344b60f407928e": "기타", + "f653846a95cd6e8f": "유형", + "f41ea186c275b56e": "정보", + "2f6e4f7cd364da73": "기대한 동작", + "9d11c93d4035de3e": "실제 동작", + "c87d0595693704f9": "대신 한 일", + "d7a4ea6ce5af44e0": "{speaker} · {count}자", + "f5114fb9c40fd929": "나", + "cd03eb1b84271c02": "에이전트", + "bfe1a60f3f9c60fb": "턴 {turn} · {what}", + "dfdaa6255a416140": "{turns, plural, one {최근 {turns}개 턴} other {최근 {turns}개 턴}}의 개요, {textTurns, plural, =0 {메시지 본문 없음} one {마지막 턴의 메시지 본문} other {최근 {textTurns}개 턴의 메시지 본문}}{truncated, select, yes {, 길이에 맞게 줄임} other {}}", + "afac52a5cc2dc801": "답변을 보내지 못했습니다. 다시 시도하세요.", "79d776428f4d0650": "파일을 불러올 수 없습니다. 다시 연결한 뒤 시도하세요.", "3ea34cbb1ca5ba9b": "미리 보기가 취소되었습니다.", "7c0af279ecb3da3a": "이 런타임에서는 스트리밍 파일 미리 보기를 사용할 수 없습니다.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "보통", "f42c2a36b3507308": "{label} 켜짐", "77cc5f738cb7d459": "{label} 꺼짐", - "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", "aba3bb73ce212f0c": "{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만 Homebrew claude-code cask에는 {latestVersion}까지만 있습니다. claude-code@latest cask로 전환하세요: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", "d887bea446534de5": "이 환경에는 {host}/{repository}을(를) 읽을 수 있는 프로젝트가 없습니다.", "4e466d60e2f7736b": "전체 풀 리퀘스트 URL을 붙여 넣으세요. 이 스레드에는 번호를 확인할 저장소가 없습니다.", "302625058bacbe38": "전체 URL을 붙여 넣으세요. 이 프로젝트의 호스트에는 알려진 {changeRequest} URL이 없습니다.", @@ -637,6 +657,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", @@ -2496,8 +2519,7 @@ "2d1c111e1b4ae0b0": "스레드 \"{title}\"을(를) 삭제할까요?", "c568ab8dad798ec5": "이 스레드의 대화 기록이 영구적으로 삭제됩니다.", "0fd1c746a0e38003": "스레드를 삭제하지 못했습니다", - "0ecde875b0dd2f93": "프로젝트별 스레드 필터: {projects}", - "1ef65b647231ff0b": "프로젝트별 스레드 필터", + "1c8fc3c4a42949ab": "프로젝트: {projects}", "165511761be2855c": "프로젝트 검색", "a46a6467883575a4": "프로젝트 검색...", "fdc0e086438a3045": "{project} 프로젝트 설정", @@ -2559,10 +2581,9 @@ }, "에 설치" ], + "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", "5bbac0e5afeec779": "현재 스레드", "33c7e68fca089036": "스레드, {title}", - "b4b98a0287c282e2": "다른 머신에 있어 이 머신의 에이전트가 읽을 수 없습니다. 제거하거나 원래대로 전환한 후 보내세요.", - "c6196d99000642b4": "스레드 열기", "34cc63390ad793cc": "스레드 선택", "8f12309ead62e38a": "스레드 또는 프로젝트 검색...", "2f664754d005d9a7": "활성 스레드를 찾을 수 없습니다.", @@ -2572,6 +2593,7 @@ "a3178769f8308cbc": "스레드 실패", "89b5e8f3887812da": "게스트 요청", "62e626804919b294": "입력 필요", + "c6196d99000642b4": "스레드 열기", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "나:", "a1fbf2422c588292": "에이전트:", @@ -2595,8 +2617,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "터미널 프로세스 실행 중", "fc2c9a91f498ad6b": "{count, plural, other {터미널 프로세스 {count}개 실행 중. 터미널 열기}}", - "643c4b50feadc874": "워크트리: {path}({branch})", - "fb7c44da0f0825ea": "워크트리: {path}", "56f37ff8ca568059": "스택", "6831e9a46cbd8939": "체인", "9aa9e74a3b7eee91": "채팅에 추가", @@ -3033,8 +3053,8 @@ "6f85f14f35b3f547": "{environment}을(를) 통한 {provider}", "7c59a888a062a8bd": "음성 입력을 기록할 초안이 없습니다.", "62450481c00d2ef3": "초안의 환경을 사용할 수 없어 받아쓴 내용을 정리할 수 없습니다.", - "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "0674544195fcdc39": "원본 받아쓰기 내용이 추가되었습니다.", + "c64cb58d9cecbcd2": "받아쓴 내용 정리 실패", "296496693cdac0db": "t3 명령을 사용할 수 없습니다.", "efbcef7bc9bbda01": "t3 명령 상태를 불러오지 못했습니다.", "1bf6910332426e62": "데스크톱 네트워크 액세스를 사용할 수 없습니다.", @@ -3277,6 +3297,7 @@ "4d493d0bda4d403d": "중단된 파일을 다시 첨부하거나 제거하세요", "c9cad1d84d5f1a32": "중단된 파일을 다시 첨부하거나 제거하세요", "536a820f2ff726da": "모델을 하나 이상 선택하세요.", + "48d6389202ad6754": "준비되면 전송", "fbafbe78b5e37966": "스레드 재개", "bcd7eb979dd38dae": "압축하고 보내려면 입력창을 여세요", "95ee62a0d6968b89": "메시지 보내기", @@ -3450,6 +3471,9 @@ "e778e4f446fdf873": "다음 메시지부터 새 세션이 시작됩니다", "0e2f2da4f2d94785": "에이전트는 이 스레드의 이전 메시지를 볼 수 없습니다.", "e1189d2e582b008d": "현재 세션 유지", + "2bb448d605877a22": "편집하거나 Esc를 눌러 취소", + "1a1f128d70c62304": "{count, plural, other {이미지가 준비되면 전송}}", + "5af3ab719a9725fb": "메시지 전송 중", "461c9f865f2e9b92": "{option} 켜짐", "f2aa17b5c620f2a4": "{option} 꺼짐", "f59314a884aae1ff": "기본값", @@ -3573,6 +3597,14 @@ "c53bc5a4b0314342": "다음 미디어", "2950b1424a3cddf5": "이 환경에 다시 연결한 후 미디어를 다시 여세요.", "ef638bf1479a5461": "환경에서 잘못된 미디어 URL을 반환했습니다.", + "3ccfbf7e86868c35": "T3 팀에 보내는 피드백", + "4e0710d19dfc2e7e": "이 보고서를 T3 팀에 보낼까요?", + "87d0ae0723ba75d1": "이 내용만 이 컴퓨터에서 전송됩니다. 보내기를 누르기 전에는 아무것도 전송되지 않습니다.", + "bf19826f81484328": "대화 포함", + "260c6b45f52d2f27": "최근 {textTurns}개 턴에서 내 메시지와 에이전트 답변의 본문을 추가합니다.", + "ddb7e6f8ce99e657": "이 컴퓨터에서 에이전트를 실행할 수 있는 사람만 보고서를 보내거나 거절할 수 있습니다.", + "03c1eb603c112f47": "보내지 않기", + "653405e4ed498d9f": "보내기", "262955d6eb632f9b": "게스트 링크를 복사하는 중 클립보드 API를 사용할 수 없습니다.", "f1a4f2b04cdbb4ef": "게스트 링크를 클립보드에 복사하지 못했습니다.", "cf3490a604e44d31": "게스트 링크를 만들 수 없습니다.", @@ -3593,7 +3625,6 @@ "abd89e9eefedf11b": "완료", "18d166056c1ab6ff": "공유 중지", "7a2d510eac9e4587": "게스트 링크 만료됨", - "653405e4ed498d9f": "보내기", "21888e302219891d": "확대된 {title} 미리 보기", "419719298a7acaea": "축소", "ed8d5db95359cff4": "확대/축소 초기화", @@ -3688,7 +3719,6 @@ "7c1923203049d602": "코드 복사", "637817e4ff79c90e": "코드 블록 작업", "ebf3a2b1e314aa5f": "터미널에서 실행", - "fe219642547fa0bf": "터미널에서 실행", "122a8512abc51180": "세부 정보", "58c38c65c2783c5d": "전체 경로", "f37e7d36b51c5b28": "상대 경로 복사", @@ -3700,10 +3730,6 @@ "4967584e8d0fb1c2": "미디어 미리 보기", "67589dd912eacb7c": "통합 브라우저에서 열기", "a3c98d4c4b24cecb": "{label} 파일 옵션", - "b4fe8a076e9fd2f8": "블록 수식", - "085d1407e8c92cce": "인라인 수식", - "a2ef393fa7b48ae8": "블록 수식 스크롤", - "e94685ea5642e088": "인라인 수식 스크롤", "3a04583c8500e23d": "다이어그램 표시", "16d64f650840fe06": "코드 표시", "6d329f7d3a50c7e7": "표 복사", @@ -3973,9 +3999,11 @@ "973e99fa86d7f531": "대기열 메시지 {total}개 중 {position}번째, 보내지 않음", "0f6087c4f53c7f17": "이 메시지로 턴 시작({shortcut})", "adab89933af02669": "압축을 건너뛰고 이 메시지 보내기({shortcut})", + "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", "3de4016452e8d2bd": "현재 턴에 보내기({shortcut})", "259cc9568148e8ad": "이 메시지로 턴 시작", "bb7fddb812d5d29e": "압축을 건너뛰고 이 메시지 보내기", + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동", "a5fe1ee609b29a9f": "현재 턴에 보내기", "2b7fd345e4f4fd6e": "대기열 메시지 편집 취소", "47f1726bf106d2c8": "대기열 메시지 편집", @@ -5580,7 +5608,6 @@ }, ". 링크의 경로를 확인하거나 파일에서 해당 파일을 찾으세요." ], - "b9b6bbd1e1ea189f": "전체 파일", "d715e9494fdbaaf6": "글꼴을 불러올 수 없습니다.", "ff17c777a72b4408": "글꼴 미리 보기는 10MB로 제한됩니다.", "6bd41ad699e22f10": "글꼴을 사용할 수 없습니다.", @@ -5590,6 +5617,7 @@ "a9abaaa4220eae21": "{error} 저장한 후 다른 앱에서 여세요.", "c508c9000d9656f8": "글꼴 미리 보기", "1c416d621d250be8": "다람쥐 헌 쳇바퀴에 타고파.", + "d7d08260f16b7828": "파일을 아직 불러오는 중입니다. 잠시 후 다시 시도하세요.", "76ebb03de52c92d6": "텍스트 뷰어가 중지되었습니다.", "f48162e8e8c12af7": "텍스트 뷰어를 불러올 수 없습니다. 파일을 닫고 다시 시도하세요.", "bc4c5b13d38a5da7": "미리 보기가 닫혔습니다.", @@ -5597,8 +5625,6 @@ "9450d1827ef336a1": "다른 복사가 진행 중입니다.", "8f48999eb6d9e2e3": "{count, plural, other {{formatted}줄}}", "13b14784f8707ddd": "0바이트", - "f6e9581cba3467fa": "색인하는 중…", - "2d1f293ac12463fc": "파일의 나머지를 불러오는 중…", "b75105bef8f564a4": "처음 1,024열을 표시합니다. 소스와 저장에는 모든 열이 유지됩니다.", "2a6e1b1f209c3888": "이 파일은 비어 있습니다.", "192fc79eb3b5b2cb": "이 다이어그램에는 리소스 URL, 마크업, 노드 메타데이터 또는 사용자 지정 구성이 포함되어 있습니다. 안전하게 확인하려면 Mermaid 소스를 표시하세요.", @@ -5785,7 +5811,6 @@ "0061fff77e36bd4f": "서버에 연결할 수 없습니다.", "04dfdd46e3dd4a2e": "문제가 발생했습니다. 다시 시도하세요.", "084bb2d8127a508d": "보냄", - "e7c59185f8ab3987": "보내지 않음", "77c01a15bd36d17c": "이 링크는 종료되었거나 유효하지 않습니다", "e0e736810f3cbef2": "소유자에게 새 링크를 요청하세요. 각 링크는 한 브라우저에서만 작동합니다.", "c3c53aa46f7330e5": "이 링크는 종료되었습니다", @@ -8789,6 +8814,12 @@ "d3866ead082d14e5": "단축키 추가", "d4345c90894a3220": "keybindings.json 열기", "e56a8d51219efaa0": "검색과 일치하는 단축키가 없습니다.", + "90a258fff61fd77e": "끔", + "4060244a7079a0d2": "내가 요청할 때", + "e88c9d8769544731": "자동", + "f29d1dade4dde8aa": "에이전트가 T3 팀에 피드백을 보내지 않습니다.", + "93c4c53562d30a98": "요청하면 에이전트가 T3 Code에 관한 짧은 보고서를 보여주고, 승인하면 T3 팀에 보냅니다.", + "cd9ee803e8727017": "에이전트가 직접 겪은 T3 Code 문제도 보고합니다. 예를 들어 T3 도구가 실패한 경우입니다.", "45fa271ea0e1ac8e": "베타", "3a678332fc7142f7": "사이드바 스레드를 프로젝트 폴더로 묶습니다. 고정된 스레드는 맨 위에, 다시 알림과 정리됨은 폴더 아래에 유지됩니다.", "e4e91d155cb6a9b4": "단순 사이드바(프로젝트별 그룹화)", @@ -8802,6 +8833,9 @@ "298c7150a7621c80": "Simlock 기기 호스트", "67937aa49179285e": "Mac에서 모든 파일을 쓰는 대신 T3 홈 폴더에 캐시된 체크아웃에서 새 워크트리를 복제합니다. 불가능하면 Git의 일반 체크아웃을 사용합니다. 끄면 캐시가 삭제됩니다.", "f9904f78d3003f58": "빠른 워크트리 체크아웃", + "9c2f647882522302": "선택한 컴퓨터의 에이전트 피드백 모드가 서로 다릅니다.", + "31bbf7bf8c0a5279": "에이전트 피드백", + "d52b3d6bf9f2a013": "혼합", "ec7623deed751c05": [ "브라우저에서 실시간으로 지켜보고 승인한 메시지를 보낼 수 있는 게스트와 스레드를 공유합니다. T3 Connect가 필요합니다. 로그인한 뒤", " ", @@ -8885,7 +8919,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 +9150,6 @@ "0b4779a1825c85bc": "사이드바와 스레드 목록에 표시되는 이 프로젝트 그룹의 공유 이름입니다.", "f68cbda4df83d739": "프로젝트 이름 기본값으로 재설정", "56e37b85027e8431": "프로젝트 아이콘", - "e88c9d8769544731": "자동", "c99736317da5b1fa": "프로젝트 아이콘 기본값으로 재설정", "6afaa3e3739dc570": "프로젝트 아이콘 선택", "51651ce45d481a20": "프로젝트 아이콘 파일 선택", @@ -10084,7 +10119,6 @@ "16bdc70b858c223f": "패널 미리 열기 기본값으로 재설정", "c5424f09d77138ff": "200,000 토큰이 넘는 유휴 Claude 스레드를 압축할 시점입니다. 돌아온 뒤, 프롬프트 캐시가 만료되기 직전, 또는 압축 안 함 중에서 선택합니다. 각 Claude 제공자에서 재정의할 수 있습니다.", "3e99c5c14f4939c8": "유휴 스레드 압축 기본값으로 재설정", - "d52b3d6bf9f2a013": "혼합", "cd72fe451ba0d6aa": "새 프로젝트", "394c3bd0a1782c8e": "프로젝트 추가 탐색기가 열릴 때 \"~/\"를 사용하려면 비워 두세요.", "f9b912a818bd869d": "프로젝트 추가 기본 디렉터리 기본값으로 재설정", @@ -10982,7 +11016,6 @@ "4a237f41ce592b7f": "직접 삭제할 때까지 이 프로젝트의 워크트리를 유지합니다.", "00b8ffd8ea6e6a93": "이 프로젝트에 이 규칙을 사용합니다.", "72c279824d15a999": "각 머신의 워크트리 정리 설정을 사용합니다.", - "90a258fff61fd77e": "끔", "b5702d0b64866b08": "사용자 지정", "c009c901f3eefe78": "삭제된 스레드의 워크트리 삭제", "431c7cd6d50102b7": "활성 또는 보관된 스레드가 삭제되면 사용하지 않는 워크트리를 제거합니다. 로컬 변경 사항이 있는 워크트리는 유지됩니다.", @@ -11674,7 +11707,6 @@ "4c70e3e7b3e6c493": "시크릿", "79b768229c9ef672": "유지 관리", "54b188d65247e42f": "실험 기능", - "f41ea186c275b56e": "정보", "af4b7734da1d5ce7": "음성", "4ec62c39ca3192bf": "소스 제어 및 이슈", "f2bf529f85e05494": "공유 및 액세스", @@ -11800,6 +11832,7 @@ "901a823214edc8c4": "원격 분석 분석 사용 데이터 추적 법적 옵트아웃", "82136480255a5106": "OTel OTLP 원격 분석 내보내기 엔드포인트 로그 추적 메트릭 Grafana", "659d081051faf7ff": "로그 추적 프로세스 리소스 기록 실패 스팬 cpu 메모리", + "5eaeacfa9f82051a": "보고 버그 문제 t3 팀 보내기 피드백 에이전트 도구 자동 내가 요청할 때", "f537f91e1ee41d47": "키보드 단축키 핫키 명령 바인딩 json", "1ba01e7ceed64b95": "창 캡처 스크린샷", "279b1cceb779ff38": "앱 텍스트 포함", @@ -12269,7 +12302,6 @@ "0bd41ff995d36a66": "캐시 읽기", "3f0dfe0cb15a3272": "캐시 쓰기", "1c9d860be42b1c02": "출력", - "78344b60f407928e": "기타", "684e516076de81fe": "표준", "3bbcc1b826fef537": "빠름", "66796576034c18ea": "초고속", @@ -12403,6 +12435,8 @@ "faa3bb26abb39c93": "검토 가이드 실패", "b7df38b7d8792d78": "가이드 열기", "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", - "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", - "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동" + "99d51127f573296b": "다른 계정", + "8ec2c57414669b79": "두 번째 {tracker} 워크스페이스 또는 사용자를 연결합니다.", + "99963c0142e17f00": "새 {tracker} 계정용입니다.", + "6d8e4ebc889bace9": "계정 추가" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5b2b9e2b9b381..9cc052192b4eb 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Instale o {fj} 0.6 ou posterior em {fjUrl} e execute {fjLogin}, ou instale o {tea} 0.16 ou posterior em {teaUrl} e execute {teaLogin} para cada servidor Forgejo ou Gitea.", "d026a85e2e50e675": "Instale a CLI do GitCafe com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", "22d3c0c48a34b5b3": "Instale a CLI do TanStack Source com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", + "756c80ad262ef315": "Aguardando na thread original", + "d8df14f9905f38eb": "Enviado", + "e7c59185f8ab3987": "Não enviada", + "b54ddec9084fa955": "Fechado sem enviar", + "fbaa7ab5da716e50": "Bug", + "01bac997ea55272e": "Confuso", + "0f53bc8f74dfe56a": "Funcionalidade ausente", + "055560f307e15e30": "Documentação incorreta", + "78344b60f407928e": "Outros", + "f653846a95cd6e8f": "Tipo", + "f41ea186c275b56e": "Sobre", + "2f6e4f7cd364da73": "Resultado esperado", + "9d11c93d4035de3e": "O que aconteceu", + "c87d0595693704f9": "Alternativa utilizada", + "d7a4ea6ce5af44e0": "{speaker} · {count} caracteres", + "f5114fb9c40fd929": "Você", + "cd03eb1b84271c02": "Agente", + "bfe1a60f3f9c60fb": "Turno {turn} · {what}", + "dfdaa6255a416140": "Resumo de {turns, plural, one {{turns} turno recente} other {{turns} turnos recentes}}, {textTurns, plural, =0 {sem texto das mensagens} one {com o texto das mensagens do último turno} other {com o texto das mensagens dos últimos {textTurns} turnos}}{truncated, select, yes {, encurtado para caber} other {}}", + "afac52a5cc2dc801": "Não foi possível enviar sua resposta. Tente novamente.", "79d776428f4d0650": "Não foi possível carregar o arquivo. Reconecte e tente novamente.", "3ea34cbb1ca5ba9b": "Pré-visualização cancelada.", "7c0af279ecb3da3a": "As pré-visualizações de arquivos por streaming não estão disponíveis neste runtime.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} ativado", "77cc5f738cb7d459": "{label} desativado", - "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", "aba3bb73ce212f0c": "Usar {names} requer {providerName} {version} ou mais recente, mas o cask claude-code do Homebrew só tem {latestVersion}. Mude para o cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", "d887bea446534de5": "Nenhum projeto neste ambiente consegue ler {host}/{repository}.", "4e466d60e2f7736b": "Cole a URL completa do pull request; esta thread não tem repositório para resolver o número.", "302625058bacbe38": "Cole uma URL completa; o host deste projeto não tem uma URL de {changeRequest} conhecida.", @@ -637,6 +657,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", @@ -2497,8 +2520,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}", @@ -2560,10 +2582,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Está em outra máquina, então o agente desta máquina não consegue lê-lo. Remova-o ou volte para enviar.", "5bbac0e5afeec779": "Thread atual", "33c7e68fca089036": "Thread, {title}", - "b4b98a0287c282e2": "Está em outra máquina, então o agente desta máquina não consegue lê-lo. Remova-o ou volte para enviar.", - "c6196d99000642b4": "Abrir thread", "34cc63390ad793cc": "Escolha uma thread", "8f12309ead62e38a": "Pesquisar threads ou projetos...", "2f664754d005d9a7": "Nenhuma thread ativa encontrada.", @@ -2573,6 +2594,7 @@ "a3178769f8308cbc": "A thread falhou", "89b5e8f3887812da": "Pedido de convidado", "62e626804919b294": "Resposta necessária", + "c6196d99000642b4": "Abrir thread", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Você:", "a1fbf2422c588292": "Agente:", @@ -2596,8 +2618,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Processo do terminal em execução", "fc2c9a91f498ad6b": "{count, plural, one {{count} processo do terminal em execução. Abrir terminal} other {{count} processos do terminal em execução. Abrir terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "pilha", "6831e9a46cbd8939": "cadeia", "9aa9e74a3b7eee91": "Adicionar ao chat", @@ -3034,8 +3054,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "A entrada de voz não tem um rascunho onde gravar.", "62450481c00d2ef3": "O ambiente do rascunho não está disponível para limpar a transcrição.", - "c64cb58d9cecbcd2": "Falha ao limpar a transcrição", "0674544195fcdc39": "A transcrição original foi adicionada.", + "c64cb58d9cecbcd2": "Falha ao limpar a transcrição", "296496693cdac0db": "O comando t3 não está disponível.", "efbcef7bc9bbda01": "Falha ao carregar o estado do comando t3.", "1bf6910332426e62": "O acesso à rede do desktop não está disponível.", @@ -3278,6 +3298,7 @@ "4d493d0bda4d403d": "Anexe novamente o arquivo interrompido ou remova-o", "c9cad1d84d5f1a32": "Anexe novamente os arquivos interrompidos ou remova-os", "536a820f2ff726da": "Selecione pelo menos um modelo.", + "48d6389202ad6754": "Enviando quando estiver pronto", "fbafbe78b5e37966": "Retomar thread", "bcd7eb979dd38dae": "Abrir o editor de mensagens para compactar e enviar", "95ee62a0d6968b89": "Enviar mensagem", @@ -3454,6 +3475,9 @@ "e778e4f446fdf873": "Sua próxima mensagem inicia uma nova sessão", "0e2f2da4f2d94785": "O agente não verá as mensagens anteriores desta thread.", "e1189d2e582b008d": "Manter a sessão atual", + "2bb448d605877a22": "Edite ou pressione Esc para cancelar", + "1a1f128d70c62304": "{count, plural, one {Enviando assim que a imagem estiver pronta} other {Enviando assim que {count} imagens estiverem prontas}}", + "5af3ab719a9725fb": "Enviando mensagem", "461c9f865f2e9b92": "{option} ativado", "f2aa17b5c620f2a4": "{option} desativado", "f59314a884aae1ff": "Padrão", @@ -3577,6 +3601,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.", @@ -3597,7 +3629,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", @@ -3693,7 +3724,6 @@ "7c1923203049d602": "Copiar código", "637817e4ff79c90e": "Ações do bloco de código", "ebf3a2b1e314aa5f": "Executar no terminal", - "fe219642547fa0bf": "Executar no terminal", "122a8512abc51180": "Detalhes", "58c38c65c2783c5d": "Caminho completo", "f37e7d36b51c5b28": "Copiar caminho relativo", @@ -3705,10 +3735,6 @@ "4967584e8d0fb1c2": "Pré-visualizar mídia", "67589dd912eacb7c": "Abrir no navegador integrado", "a3c98d4c4b24cecb": "Opções do arquivo {label}", - "b4fe8a076e9fd2f8": "Equação em destaque", - "085d1407e8c92cce": "Equação em linha", - "a2ef393fa7b48ae8": "Rolar a equação em destaque", - "e94685ea5642e088": "Rolar a equação em linha", "3a04583c8500e23d": "Mostrar diagrama", "16d64f650840fe06": "Mostrar código", "6d329f7d3a50c7e7": "Copiar tabela", @@ -3985,9 +4011,11 @@ "973e99fa86d7f531": "Mensagem {position} de {total} na fila, não enviada", "0f6087c4f53c7f17": "Iniciar um turno com esta mensagem ({shortcut})", "adab89933af02669": "Pular a compactação e enviar esta mensagem ({shortcut})", + "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", "3de4016452e8d2bd": "Enviar para o turno atual ({shortcut})", "259cc9568148e8ad": "Iniciar um turno com esta mensagem", "bb7fddb812d5d29e": "Pular a compactação e enviar esta mensagem", + "425ab15036aec8a4": "Mover este comando para o início da fila", "a5fe1ee609b29a9f": "Enviar para o turno atual", "2b7fd345e4f4fd6e": "Cancelar a edição da mensagem na fila", "47f1726bf106d2c8": "Editar mensagem na fila", @@ -5599,7 +5627,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 +5636,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 +5644,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 +5830,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 +8853,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)", @@ -8841,6 +8872,9 @@ "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 +8959,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 +9191,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 +10164,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 +11065,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 +11760,6 @@ "4c70e3e7b3e6c493": "Segredos", "79b768229c9ef672": "Manutenção", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Sobre", "af4b7734da1d5ce7": "Voz", "4ec62c39ca3192bf": "Versões e issues", "f2bf529f85e05494": "Compartilhamento", @@ -11853,6 +11885,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", @@ -12322,7 +12355,6 @@ "0bd41ff995d36a66": "Leitura de cache", "3f0dfe0cb15a3272": "Gravação de cache", "1c9d860be42b1c02": "Saída", - "78344b60f407928e": "Outros", "684e516076de81fe": "Padrão", "3bbcc1b826fef537": "Rápido", "66796576034c18ea": "Ultrarrápido", @@ -12459,6 +12491,8 @@ "faa3bb26abb39c93": "O guia de revisão falhou", "b7df38b7d8792d78": "Abrir guia", "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", - "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", - "425ab15036aec8a4": "Mover este comando para o início da fila" + "99d51127f573296b": "Outra conta", + "8ec2c57414669b79": "Conecte um segundo espaço de trabalho ou usuário do {tracker}.", + "99963c0142e17f00": "Para a nova conta do {tracker}.", + "6d8e4ebc889bace9": "Adicionar conta" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0ecadaba9ded1..1d8bc14fde51f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Установите {fj} 0.6 или новее с {fjUrl} и выполните {fjLogin} либо установите {tea} 0.16 или новее с {teaUrl} и выполните {teaLogin} для каждого сервера Forgejo или Gitea.", "d026a85e2e50e675": "Установите GitCafe CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", "22d3c0c48a34b5b3": "Установите TanStack Source CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", + "756c80ad262ef315": "Ожидание в исходном треде", + "d8df14f9905f38eb": "Отправлено", + "e7c59185f8ab3987": "Не отправлено", + "b54ddec9084fa955": "Закрыто без отправки", + "fbaa7ab5da716e50": "Ошибка", + "01bac997ea55272e": "Непонятное поведение", + "0f53bc8f74dfe56a": "Не хватает возможности", + "055560f307e15e30": "Ошибка в документации", + "78344b60f407928e": "Другое", + "f653846a95cd6e8f": "Тип", + "f41ea186c275b56e": "О приложении", + "2f6e4f7cd364da73": "Ожидалось", + "9d11c93d4035de3e": "Произошло", + "c87d0595693704f9": "Что сделано вместо этого", + "d7a4ea6ce5af44e0": "{speaker} · {count} симв.", + "f5114fb9c40fd929": "Вы", + "cd03eb1b84271c02": "Агент", + "bfe1a60f3f9c60fb": "Ход {turn} · {what}", + "dfdaa6255a416140": "Обзор {turns, plural, one {{turns} последнего хода} other {{turns} последних ходов}}, {textTurns, plural, =0 {без текста сообщений} =1 {с текстом сообщений последнего хода} one {с текстом сообщений последнего {textTurns} хода} other {с текстом сообщений последних {textTurns} ходов}}{truncated, select, yes {, сокращено до допустимого размера} other {}}", + "afac52a5cc2dc801": "Не удалось отправить ваш ответ. Попробуйте ещё раз.", "79d776428f4d0650": "Не удалось загрузить файл. Переподключитесь и попробуйте ещё раз.", "3ea34cbb1ca5ba9b": "Предпросмотр отменён.", "7c0af279ecb3da3a": "Потоковый предпросмотр файлов недоступен в этой среде выполнения.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Обычная", "f42c2a36b3507308": "{label}: вкл.", "77cc5f738cb7d459": "{label}: выкл.", - "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", "aba3bb73ce212f0c": "Для {names} нужен {providerName} {version} или новее, но в Homebrew cask claude-code есть только {latestVersion}. Перейдите на cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", "d887bea446534de5": "Ни один проект в этом окружении не может прочитать {host}/{repository}.", "4e466d60e2f7736b": "Вставьте полный URL пул-реквеста: у этого треда нет репозитория, по которому можно найти номер.", "302625058bacbe38": "Вставьте полный URL: для хоста этого проекта неизвестен формат URL {changeRequest}.", @@ -637,6 +657,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", @@ -2497,8 +2520,7 @@ "2d1c111e1b4ae0b0": "Удалить тред «{title}»?", "c568ab8dad798ec5": "История беседы этого треда будет удалена безвозвратно.", "0fd1c746a0e38003": "Не удалось удалить тред", - "0ecde875b0dd2f93": "Фильтр тредов по проекту: {projects}", - "1ef65b647231ff0b": "Фильтр тредов по проекту", + "1c8fc3c4a42949ab": "Проекты: {projects}", "165511761be2855c": "Поиск проектов", "a46a6467883575a4": "Поиск проектов...", "fdc0e086438a3045": "Настройки проекта {project}", @@ -2560,10 +2582,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", "5bbac0e5afeec779": "Текущий тред", "33c7e68fca089036": "Тред, {title}", - "b4b98a0287c282e2": "Находится на другой машине, поэтому агент этой машины не может его прочитать. Удалите его или переключитесь обратно, чтобы отправить.", - "c6196d99000642b4": "Открыть тред", "34cc63390ad793cc": "Выберите тред", "8f12309ead62e38a": "Поиск тредов или проектов...", "2f664754d005d9a7": "Активные треды не найдены.", @@ -2573,6 +2594,7 @@ "a3178769f8308cbc": "Ошибка в треде", "89b5e8f3887812da": "Запрос гостя", "62e626804919b294": "Нужен ввод", + "c6196d99000642b4": "Открыть тред", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Вы:", "a1fbf2422c588292": "Агент:", @@ -2596,8 +2618,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Процесс в терминале запущен", "fc2c9a91f498ad6b": "{count, plural, one {Запущен {count} процесс в терминале. Открыть терминал} few {Запущено {count} процесса в терминале. Открыть терминал} many {Запущено {count} процессов в терминале. Открыть терминал} other {Запущено {count} процесса в терминале. Открыть терминал}}", - "643c4b50feadc874": "Рабочее дерево: {path} ({branch})", - "fb7c44da0f0825ea": "Рабочее дерево: {path}", "56f37ff8ca568059": "стек", "6831e9a46cbd8939": "цепочка", "9aa9e74a3b7eee91": "Добавить в чат", @@ -3034,8 +3054,8 @@ "6f85f14f35b3f547": "{provider} через {environment}", "7c59a888a062a8bd": "Нет черновика для записи голосового ввода.", "62450481c00d2ef3": "Окружение черновика недоступно для очистки расшифровки.", - "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "0674544195fcdc39": "Добавлена исходная расшифровка.", + "c64cb58d9cecbcd2": "Не удалось очистить расшифровку", "296496693cdac0db": "Команда t3 недоступна.", "efbcef7bc9bbda01": "Не удалось загрузить состояние команды t3.", "1bf6910332426e62": "Сетевой доступ десктопа недоступен.", @@ -3278,6 +3298,7 @@ "4d493d0bda4d403d": "Прикрепите прерванный файл снова или удалите его", "c9cad1d84d5f1a32": "Прикрепите прерванные файлы снова или удалите их", "536a820f2ff726da": "Выберите хотя бы одну модель.", + "48d6389202ad6754": "Отправка по готовности", "fbafbe78b5e37966": "Возобновить тред", "bcd7eb979dd38dae": "Откройте поле ввода, чтобы сжать и отправить", "95ee62a0d6968b89": "Отправить сообщение", @@ -3454,6 +3475,9 @@ "e778e4f446fdf873": "Следующее сообщение начнёт новый сеанс", "0e2f2da4f2d94785": "Агент не увидит предыдущие сообщения этого треда.", "e1189d2e582b008d": "Оставить текущий сеанс", + "2bb448d605877a22": "Отредактируйте или нажмите Esc для отмены", + "1a1f128d70c62304": "{count, plural, one {Отправится, когда изображение будет готово} few {Отправится, когда {count} изображения будут готовы} many {Отправится, когда {count} изображений будут готовы} other {Отправится, когда {count} изображения будут готовы}}", + "5af3ab719a9725fb": "Отправка сообщения", "461c9f865f2e9b92": "{option}: вкл.", "f2aa17b5c620f2a4": "{option}: выкл.", "f59314a884aae1ff": "По умолчанию", @@ -3577,6 +3601,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": "Не удалось создать гостевую ссылку.", @@ -3597,7 +3629,6 @@ "abd89e9eefedf11b": "Готово", "18d166056c1ab6ff": "Прекратить общий доступ", "7a2d510eac9e4587": "Срок гостевой ссылки истёк", - "653405e4ed498d9f": "Отправить", "21888e302219891d": "Развёрнутый предпросмотр: {title}", "419719298a7acaea": "Уменьшить", "ed8d5db95359cff4": "Сбросить масштаб", @@ -3693,7 +3724,6 @@ "7c1923203049d602": "Копировать код", "637817e4ff79c90e": "Действия с блоком кода", "ebf3a2b1e314aa5f": "Выполнить в терминале", - "fe219642547fa0bf": "Выполнить в терминале", "122a8512abc51180": "Подробности", "58c38c65c2783c5d": "Полный путь", "f37e7d36b51c5b28": "Копировать относительный путь", @@ -3705,10 +3735,6 @@ "4967584e8d0fb1c2": "Предпросмотр медиа", "67589dd912eacb7c": "Открыть во встроенном браузере", "a3c98d4c4b24cecb": "Параметры файла {label}", - "b4fe8a076e9fd2f8": "Формула в отдельной строке", - "085d1407e8c92cce": "Формула в строке", - "a2ef393fa7b48ae8": "Прокрутить формулу", - "e94685ea5642e088": "Прокрутить формулу в строке", "3a04583c8500e23d": "Показать диаграмму", "16d64f650840fe06": "Показать код", "6d329f7d3a50c7e7": "Копировать таблицу", @@ -3985,9 +4011,11 @@ "973e99fa86d7f531": "Сообщение в очереди {position} из {total}, не отправлено", "0f6087c4f53c7f17": "Начать ход с этим сообщением ({shortcut})", "adab89933af02669": "Пропустить сжатие и отправить сообщение ({shortcut})", + "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", "3de4016452e8d2bd": "Отправить в текущий ход ({shortcut})", "259cc9568148e8ad": "Начать ход с этим сообщением", "bb7fddb812d5d29e": "Пропустить сжатие и отправить сообщение", + "425ab15036aec8a4": "Переместить эту команду в начало очереди", "a5fe1ee609b29a9f": "Отправить в текущий ход", "2b7fd345e4f4fd6e": "Отменить редактирование сообщения в очереди", "47f1726bf106d2c8": "Редактировать сообщение в очереди", @@ -5599,7 +5627,6 @@ }, ". Проверьте путь в ссылке или найдите файл в «Файлах»." ], - "b9b6bbd1e1ea189f": "Файл целиком", "d715e9494fdbaaf6": "Не удалось загрузить шрифт.", "ff17c777a72b4408": "Предпросмотр шрифтов ограничен 10 МБ.", "6bd41ad699e22f10": "Шрифт недоступен.", @@ -5609,6 +5636,7 @@ "a9abaaa4220eae21": "{error} Сохраните его, чтобы открыть в другом приложении.", "c508c9000d9656f8": "Предпросмотр шрифта", "1c416d621d250be8": "Съешь же ещё этих мягких французских булок, да выпей чаю.", + "d7d08260f16b7828": "Файл ещё загружается. Повторите попытку через мгновение.", "76ebb03de52c92d6": "Просмотрщик текста остановился.", "f48162e8e8c12af7": "Не удалось загрузить просмотрщик текста. Закройте файл и повторите попытку.", "bc4c5b13d38a5da7": "Предпросмотр закрыт.", @@ -5616,8 +5644,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 +5830,6 @@ "0061fff77e36bd4f": "Не удалось связаться с сервером.", "04dfdd46e3dd4a2e": "Что-то пошло не так. Повторите попытку.", "084bb2d8127a508d": "Отправлено", - "e7c59185f8ab3987": "Не отправлено", "77c01a15bd36d17c": "Срок действия ссылки истёк или она недействительна", "e0e736810f3cbef2": "Попросите владельца прислать новую ссылку. Каждая ссылка работает в одном браузере.", "c3c53aa46f7330e5": "Срок действия ссылки истёк", @@ -8830,6 +8855,12 @@ "d3866ead082d14e5": "Добавить сочетание клавиш", "d4345c90894a3220": "Открыть keybindings.json", "e56a8d51219efaa0": "Нет сочетаний клавиш по вашему запросу.", + "90a258fff61fd77e": "Выкл.", + "4060244a7079a0d2": "По моему запросу", + "e88c9d8769544731": "Автоматически", + "f29d1dade4dde8aa": "Агенты не отправляют обратную связь команде T3.", + "93c4c53562d30a98": "По вашему запросу агенты показывают краткий отчёт о T3 Code и с вашего одобрения отправляют его команде T3.", + "cd9ee803e8727017": "Агенты также сообщают о проблемах T3 Code, с которыми сталкиваются самостоятельно, например о сбое инструмента T3.", "45fa271ea0e1ac8e": "Бета", "3a678332fc7142f7": "Группирует треды боковой панели по папкам проектов. Закреплённые треды остаются наверху, а отложенные и разобранные — под папками.", "e4e91d155cb6a9b4": "Простая боковая панель (группировка по проектам)", @@ -8843,6 +8874,9 @@ "298c7150a7621c80": "Хосты устройств Simlock", "67937aa49179285e": "На Mac клонировать новые рабочие деревья из копии, закешированной в домашней папке T3, вместо записи каждого файла. Если это невозможно, используется обычный checkout Git. При выключении кеш удаляется.", "f9904f78d3003f58": "Быстрый checkout рабочих деревьев", + "9c2f647882522302": "На выбранных компьютерах используются разные режимы обратной связи от агентов.", + "31bbf7bf8c0a5279": "Обратная связь от агентов", + "d52b3d6bf9f2a013": "Разные", "ec7623deed751c05": [ "Поделитесь тредом с гостем: он смотрит его в браузере в реальном времени и отправляет сообщения, которые вы одобряете. Нужен T3 Connect: войдите и привяжите эту машину в разделе", " ", @@ -8926,7 +8960,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 +9192,6 @@ "0b4779a1825c85bc": "Общее название этой группы проектов на боковой панели и в списках тредов.", "f68cbda4df83d739": "Сбросить название проекта к значению по умолчанию", "56e37b85027e8431": "Значок проекта", - "e88c9d8769544731": "Автоматически", "c99736317da5b1fa": "Сбросить значок проекта к значению по умолчанию", "6afaa3e3739dc570": "Выберите значок проекта", "51651ce45d481a20": "Выберите файл значка проекта", @@ -10132,7 +10167,6 @@ "16bdc70b858c223f": "Сбросить заблаговременные панели к значению по умолчанию", "c5424f09d77138ff": "Когда сжимать неактивный тред Claude больше 200 000 токенов: после вашего возвращения, перед самым истечением его кеша промптов или никогда. Каждый провайдер Claude может это переопределить.", "3e99c5c14f4939c8": "Сбросить сжатие простаивающих тредов к значению по умолчанию", - "d52b3d6bf9f2a013": "Разные", "cd72fe451ba0d6aa": "Новые проекты", "394c3bd0a1782c8e": "Оставьте пустым, чтобы при открытии «Добавить проект» использовался «~/».", "f9b912a818bd869d": "Сбросить базовый каталог для добавления проектов к значению по умолчанию", @@ -11032,7 +11066,6 @@ "4a237f41ce592b7f": "Хранить рабочие деревья этого проекта, пока вы не удалите их вручную.", "00b8ffd8ea6e6a93": "Использовать эти правила для этого проекта.", "72c279824d15a999": "Использовать настройки очистки рабочих деревьев каждой машины.", - "90a258fff61fd77e": "Выкл.", "b5702d0b64866b08": "Свои", "c009c901f3eefe78": "Удалять рабочие деревья вместе с удалёнными тредами", "431c7cd6d50102b7": "Удалять неиспользуемые рабочие деревья при удалении активных или архивных тредов. Рабочие деревья с локальными изменениями сохраняются.", @@ -11728,7 +11761,6 @@ "4c70e3e7b3e6c493": "Секреты", "79b768229c9ef672": "Обслуживание", "54b188d65247e42f": "Эксперименты", - "f41ea186c275b56e": "О приложении", "af4b7734da1d5ce7": "Голос", "4ec62c39ca3192bf": "Контроль версий и issue", "f2bf529f85e05494": "Общий доступ", @@ -11854,6 +11886,7 @@ "901a823214edc8c4": "телеметрия аналитика данные об использовании отслеживание юридическое отказ", "82136480255a5106": "OTel OTLP телеметрия экспорт конечные точки логи трассировки метрики Grafana", "659d081051faf7ff": "логи трассировки процессы история ресурсов сбои спаны cpu память", + "5eaeacfa9f82051a": "отчёт ошибка проблема t3 команда отправить обратная связь агенты инструменты автоматически по моему запросу", "f537f91e1ee41d47": "сочетания клавиш горячие клавиши команды привязки json", "1ba01e7ceed64b95": "окно захват снимок экрана", "279b1cceb779ff38": "Включать текст приложения", @@ -12323,7 +12356,6 @@ "0bd41ff995d36a66": "Чтение кеша", "3f0dfe0cb15a3272": "Запись кеша", "1c9d860be42b1c02": "Вывод", - "78344b60f407928e": "Другое", "684e516076de81fe": "Стандартная", "3bbcc1b826fef537": "Быстрая", "66796576034c18ea": "Сверхбыстрая", @@ -12459,6 +12491,8 @@ "faa3bb26abb39c93": "Не удалось создать гид по ревью", "b7df38b7d8792d78": "Открыть гид", "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", - "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", - "425ab15036aec8a4": "Переместить эту команду в начало очереди" + "99d51127f573296b": "Другой аккаунт", + "8ec2c57414669b79": "Подключите второе рабочее пространство или пользователя {tracker}.", + "99963c0142e17f00": "Для нового аккаунта {tracker}.", + "6d8e4ebc889bace9": "Добавить аккаунт" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 1c01b1112768f..234479a1b2558 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "Installera {fj} 0.6 eller senare från {fjUrl} och kör {fjLogin}, eller installera {tea} 0.16 eller senare från {teaUrl} och kör {teaLogin} för varje Forgejo- eller Gitea-server.", "d026a85e2e50e675": "Installera GitCafe CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", "22d3c0c48a34b5b3": "Installera TanStack Source CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", + "756c80ad262ef315": "Väntar i den ursprungliga tråden", + "d8df14f9905f38eb": "Skickat", + "e7c59185f8ab3987": "Inte skickat", + "b54ddec9084fa955": "Stängd utan att skickas", + "fbaa7ab5da716e50": "Bugg", + "01bac997ea55272e": "Otydligt", + "0f53bc8f74dfe56a": "Funktion saknas", + "055560f307e15e30": "Fel i dokumentationen", + "78344b60f407928e": "Övrigt", + "f653846a95cd6e8f": "Typ", + "f41ea186c275b56e": "Om", + "2f6e4f7cd364da73": "Förväntat", + "9d11c93d4035de3e": "Vad som hände", + "c87d0595693704f9": "Gjorde i stället", + "d7a4ea6ce5af44e0": "{speaker} · {count} tecken", + "f5114fb9c40fd929": "Du", + "cd03eb1b84271c02": "Agent", + "bfe1a60f3f9c60fb": "Omgång {turn} · {what}", + "dfdaa6255a416140": "Översikt över {turns, plural, one {{turns} senaste omgång} other {{turns} senaste omgångar}}, {textTurns, plural, =0 {ingen meddelandetext} one {meddelandetext från den senaste omgången} other {meddelandetext från de senaste {textTurns} omgångarna}}{truncated, select, yes {, förkortad för att få plats} other {}}", + "afac52a5cc2dc801": "Det gick inte att skicka ditt svar. Försök igen.", "79d776428f4d0650": "Filen kunde inte läsas in. Återanslut och försök igen.", "3ea34cbb1ca5ba9b": "Förhandsvisningen avbröts.", "7c0af279ecb3da3a": "Strömmande förhandsvisning av filer är inte tillgänglig i den här körmiljön.", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} på", "77cc5f738cb7d459": "{label} av", - "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", "aba3bb73ce212f0c": "{names} kräver {providerName} {version} eller senare, men Homebrew-casken claude-code har bara {latestVersion}. Byt till casken claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", "d887bea446534de5": "Inget projekt i den här miljön kan läsa {host}/{repository}.", "4e466d60e2f7736b": "Klistra in hela pull request-URL:en; den här tråden har inget repo att slå upp numret i.", "302625058bacbe38": "Klistra in en fullständig URL; det här projektets värd har ingen känd URL för {changeRequest}.", @@ -637,6 +657,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", @@ -2497,8 +2520,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}", @@ -2560,10 +2582,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "Finns på en annan dator, så den här datorns agent kan inte läsa den. Ta bort den eller byt tillbaka för att skicka.", "5bbac0e5afeec779": "Aktuell tråd", "33c7e68fca089036": "Tråd, {title}", - "b4b98a0287c282e2": "Finns på en annan dator, så den här datorns agent kan inte läsa den. Ta bort den eller byt tillbaka för att skicka.", - "c6196d99000642b4": "Öppna tråd", "34cc63390ad793cc": "Välj en tråd", "8f12309ead62e38a": "Sök trådar eller projekt...", "2f664754d005d9a7": "Inga aktiva trådar hittades.", @@ -2573,6 +2594,7 @@ "a3178769f8308cbc": "Tråden misslyckades", "89b5e8f3887812da": "Gästbegäran", "62e626804919b294": "Input behövs", + "c6196d99000642b4": "Öppna tråd", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "Du:", "a1fbf2422c588292": "Agent:", @@ -2596,8 +2618,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminalprocess körs", "fc2c9a91f498ad6b": "{count, plural, one {{count} terminalprocess körs. Öppna terminalen} other {{count} terminalprocesser körs. Öppna terminalen}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "stack", "6831e9a46cbd8939": "kedja", "9aa9e74a3b7eee91": "Lägg till i chatten", @@ -3034,8 +3054,8 @@ "6f85f14f35b3f547": "{provider} via {environment}", "7c59a888a062a8bd": "Röstinmatningen har inget utkast att spela in i.", "62450481c00d2ef3": "Utkastets miljö är inte tillgänglig för att städa transkriptionen.", - "c64cb58d9cecbcd2": "Det gick inte att städa transkriptionen", "0674544195fcdc39": "Den ursprungliga transkriptionen lades till.", + "c64cb58d9cecbcd2": "Det gick inte att städa transkriptionen", "296496693cdac0db": "Kommandot t3 är inte tillgängligt.", "efbcef7bc9bbda01": "Det gick inte att läsa in statusen för kommandot t3.", "1bf6910332426e62": "Skrivbordsappens nätverksåtkomst är inte tillgänglig.", @@ -3278,6 +3298,7 @@ "4d493d0bda4d403d": "Bifoga den avbrutna filen igen eller ta bort den", "c9cad1d84d5f1a32": "Bifoga de avbrutna filerna igen eller ta bort dem", "536a820f2ff726da": "Välj minst en modell.", + "48d6389202ad6754": "Skickar när det är klart", "fbafbe78b5e37966": "Återuppta tråd", "bcd7eb979dd38dae": "Öppna inmatningsfältet för att komprimera och skicka", "95ee62a0d6968b89": "Skicka meddelande", @@ -3454,6 +3475,9 @@ "e778e4f446fdf873": "Ditt nästa meddelande startar en ny session", "0e2f2da4f2d94785": "Agenten ser inte tidigare meddelanden i den här tråden.", "e1189d2e582b008d": "Behåll den aktuella sessionen", + "2bb448d605877a22": "Redigera eller tryck Esc för att avbryta", + "1a1f128d70c62304": "{count, plural, one {Skickas när bilden är klar} other {Skickas när {count} bilder är klara}}", + "5af3ab719a9725fb": "Skickar meddelande", "461c9f865f2e9b92": "{option} på", "f2aa17b5c620f2a4": "{option} av", "f59314a884aae1ff": "Standard", @@ -3577,6 +3601,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.", @@ -3597,7 +3629,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", @@ -3693,7 +3724,6 @@ "7c1923203049d602": "Kopiera kod", "637817e4ff79c90e": "Åtgärder för kodblock", "ebf3a2b1e314aa5f": "Kör i terminalen", - "fe219642547fa0bf": "Kör i terminalen", "122a8512abc51180": "Detaljer", "58c38c65c2783c5d": "Fullständig sökväg", "f37e7d36b51c5b28": "Kopiera relativ sökväg", @@ -3705,10 +3735,6 @@ "4967584e8d0fb1c2": "Förhandsvisa media", "67589dd912eacb7c": "Öppna i den integrerade webbläsaren", "a3c98d4c4b24cecb": "Filalternativ för {label}", - "b4fe8a076e9fd2f8": "Fristående ekvation", - "085d1407e8c92cce": "Ekvation i texten", - "a2ef393fa7b48ae8": "Rulla fristående ekvation", - "e94685ea5642e088": "Rulla ekvation i texten", "3a04583c8500e23d": "Visa diagram", "16d64f650840fe06": "Visa kod", "6d329f7d3a50c7e7": "Kopiera tabell", @@ -3985,9 +4011,11 @@ "973e99fa86d7f531": "Köat meddelande {position} av {total}, inte skickat", "0f6087c4f53c7f17": "Starta en omgång med det här meddelandet ({shortcut})", "adab89933af02669": "Hoppa över komprimering och skicka det här meddelandet ({shortcut})", + "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", "3de4016452e8d2bd": "Skicka in i den aktuella omgången ({shortcut})", "259cc9568148e8ad": "Starta en omgång med det här meddelandet", "bb7fddb812d5d29e": "Hoppa över komprimering och skicka det här meddelandet", + "425ab15036aec8a4": "Flytta det här kommandot först i kön", "a5fe1ee609b29a9f": "Skicka in i den aktuella omgången", "2b7fd345e4f4fd6e": "Avbryt redigering av köat meddelande", "47f1726bf106d2c8": "Redigera köat meddelande", @@ -5600,7 +5628,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 +5637,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 +5645,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 +5831,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 +8861,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)", @@ -8849,6 +8880,9 @@ "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 +8966,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 +9197,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", @@ -10137,7 +10172,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 +11073,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 +11768,6 @@ "4c70e3e7b3e6c493": "Hemligheter", "79b768229c9ef672": "Underhåll", "54b188d65247e42f": "Labs", - "f41ea186c275b56e": "Om", "af4b7734da1d5ce7": "Röst", "4ec62c39ca3192bf": "Versioner och ärenden", "f2bf529f85e05494": "Delning och åtkomst", @@ -11861,6 +11893,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", @@ -12330,7 +12363,6 @@ "0bd41ff995d36a66": "Cacheläsning", "3f0dfe0cb15a3272": "Cacheskrivning", "1c9d860be42b1c02": "Utdata", - "78344b60f407928e": "Övrigt", "684e516076de81fe": "Standard", "3bbcc1b826fef537": "Snabb", "66796576034c18ea": "Ultrasnabb", @@ -12466,6 +12498,8 @@ "faa3bb26abb39c93": "Granskningsguiden misslyckades", "b7df38b7d8792d78": "Öppna guiden", "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", - "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", - "425ab15036aec8a4": "Flytta det här kommandot först i kön" + "99d51127f573296b": "Ett konto till", + "8ec2c57414669b79": "Anslut en andra {tracker}-arbetsyta eller användare.", + "99963c0142e17f00": "För det nya {tracker}-kontot.", + "6d8e4ebc889bace9": "Lägg till konto" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 43790340d1167..19eff455a318c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -52,6 +52,26 @@ "eb0f60ef4f92ab7d": "请从 {fjUrl} 安装 {fj} 0.6 或更高版本并运行 {fjLogin},或从 {teaUrl} 安装 {tea} 0.16 或更高版本,并为每个 Forgejo 或 Gitea 服务器运行 {teaLogin}。", "d026a85e2e50e675": "请使用 {install} 安装 GitCafe CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", "22d3c0c48a34b5b3": "请使用 {install} 安装 TanStack Source CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", + "756c80ad262ef315": "正在原始对话中等待", + "d8df14f9905f38eb": "已发送", + "e7c59185f8ab3987": "未发送", + "b54ddec9084fa955": "已关闭,未发送", + "fbaa7ab5da716e50": "错误", + "01bac997ea55272e": "难以理解", + "0f53bc8f74dfe56a": "缺少功能", + "055560f307e15e30": "文档有误", + "78344b60f407928e": "其他", + "f653846a95cd6e8f": "类型", + "f41ea186c275b56e": "关于", + "2f6e4f7cd364da73": "预期行为", + "9d11c93d4035de3e": "实际情况", + "c87d0595693704f9": "替代做法", + "d7a4ea6ce5af44e0": "{speaker} · {count} 个字符", + "f5114fb9c40fd929": "你", + "cd03eb1b84271c02": "智能体", + "bfe1a60f3f9c60fb": "第 {turn} 轮 · {what}", + "dfdaa6255a416140": "{turns, plural, one {最近 {turns} 轮的概要} other {最近 {turns} 轮的概要}},{textTurns, plural, =0 {不含消息文本} one {包含最后一轮的消息文本} other {包含最近 {textTurns} 轮的消息文本}}{truncated, select, yes {,已缩短以符合长度限制} other {}}", + "afac52a5cc2dc801": "无法发送你的回答。请重试。", "79d776428f4d0650": "无法加载文件。请重新连接后重试。", "3ea34cbb1ca5ba9b": "预览已取消。", "7c0af279ecb3da3a": "此运行时不支持流式文件预览。", @@ -118,9 +138,9 @@ "c4eb2b21c8c58a54": "普通", "f42c2a36b3507308": "{label} 开启", "77cc5f738cb7d459": "{label} 关闭", - "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", "aba3bb73ce212f0c": "使用 {names} 需要 {providerName} {version} 或更高版本,但 Homebrew 的 claude-code cask 只有 {latestVersion}。请切换到 claude-code@latest cask:{command}", + "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", + "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", "d887bea446534de5": "此环境中没有项目能读取 {host}/{repository}。", "4e466d60e2f7736b": "请粘贴完整的 pull request URL;此会话没有可用于解析编号的仓库。", "302625058bacbe38": "请粘贴完整 URL;此项目的托管平台没有已知的 {changeRequest} URL。", @@ -637,6 +657,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2501,8 +2524,7 @@ "2d1c111e1b4ae0b0": "删除会话“{title}”?", "c568ab8dad798ec5": "这将永久清除此会话的对话历史。", "0fd1c746a0e38003": "删除会话失败", - "0ecde875b0dd2f93": "按项目筛选会话:{projects}", - "1ef65b647231ff0b": "按项目筛选会话", + "1c8fc3c4a42949ab": "项目:{projects}", "165511761be2855c": "搜索项目", "a46a6467883575a4": "搜索项目…", "fdc0e086438a3045": "{project} 的项目设置", @@ -2564,10 +2586,9 @@ "v": "v" } ], + "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", "5bbac0e5afeec779": "当前会话", "33c7e68fca089036": "会话,{title}", - "b4b98a0287c282e2": "它在另一台机器上,本机的智能体读不到它。请移除它,或切回那台机器再发送。", - "c6196d99000642b4": "打开会话", "34cc63390ad793cc": "选择会话", "8f12309ead62e38a": "搜索会话或项目…", "2f664754d005d9a7": "未找到活动会话。", @@ -2577,6 +2598,7 @@ "a3178769f8308cbc": "会话失败", "89b5e8f3887812da": "访客请求", "62e626804919b294": "需要输入", + "c6196d99000642b4": "打开会话", "826cb862b4a11fb3": "{label}:", "3e597ec938e7551b": "你:", "a1fbf2422c588292": "智能体:", @@ -2600,8 +2622,6 @@ "3260b22f72f7effb": "{tooltipLead}:{title}", "feac8e54b30c5a03": "终端进程正在运行", "fc2c9a91f498ad6b": "{count, plural, other {{count} 个终端进程正在运行。打开终端}}", - "643c4b50feadc874": "工作树:{path}({branch})", - "fb7c44da0f0825ea": "工作树:{path}", "56f37ff8ca568059": "堆叠", "6831e9a46cbd8939": "链", "9aa9e74a3b7eee91": "添加到对话", @@ -3038,8 +3058,8 @@ "6f85f14f35b3f547": "{provider}(经由 {environment})", "7c59a888a062a8bd": "语音输入没有可录入的草稿。", "62450481c00d2ef3": "草稿所在环境不可用,无法整理转写内容。", - "c64cb58d9cecbcd2": "转写文本整理失败", "0674544195fcdc39": "已添加原始转写文本。", + "c64cb58d9cecbcd2": "转写文本整理失败", "296496693cdac0db": "t3 命令不可用。", "efbcef7bc9bbda01": "无法加载 t3 命令状态。", "1bf6910332426e62": "桌面网络访问不可用。", @@ -3282,6 +3302,7 @@ "4d493d0bda4d403d": "请重新添加中断的文件,或将其移除", "c9cad1d84d5f1a32": "请重新添加中断的文件,或将它们移除", "536a820f2ff726da": "请至少选择一个模型。", + "48d6389202ad6754": "就绪后发送", "fbafbe78b5e37966": "继续会话", "bcd7eb979dd38dae": "打开输入框以压缩并发送", "95ee62a0d6968b89": "发送消息", @@ -3459,6 +3480,9 @@ "e778e4f446fdf873": "你的下一条消息将以全新上下文开始", "0e2f2da4f2d94785": "智能体将看不到这个会话里之前的消息。", "e1189d2e582b008d": "保留当前上下文", + "2bb448d605877a22": "编辑或按 Esc 取消", + "1a1f128d70c62304": "{count, plural, other {图片就绪后发送}}", + "5af3ab719a9725fb": "正在发送消息", "461c9f865f2e9b92": "{option} 开启", "f2aa17b5c620f2a4": "{option} 关闭", "f59314a884aae1ff": "默认", @@ -3582,6 +3606,14 @@ "c53bc5a4b0314342": "下一个媒体", "2950b1424a3cddf5": "请重新连接这个环境,然后再打开媒体。", "ef638bf1479a5461": "环境返回了无效的媒体 URL。", + "3ccfbf7e86868c35": "给 T3 团队的反馈", + "4e0710d19dfc2e7e": "将这份报告发送给 T3 团队?", + "87d0ae0723ba75d1": "只有这些内容会从你的机器发送出去。点击“发送”前,不会发送任何内容。", + "bf19826f81484328": "包含对话", + "260c6b45f52d2f27": "添加你在最近 {textTurns} 轮中的消息和智能体回复的文本。", + "ddb7e6f8ce99e657": "只有能在这台机器上运行智能体的人,才能发送或拒绝这份报告。", + "03c1eb603c112f47": "不发送", + "653405e4ed498d9f": "发送", "262955d6eb632f9b": "复制访客链接时剪贴板 API 不可用。", "f1a4f2b04cdbb4ef": "无法将访客链接复制到剪贴板。", "cf3490a604e44d31": "无法创建访客链接。", @@ -3602,7 +3634,6 @@ "abd89e9eefedf11b": "完成", "18d166056c1ab6ff": "停止分享", "7a2d510eac9e4587": "访客链接已过期", - "653405e4ed498d9f": "发送", "21888e302219891d": "展开的 {title} 预览", "419719298a7acaea": "缩小", "ed8d5db95359cff4": "重置缩放", @@ -3698,7 +3729,6 @@ "7c1923203049d602": "复制代码", "637817e4ff79c90e": "代码块操作", "ebf3a2b1e314aa5f": "在终端中运行", - "fe219642547fa0bf": "在终端中运行", "122a8512abc51180": "详情", "58c38c65c2783c5d": "完整路径", "f37e7d36b51c5b28": "复制相对路径", @@ -3710,10 +3740,6 @@ "4967584e8d0fb1c2": "预览媒体", "67589dd912eacb7c": "在内置浏览器中打开", "a3c98d4c4b24cecb": "{label} 的文件选项", - "b4fe8a076e9fd2f8": "独立公式", - "085d1407e8c92cce": "行内公式", - "a2ef393fa7b48ae8": "滚动查看独立公式", - "e94685ea5642e088": "滚动查看行内公式", "3a04583c8500e23d": "显示图表", "16d64f650840fe06": "显示代码", "6d329f7d3a50c7e7": "复制表格", @@ -3990,9 +4016,11 @@ "973e99fa86d7f531": "排队消息 {position}/{total},尚未发送", "0f6087c4f53c7f17": "用此消息开始一个轮次 ({shortcut})", "adab89933af02669": "跳过压缩并发送此消息 ({shortcut})", + "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", "3de4016452e8d2bd": "发送到当前轮次 ({shortcut})", "259cc9568148e8ad": "用这条消息开始新一轮", "bb7fddb812d5d29e": "跳过压缩并发送这条消息", + "425ab15036aec8a4": "将此命令移到队列最前面", "a5fe1ee609b29a9f": "发送到当前这一轮", "2b7fd345e4f4fd6e": "取消编辑排队消息", "47f1726bf106d2c8": "编辑排队消息", @@ -5606,7 +5634,6 @@ }, "。请检查链接的路径,或在“文件”中找到该文件。" ], - "b9b6bbd1e1ea189f": "完整文件", "d715e9494fdbaaf6": "无法加载该字体。", "ff17c777a72b4408": "字体预览限制为 10 MB。", "6bd41ad699e22f10": "该字体不可用。", @@ -5616,6 +5643,7 @@ "a9abaaa4220eae21": "{error} 保存后可在其他应用中打开。", "c508c9000d9656f8": "字体预览", "1c416d621d250be8": "敏捷的棕色狐狸跳过了那只懒狗。", + "d7d08260f16b7828": "文件仍在加载中。请稍后重试。", "76ebb03de52c92d6": "文本查看器已停止。", "f48162e8e8c12af7": "无法加载文本查看器。请关闭文件后重试。", "bc4c5b13d38a5da7": "预览已关闭。", @@ -5623,8 +5651,6 @@ "9450d1827ef336a1": "另一个复制操作正在进行。", "8f48999eb6d9e2e3": "{count, plural, other {{formatted} 行}}", "13b14784f8707ddd": "0 字节", - "f6e9581cba3467fa": "正在建立索引…", - "2d1f293ac12463fc": "正在加载文件的其余部分…", "b75105bef8f564a4": "仅显示前 1,024 列。查看源码或保存文件时会保留所有列。", "2a6e1b1f209c3888": "此文件为空。", "192fc79eb3b5b2cb": "此图表包含资源 URL、标记、节点元数据或自定义配置。请显示 Mermaid 源码以安全查看。", @@ -5811,7 +5837,6 @@ "0061fff77e36bd4f": "无法连接到服务器。", "04dfdd46e3dd4a2e": "出了点问题。请重试。", "084bb2d8127a508d": "已发送", - "e7c59185f8ab3987": "未发送", "77c01a15bd36d17c": "此链接已结束或无效", "e0e736810f3cbef2": "请向所有者索取新链接。每个链接只能在一个浏览器中使用。", "c3c53aa46f7330e5": "此链接已结束", @@ -8846,6 +8871,12 @@ "d3866ead082d14e5": "添加快捷键", "d4345c90894a3220": "打开 keybindings.json", "e56a8d51219efaa0": "没有匹配的快捷键。", + "90a258fff61fd77e": "关闭", + "4060244a7079a0d2": "当我要求时", + "e88c9d8769544731": "自动", + "f29d1dade4dde8aa": "智能体不会向 T3 团队发送反馈。", + "93c4c53562d30a98": "当你要求时,智能体会向你展示一份关于 T3 Code 的简短报告,经你批准后发送给 T3 团队。", + "cd9ee803e8727017": "智能体还会主动报告自己遇到的 T3 Code 问题,例如 T3 工具运行失败。", "45fa271ea0e1ac8e": "测试版", "3a678332fc7142f7": "将侧边栏会话按项目文件夹分组。置顶会话保留在顶部,已暂缓和已收尾会话显示在文件夹下方。", "e4e91d155cb6a9b4": "简洁侧边栏(按项目分组)", @@ -8859,6 +8890,9 @@ "298c7150a7621c80": "Simlock 设备主机", "67937aa49179285e": "在 Mac 上,从缓存在 T3 主目录中的工作副本克隆新的工作树,无需逐个写入每个文件。无法使用时改为 Git 的常规检出。关闭后会删除缓存。", "f9904f78d3003f58": "快速创建工作树", + "9c2f647882522302": "所选机器使用的智能体反馈模式不同。", + "31bbf7bf8c0a5279": "智能体反馈", + "d52b3d6bf9f2a013": "各不相同", "ec7623deed751c05": [ "与访客共享会话,访客可在浏览器中实时观看并发送需经你批准的消息。需要 T3 Connect:请登录并在", " ", @@ -8942,7 +8976,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 +9208,6 @@ "0b4779a1825c85bc": "此项目组在侧边栏和会话列表中共用的名称。", "f68cbda4df83d739": "重置项目名称为默认值", "56e37b85027e8431": "项目图标", - "e88c9d8769544731": "自动", "c99736317da5b1fa": "重置项目图标为默认值", "6afaa3e3739dc570": "选择项目图标", "51651ce45d481a20": "选择项目图标文件", @@ -10145,7 +10180,6 @@ "16bdc70b858c223f": "重置主动面板为默认值", "c5424f09d77138ff": "空闲且超过 200,000 token 的 Claude 会话何时压缩:在你回来后、提示缓存即将过期前,或从不压缩。每个 Claude 提供方都可以单独覆盖此设置。", "3e99c5c14f4939c8": "重置压缩空闲会话为默认值", - "d52b3d6bf9f2a013": "各不相同", "cd72fe451ba0d6aa": "新项目", "394c3bd0a1782c8e": "留空时,“添加项目”浏览器从“~/”打开。", "f9b912a818bd869d": "重置添加项目基础目录为默认值", @@ -11053,7 +11087,6 @@ "4a237f41ce592b7f": "保留此项目的工作树,直到你手动删除。", "00b8ffd8ea6e6a93": "此项目使用以下规则。", "72c279824d15a999": "使用各机器的工作树清理设置。", - "90a258fff61fd77e": "关闭", "b5702d0b64866b08": "自定义", "c009c901f3eefe78": "删除会话时删除工作树", "431c7cd6d50102b7": "删除活跃或已归档会话时,移除不再使用的工作树。保留有本地改动的工作树。", @@ -11752,7 +11785,6 @@ "4c70e3e7b3e6c493": "凭据", "79b768229c9ef672": "维护", "54b188d65247e42f": "实验功能", - "f41ea186c275b56e": "关于", "af4b7734da1d5ce7": "语音", "4ec62c39ca3192bf": "版本控制与 issue", "f2bf529f85e05494": "共享与访问", @@ -11878,6 +11910,7 @@ "901a823214edc8c4": "遥测 分析 用量数据 跟踪 法律 退出", "82136480255a5106": "OTel OTLP 遥测 导出 端点 日志 追踪 指标 Grafana", "659d081051faf7ff": "日志 追踪 进程 资源历史 失败 span cpu 内存", + "5eaeacfa9f82051a": "报告 错误 问题 t3 团队 发送 反馈 智能体 工具 自动 当我要求时", "f537f91e1ee41d47": "键盘 快捷键 热键 命令 绑定 json", "1ba01e7ceed64b95": "窗口 捕获 截图", "279b1cceb779ff38": "包含应用文本", @@ -12348,7 +12381,6 @@ "0bd41ff995d36a66": "缓存读取", "3f0dfe0cb15a3272": "缓存写入", "1c9d860be42b1c02": "输出", - "78344b60f407928e": "其他", "684e516076de81fe": "标准", "3bbcc1b826fef537": "快速", "66796576034c18ea": "极速", @@ -12485,6 +12517,8 @@ "faa3bb26abb39c93": "审查导览生成失败", "b7df38b7d8792d78": "打开导览", "9e91e9a77b664e4e": "无法开始生成审查导览", - "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", - "425ab15036aec8a4": "将此命令移到队列最前面" + "99d51127f573296b": "其他账号", + "8ec2c57414669b79": "连接第二个 {tracker} 工作区或用户。", + "99963c0142e17f00": "用于新的 {tracker} 账号。", + "6d8e4ebc889bace9": "添加账号" } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4ba107059f2b7..2b19b90cc28e3 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -1887,10 +1887,6 @@ code { margin: 0.65rem 0; } -.chat-markdown-math-display .katex-display { - margin: 0; -} - :is(.chat-markdown, .composer-tiptap) h1, :is(.chat-markdown, .composer-tiptap) h2, :is(.chat-markdown, .composer-tiptap) h3, @@ -2312,6 +2308,15 @@ code { overflow-wrap: break-word; } +.chat-markdown [data-markdown-math] { + font-weight: normal; + font-style: normal; +} + +.chat-markdown [data-markdown-math] > svg { + font-size: 1.21em; +} + /* Formula cells keep their natural width and scroll with the table. */ .chat-markdown :is(th, td):has([data-markdown-math]) { max-width: none; diff --git a/apps/web/src/lib/chunkReloadGuard.ts b/apps/web/src/lib/chunkReloadGuard.ts index 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/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..51aeeade6863d 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -9,20 +9,12 @@ import { isElectron } from "./env"; import { startAppServices } from "./appInit"; import { AppRoot } from "./AppRoot"; import { whenLocaleReady } from "./i18n/runtime"; -import { reloadOnceForChunkLoadError } from "./lib/chunkReloadGuard"; +import { chunkLoadState } from "./lib/chunkReloadGuard"; const router = startAppServices(); const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined; -let reloadScheduled = false; -window.addEventListener("vite:preloadError", (event) => { - if (reloadOnceForChunkLoadError()) { - reloadScheduled = true; - event.preventDefault(); - } -}); - const app = ; // Split by runtime to keep Clerk out of local startup and clerk-js out of browser builds. @@ -40,7 +32,7 @@ export const startup = Promise.all([ ]) .then(([ManagedAuthShell]) => { // Route chunk failures resolve router.load() and surface later through the error boundary. - if (reloadScheduled) return; + if (chunkLoadState.reloadScheduled) return; ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( {ManagedAuthShell && clerkPublishableKey ? ( @@ -52,6 +44,6 @@ export const startup = Promise.all([ ); }) .catch((error: unknown) => { - if (reloadScheduled) return; + if (chunkLoadState.reloadScheduled) return; throw error; }); diff --git a/apps/web/src/markdown-clipboard.test.ts b/apps/web/src/markdown-clipboard.test.ts index 1b0aa804a8437..7a50785c726c7 100644 --- a/apps/web/src/markdown-clipboard.test.ts +++ b/apps/web/src/markdown-clipboard.test.ts @@ -11,19 +11,27 @@ import { collectAssistantCitations, serializeAssistantCitation, } from "@t3tools/shared/assistantCitations"; -import { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath"; +import type { Element as HastElement, ElementContent, Root } from "hast"; -import { unified } from "unified"; -import remarkParse from "remark-parse"; -import { - CHAT_MARKDOWN_REMARK_PLUGINS, - CHAT_USER_MARKDOWN_REMARK_PLUGINS, -} from "@t3tools/shared/markdownPipeline"; +import { markdownTree } from "./markdown/wordsHast"; -const userMarkdown = unified() - .use(remarkParse) - .use(CHAT_MARKDOWN_REMARK_PLUGINS) - .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS); +// Copied Markdown read back as the chat reads it, to check it says what was copied. +const elementsOf = (node: Root | HastElement) => + (node.children as ElementContent[]).filter( + (child): child is HastElement => child.type === "element", + ); +const textOf = (node: ElementContent): string => + node.type === "text" + ? node.value + : node.type === "element" + ? node.children.map(textOf).join("") + : ""; +const readBack = (markdown: string, options?: Parameters[1]) => + elementsOf(markdownTree(markdown, options))[0]!; +// A user message's reading: a single `~` stays text. +const readUserBack = (markdown: string) => readBack(markdown, { singleTilde: false }); +const inline = (node: ElementContent) => + node.type === "element" ? [node.tagName, textOf(node)] : [node.type, textOf(node)]; const TEXT_NODE = 3; const ELEMENT_NODE = 1; @@ -223,10 +231,10 @@ describe("serializeRenderedMarkdownFragment", () => { new FakeText(" here."), ), ); - const paragraph = parseMarkdownWithMath(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children.find((child) => child.type === "inlineCode")?.value).toBe(value); + const paragraph = readBack(serializeRenderedMarkdownFragment(asNode(container))); + const code = elementsOf(paragraph).find((child) => child.tagName === "code"); + expect(paragraph.tagName).toBe("p"); + expect(code && textOf(code)).toBe(value); }); it.each([ @@ -238,28 +246,24 @@ describe("serializeRenderedMarkdownFragment", () => { String.raw`before\ after\ end`, ])("copies prose that parses back unchanged: %s", (value) => { const container = new FakeElement("DIV").append(new FakeText(value)); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ type: "paragraph", children: [{ type: "text", value }] }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.tagName).toBe("p"); + expect(paragraph.children.map(inline)).toEqual([["text", value]]); }); it.each([ - ["*", "EM", "word", "emphasis"], - ["\\", "CODE", "value", "inlineCode"], - ])("keeps a text edge %j beside %s", (edge, tag, value, type) => { + ["*", "EM", "word"], + ["\\", "CODE", "value"], + ])("keeps a text edge %j beside %s", (edge, tag, value) => { const container = new FakeElement("DIV").append( new FakeText(edge), new FakeElement(tag).append(new FakeText(value)), ); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - expect(paragraph).toMatchObject({ - type: "paragraph", - children: [ - { type: "text", value: edge }, - type === "inlineCode" ? { type, value } : { type, children: [{ type: "text", value }] }, - ], - }); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect(paragraph.children.map(inline)).toEqual([ + ["text", edge], + [tag.toLowerCase(), value], + ]); }); it("copies email links with their address and drops in-app destinations", () => { @@ -288,10 +292,10 @@ describe("serializeRenderedMarkdownFragment", () => { expect(copied).toBe( "Write to support@example.com, [Support](mailto:support@example.com?subject=Help), [Support](mailto:support@example.com?subject=Help\\)) or the thread.", ); - const paragraph = parseMarkdownWithMath(copied).children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); expect( - paragraph.children.filter((child) => child.type === "link").map((link) => link.url), + elementsOf(readBack(copied)) + .filter((child) => child.tagName === "a") + .map((link) => link.properties.href), ).toEqual([ "mailto:support@example.com", "mailto:support@example.com?subject=Help", @@ -312,12 +316,14 @@ describe("serializeRenderedMarkdownFragment", () => { ])("keeps the link label and destination: %s", (label, href) => { const anchor = new FakeElement("A", [], { href }).append(new FakeText(label)); const container = new FakeElement("DIV").append(anchor); - const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container))) - .children[0]; - if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); - expect(paragraph.children).toMatchObject([ - { type: "link", url: href, children: [{ type: "text", value: label }] }, - ]); + const paragraph = readUserBack(serializeRenderedMarkdownFragment(asNode(container))); + expect( + paragraph.children.map((child) => + child.type === "element" + ? [child.tagName, decodeURI(String(child.properties.href)), textOf(child)] + : [child.type, textOf(child)], + ), + ).toEqual([["a", href, label]]); }); it("copies alert and insight callouts as their Markdown instead of the rendered label", () => { @@ -484,31 +490,25 @@ describe("copying rendered Markdown tables", () => { ); const markdown = serializeTableElementToMarkdown(table as unknown as Element); - const tree = parseMarkdownWithMath(markdown); - const parsed = tree.children[0]; - if (parsed?.type !== "table") throw new Error("Expected a table"); - expect(parsed.children.map((row) => row.children.length)).toEqual([2, 2, 2, 2, 2]); - expect(markdownMathRanges(markdown, tree).map((formula) => formula.tex)).toEqual([ - "|x|", - "\\|x\\|", - "|y|", - "|z|", - ]); - expect(parsed.children[1]?.children[1]?.children).toMatchObject([ - { type: "text", value: "*a* | ~~b~~" }, - ]); - expect(parsed.children[4]?.children[1]?.children).toMatchObject([ - { type: "text", value: "> c | d" }, - ]); - const [, , codeRow, linkRow] = parsed.children; - expect(codeRow?.children[1]?.children[0]).toMatchObject({ - type: "inlineCode", - value: "\\(c|d\\)", - }); - expect(linkRow?.children[0]?.children[0]).toMatchObject({ - type: "link", - url: "https://example.com/?q=a|b", - }); + const parsed = readBack(markdown, { math: true }); + expect(parsed.tagName).toBe("table"); + const rows = elementsOf(parsed).flatMap((section) => elementsOf(section)); + const cells = rows.map((row) => elementsOf(row)); + expect(cells.map((row) => row.length)).toEqual([2, 2, 2, 2, 2]); + const formulas: string[] = []; + const visit = (node: HastElement) => { + if (node.tagName === "svg") formulas.push(String(node.properties.ariaLabel)); + else elementsOf(node).forEach(visit); + }; + visit(parsed); + expect(formulas).toEqual(["|x|", "\\|x\\|", "|y|", "|z|"]); + expect(textOf(cells[1]![1]!)).toBe("*a* | ~~b~~"); + expect(textOf(cells[4]![1]!).trim()).toBe("> c | d"); + expect(inline(cells[2]![1]!.children[0]!)).toEqual(["code", "\\(c|d\\)"]); + const link = cells[3]![0]!.children[0]!; + expect(link.type === "element" && decodeURI(String(link.properties.href))).toBe( + "https://example.com/?q=a|b", + ); }); it("copies code and diagrams in cells without markers or unescaped pipes", () => { diff --git a/apps/web/src/markdown-clipboard.ts b/apps/web/src/markdown-clipboard.ts index 7421dbadd4bae..39ef90b2ec19a 100644 --- a/apps/web/src/markdown-clipboard.ts +++ b/apps/web/src/markdown-clipboard.ts @@ -1,4 +1,4 @@ -import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownWindowsPaths"; +import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownLinks"; const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]); const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"]; @@ -428,7 +428,7 @@ export function serializeTableElementToMarkdown(table: Element): string { return serializeTable(table).replaceAll(CODE_BOUNDARY, "").trim(); } -// The wrapper MarkdownMath puts on every formula it renders. The sanitizer drops +// The wrapper wordsHast puts on every formula it renders. The sanitizer drops // the attribute from authored HTML. const MATH_SELECTOR = "[data-markdown-math]"; diff --git a/apps/web/src/markdown-incremental.test.tsx b/apps/web/src/markdown-incremental.test.tsx deleted file mode 100644 index 3682deb281fa9..0000000000000 --- a/apps/web/src/markdown-incremental.test.tsx +++ /dev/null @@ -1,135 +0,0 @@ -import { CHAT_MARKDOWN_REHYPE_PLUGINS } from "@t3tools/shared/markdownPipeline"; -import type { Root } from "mdast"; -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; -import remarkGfm from "remark-gfm"; -import type { Plugin } from "unified"; -import { describe, expect, it } from "vite-plus/test"; - -import { remarkCodexDirectives } from "@t3tools/shared/codexMarkdownDirectives"; -import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts"; -import { createIncrementalMarkdownPlugin } from "./markdown-incremental"; -import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation"; - -function render(source: string, incremental?: Plugin<[], Root>, parsedSources?: string[]) { - let tree: Root | undefined; - const observeParsing: Plugin<[], Root> = function () { - const original = this.parser; - if (original) { - this.parser = (text, file) => { - parsedSources?.push(text); - return original(text, file); - }; - } - }; - const capture: Plugin<[], Root> = () => (root) => { - tree = structuredClone(root); - }; - const html = renderToStaticMarkup( - - {source} - , - ); - return { html, tree }; -} - -const prefix = "# Before\n\n```ts\nconst values = [1, 2];\n```\n\n"; - -describe("incremental Markdown parsing", () => { - it("keeps the document prefix cached when list recovery parses contain fences", () => { - const source = - prefix + - "- first block\n\n ```ts\n const nested = 1;\n ```\n\n tail"; - const incremental = createIncrementalMarkdownPlugin(); - const parsedSources: string[] = []; - expect(render(source, incremental, parsedSources)).toEqual(render(source)); - parsedSources.length = 0; - const next = source + " more"; - expect(render(next, incremental, parsedSources)).toEqual(render(next)); - expect(parsedSources).not.toContain(next); - expect(parsedSources.some((text) => text.startsWith("t3-markdown-inline-prefix:"))).toBe(true); - }); - - it.each([ - "a\n===\n\nb\n---\n", - "- first\n\n continued\n\n- next\n", - "> quoted\n>\n> ```js\n> abc\n> ```\n\nend", - "
\nhello\n\n
\n\nend", - "[ref]\n\n[ref]: /later", - "a[^x]\n\n[^x]: note", - "a | b\n--|--\na | b\n", - "```\na\n```\n\nnext\n\n~~~\nb\n~~~\n\nmore", - "\n\n\tcode\n\nmore", - "text *bold*", - "> [!NOTE]\n> alert\n\n- [ ] task", - "\uFEFFtext after a byte-order mark", - ])("preserves the parse tree, positions, and HTML while streaming %j", (tail) => { - const source = prefix + tail; - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental), `prefix ${end}`).toEqual(render(text)); - } - }); - - it.each(["\r\n", "\r"])("preserves partial %j line endings", (newline) => { - const source = (prefix + "next\n\n```\nlast\n```\n\nend").replaceAll("\n", newline); - const incremental = createIncrementalMarkdownPlugin(); - for (let end = 0; end <= source.length; end++) { - const text = source.slice(0, end); - expect(render(text, incremental)).toEqual(render(text)); - } - }); - - it("updates earlier references when definitions arrive after the cached prefix", () => { - const before = "[later] and footnote[^note]\n\n" + prefix; - const incremental = createIncrementalMarkdownPlugin(); - for (const tail of ["text", "[later]: /target", "[later]: /target\n\n[^note]: a note"]) { - expect(render(before + tail, incremental)).toEqual(render(before + tail)); - } - }); - - it("handles edits, replacements, and repeated renders without leaking transformed nodes", () => { - const incremental = createIncrementalMarkdownPlugin(); - const documents = [ - prefix + "- first\n - second", - prefix + "> [!NOTE]\n> transformed alert", - prefix + "plain text", - "replacement without fences", - prefix.replace("Before", "Edited") + "edited prefix", - prefix + "plain text", - prefix + "plain text", - ]; - for (const document of documents) { - expect(render(document, incremental)).toEqual(render(document)); - } - }); - - it("does not freeze unclosed, nested, indented, or mismatched fences", () => { - const prefixes = [ - "```\nopen\n\n", - "````\n```\n\n", - "> ```\n> code\n> ```\n\n", - "- ```\n code\n ```\n\n", - " ```\n code\n ```\n\n", - " $y$', + { ...ASSISTANT, math: true }, + ), + ); + expect(html).not.toMatch(/onload|javascript|position| ReadonlyArray) | null; + }; + /** Expand GitHub `:alias:` emoji shortcodes in prose outside code. */ + readonly githubEmoji?: boolean; +} + +export interface WordsHastOptions { + /** `$…$`, `$$…$$` and `math` code blocks render as SVG. */ + readonly math: boolean; + /** Soft line breaks render as `
`, as remark-breaks does. */ + readonly breaks: boolean; + /** Raw HTML shows as the text it was written as. */ + readonly escapeHtml: boolean; + /** `★ Insight ───` blocks render as insight callouts. */ + readonly insights: boolean; + readonly extensions: MarkdownExtensions; +} + +const CODEX_DIRECTIVES = ["codex-file-citation", "codex-followup", "artifact-template"]; + +const VOID = new Set("area base br col embed hr img input link meta source track wbr".split(" ")); + +const TAG = + /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|)|]*>|<\?[\s\S]*?\?>/g; +const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g; + +// Start tags an HTML parser closes an open `

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

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

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

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

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

  • `, loose ones inside its first `

    `. + const checkbox = isElement(child.children[0], "input") + ? child.children[0] + : isElement(firstBlock, "p") && isElement(firstBlock.children[0], "input") + ? firstBlock.children[0] + : undefined; + if (checkbox) { + props.className = ["task-list-item"]; + const { checked } = checkbox.properties; + checkbox.properties = { type: "checkbox", checked, disabled: true }; + if (node.type === "element") node.properties.className = ["contains-task-list"]; + } + breakLines(child, walk.options.breaks); + } else if (tagName === "p") { + breakLines(child, walk.options.breaks); + } else if (tagName === "blockquote") { + // remarkGithubAlerts + const paragraph = child.children.find((item) => item.type === "element"); + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + const text = first?.type === "text" ? first.value : ""; + const insight = walk.insightMarker?.exec(text); + const alert = GITHUB_ALERT_MARKER.exec(text); + // An alert marker followed by more inline content on its line is text, as remarkGithubAlerts reads it. + const match = insight + ? ([insight[0], "insight"] as const) + : alert && (alert[0].endsWith("\n") || (paragraph as Element).children.length === 1) + ? alert + : null; + if (match && first?.type === "text" && isElement(paragraph, "p")) { + first.value = first.value.slice(match[0].length); + if (first.value === "") paragraph.children.shift(); + if (paragraph.children.length === 0) { + const at = child.children.indexOf(paragraph); + const next = child.children[at + 1]; + // The line ending after it goes too, as remark leaves none for a removed paragraph. + const blank = next?.type === "text" && next.value.trim() === "" ? 2 : 1; + child.children.splice(at, blank); + } + props.dataAlert = match[1]!.toLowerCase(); + } + } + transform( + child, + walk, + inLink || tagName === "a", + inCode || tagName === "code" || tagName === "pre", + ); + } +} + +/** + * remark-breaks puts a `
    ` before every soft line ending, and remarkBreakAroundImageLines + * before those next to a Markdown image. Both keep the line ending after it. + */ +/** A Markdown image alone on its line: nothing but a line ending (or the paragraph's edge) around it. */ +function imageOwnsLine(items: ElementContent[], at: number): boolean { + if (!isMarkdownImage(items[at])) return false; + const before = items[at - 1]; + const after = items[at + 1]; + const startsLine = + before === undefined || + (before.type === "text" && /\n[ \t]*$/.test(before.value)) || + isElement(before, "br"); + const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value)); + return startsLine && endsLine; +} + +const isBlockElement = (node: ElementContent | undefined) => + node?.type === "element" && CLOSES_PARAGRAPH.has(node.tagName); + +function breakLines(paragraph: Element, breaks: boolean) { + const items = paragraph.children; + for (let at = 0; at < items.length; at++) { + const item = items[at]!; + if ( + item.type === "element" && + breaks && + item.tagName !== "code" && + !CLOSES_PARAGRAPH.has(item.tagName) + ) { + breakLines(item, breaks); + } + if (item.type !== "text" || !item.value.includes("\n")) continue; + const afterImage = imageOwnsLine(items, at - 1); + const beforeImage = imageOwnsLine(items, at + 1); + const afterBlock = isBlockElement(items[at - 1]) || (at === 0 && paragraph.tagName === "li"); + const beforeBlock = + isBlockElement(items[at + 1]) || (at === items.length - 1 && paragraph.tagName === "li"); + const lines = item.value.split("\n"); + const parts: ElementContent[] = []; + lines.forEach((line, index) => { + // A hard break's own line ending follows its
    , and adds no second one; + // structural line endings around a list item's block children stay breaks between blocks. + const afterHardBreak = index === 1 && isElement(items[at - 1], "br"); + const blockBoundary = + (index === 1 && lines[0] === "" && afterBlock) || + (index === lines.length - 1 && line === "" && beforeBlock); + const breaksHere = + index > 0 && + !afterHardBreak && + !blockBoundary && + (breaks || (index === 1 && afterImage) || (index === lines.length - 1 && beforeImage)); + if (index > 0) { + if (breaksHere) { + const previous = parts.at(-1); + if (previous?.type === "text") previous.value = previous.value.replace(/[ \t]+$/, ""); + parts.push(BREAK); + } + parts.push({ type: "text", value: `\n${line}` }); + } else if (line) { + parts.push({ type: "text", value: line }); + } + }); + // Rejoin text that did not break, so the tree matches remark's text nodes. + const merged: ElementContent[] = []; + for (const part of parts) { + const previous = merged.at(-1); + if (part.type === "text" && previous?.type === "text") previous.value += part.value; + else merged.push(part); + } + items.splice(at, 1, ...merged); + at += merged.length - 1; + } +} + +/** + * The wrapper copying reads (markdown-clipboard's MATH_SELECTOR): the formula's TeX, as the source + * Words drew it from, so copying any part of a formula copies the whole of it. + */ +// A formula wider than its block scrolls, with room for the glyphs that reach past its box; in a +// table it keeps its width and the table scrolls. +const MATH_SCROLL = [ + "max-w-full", + "overflow-x-auto", + "overflow-y-hidden", + "px-0.5", + "py-0.75", + "in-[.chat-markdown-table-container]:max-w-none", + "in-[.chat-markdown-table-container]:overflow-visible", +]; + +function mathWrapper(svg: Element): Element { + const tex = String(svg.properties.ariaLabel ?? "").trim(); + const display = /display:\s*block/.test(String(svg.properties.style ?? "")); + return { + type: "element", + tagName: "span", + properties: display + ? { + className: ["chat-markdown-math-display", "block", ...MATH_SCROLL], + dataMarkdownMath: "display", + dataMarkdownCopy: `\\[\n${tex}\n\\]\n\n`, + } + : { + className: ["inline-block", "align-middle", ...MATH_SCROLL], + dataMarkdownMath: "inline", + dataMarkdownCopy: `\\(${tex}\\)`, + }, + children: [svg], + }; +} + +function restoreMath(node: Root | Element, math: Map) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + const id = child.properties.id; + const svg = typeof id === "string" ? math.get(id.replace(/^user-content-/, "")) : undefined; + if (svg) children[index] = mathWrapper(svg); + else restoreMath(child, math); + } +} + +const addHeadingIds = rehypeHeadingIds(); +const addTextDirection = rehypeTextDirection(); +const preserveImageSourceMeta = rehypePreserveImageSourceMeta(); +const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks(); +const groupChipPunctuation = rehypeChipPunctuation(); + +const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u; +const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u; + +interface InsightSource { + readonly source: string; + readonly tree: Root; + readonly marker: RegExp; + /** The offset in the message for an offset in `source`. */ + readonly toOriginal: (offset: number) => number; +} + +/** + * remarkAssistantInsights: a `★ Insight ───` line opens a quoted insight block, which a `───` line + * at the same indentation closes; the end of the text closes one that never does. Lines in code + * neither open nor close one, and an opening Words does not read as a quote's first line, as in + * an HTML block or a quote's lazy line, stays text. + */ +function insightSource(text: string, options: RenderOptions): InsightSource | null { + if (!text.includes("★ Insight")) return null; + const code: Array = []; + const findCode = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "pre" && child.position) { + code.push([child.position.start.offset!, child.position.end.offset!]); + } else findCode(child); + } + }; + findCode(parse(text, options)); + const nonce = Math.random().toString(36).slice(2); + const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`); + const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g"); + const lines = text.split(/(?<=\n)/u); + const skipped = new Set(); + for (;;) { + // Each line's offset in the message and in the source, and how much longer it got. + const offsets: Array<{ original: number; source: number; length: number; delta: number }> = []; + let original = 0; + let rewritten = 0; + let opened = 0; + let indent: string | undefined; + const source = lines + .map((line, lineIndex) => { + const value = line.replace(/[\r\n]+$/u, ""); + const ending = line.slice(value.length); + const inCode = code.some(([start, end]) => original >= start && original < end); + let output = line; + if (indent === undefined) { + const opening = inCode ? null : INSIGHT_OPENING.exec(value); + if (opening && !skipped.has(lineIndex)) { + indent = opening[1] ?? ""; + opened++; + output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`; + } + } else { + const closing = inCode ? null : INSIGHT_CLOSING.exec(value); + if (closing && closing[1] === indent) { + indent = undefined; + output = ending; + } else output = `> ${line}`; + } + offsets.push({ + original, + source: rewritten, + length: line.length, + delta: output.length - line.length, + }); + original += line.length; + rewritten += output.length; + return output; + }) + .join(""); + if (opened === 0) return null; + const tree = parse(source, options); + let stranded = false; + const visit = (node: Root | Element, quoteStart: Text | undefined) => { + for (const child of node.children) { + if (child.type === "text") { + for (const found of child.value.matchAll(anywhere)) { + if (child === quoteStart && found.index === 0) continue; + skipped.add(Number(found[1])); + stranded = true; + } + } else if (child.type === "element") { + const paragraph = + child.tagName === "blockquote" ? child.children.find(isElementNode) : undefined; + const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined; + visit(child, first?.type === "text" ? first : quoteStart); + } + } + }; + visit(tree, undefined); + if (stranded) continue; + return { + source, + tree, + marker, + toOriginal: (offset) => { + const line = offsets.findLast((entry) => entry.source <= offset) ?? offsets[0]!; + return ( + line.original + Math.min(Math.max(offset - line.source - line.delta, 0), line.length) + ); + }, + }; + } +} + +/** Positions that point into an insight's rewritten source, moved back into the message. */ +function restorePositions(node: Root | Element, toOriginal: (offset: number) => number) { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.position) { + const start = toOriginal(child.position.start.offset!); + const end = toOriginal(child.position.end.offset!); + child.position = { + start: { line: 1, column: start + 1, offset: start }, + end: { line: 1, column: end + 1, offset: end }, + }; + } + restorePositions(child, toOriginal); + } +} + +const PREVIEW_SEPARATED = new Set([ + "blockquote", + "ul", + "ol", + "li", + "table", + "thead", + "tbody", + "tr", +]); + +/** remarkThoughtPreview: the message as one line of text, keeping math, cut at `maxLength`. */ +function flattenPreview(tree: Root, preview: NonNullable): Root { + const children: ElementContent[] = []; + let remaining = preview.maxLength; + let fragments: string[] = []; + const flush = () => { + if (fragments.length === 0) return; + children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") }); + fragments = []; + }; + const take = (value: string) => { + const text = value.slice(0, remaining); + remaining = text.length < value.length ? 0 : remaining - text.length; + // A cut must not leave half a surrogate pair. + return text.replace(/[\uD800-\uDBFF]$/, ""); + }; + const visit = (node: Root | ElementContent) => { + if (remaining === 0) return; + if (node.type === "text") { + fragments.push(take(node.value)); + return; + } + if (node.type === "element" && node.properties.dataMarkdownMath !== undefined) { + flush(); + // One line has no room for display math, which a preview shows inline. + const svg = node.children[0]; + children.push( + node.properties.dataMarkdownMath === "display" && svg?.type === "element" + ? mathWrapper({ + ...svg, + properties: { + ...svg.properties, + style: "display:inline;vertical-align:middle;overflow:visible", + }, + }) + : node, + ); + return; + } + if (node.type === "element" && node.tagName === "img") { + fragments.push(take(String(node.properties.alt ?? ""))); + return; + } + if (node.type === "element" && node.tagName === "br") { + fragments.push(take(" ")); + return; + } + if (node.type !== "root" && node.type !== "element") return; + const separates = node.type === "root" || PREVIEW_SEPARATED.has(node.tagName); + let first = true; + for (const child of node.children as ElementContent[]) { + if (remaining === 0) break; + if (child.type === "text" && child.value.trim() === "" && separates) continue; + if (!first && separates) fragments.push(take(" ")); + first = false; + visit(child); + } + }; + visit(tree); + flush(); + const head = children[0]; + const tail = children.at(-1); + if (head?.type === "text") head.value = head.value.trimStart(); + if (tail?.type === "text") tail.value = tail.value.trimEnd(); + const visible = children.some((child) => child.type !== "text" || child.value); + return { + type: "root", + children: visible ? children : [{ type: "text", value: preview.fallback }], + }; +} + +/** Links become their text, images their alt text, inline code plain text, Mermaid plain code. */ +function makeInert(node: Root | Element) { + const children = node.children as ElementContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "element") continue; + if (child.tagName === "a") { + children.splice(index, 1, ...child.children); + index--; + continue; + } + if (child.tagName === "img") { + children[index] = { type: "text", value: String(child.properties.alt ?? "") }; + continue; + } + if (child.tagName === "code" && child.properties.dataInlineCode !== undefined) { + children[index] = { type: "text", value: textOf(child) }; + continue; + } + if ( + child.tagName === "code" && + String(child.properties.className ?? "").includes("language-mermaid") + ) { + child.properties.className = ["language-text"]; + } + makeInert(child); + } +} + +/** ChatMarkdown's sanitized hast for `text`, rendered by Words. */ +export function wordsHast(text: string, options: WordsHastOptions): Root { + const { extensions } = options; + const renderOptions: RenderOptions = { + math: options.math, + // llm-math's `\(…\)` and `\[…\]`, which agents write as often as `$`. + texDelimiters: options.math, + autolinkBoundaries: true, + singleTilde: !extensions.userMessage, + leadingWhitespace: extensions.leadingWhitespace === true, + windowsPaths: true, + codeMeta: true, + directives: CODEX_DIRECTIVES, + // Previews and inert Markdown drop raw HTML, as their remark plugins dropped html nodes. + ...(extensions.preview || extensions.inert + ? { skipHtml: true } + : { escapeHtml: options.escapeHtml }), + }; + const insights = options.insights ? insightSource(text, renderOptions) : null; + const source = insights?.source ?? text; + const tree = insights?.tree ?? parse(source, renderOptions); + const walk: Walk = { + render: (markdown, indent) => + parse(markdown, { + ...renderOptions, + leadingWhitespace: extensions.leadingWhitespace === true && { indent }, + }), + source, + options, + math: new Map(), + mathKey: `t3-math-${Math.random().toString(36).slice(2)}`, + insightMarker: insights?.marker ?? null, + }; + transform(tree, walk, false, false); + preserveImageSourceMeta(tree as never); + normalizeLocalEditorLinks(tree as never); + const hast = sanitizeChatHast(tree); + if (walk.math.size > 0) restoreMath(hast, walk.math); + if (insights) restorePositions(hast, insights.toOriginal); + if (extensions.inert) makeInert(hast); + if (extensions.preview) return flattenPreview(hast, extensions.preview); + addHeadingIds(hast); + addTextDirection(hast as never); + groupChipPunctuation(hast as never); + return hast; +} + +export interface CodexDirectiveSource { + readonly name: string; + readonly attributes: Record; + /** UTF-16 offsets of the whole directive in the source. */ + readonly start: number; + readonly end: number; + /** The label's text as written. */ + readonly label: string; + /** Inside a link, where a file citation stays text. */ + readonly inLink: boolean; +} + +/** The Codex directives in `markdown`, as Words reads them. */ +export function codexDirectiveSources(markdown: string): CodexDirectiveSource[] { + const found: CodexDirectiveSource[] = []; + const visit = (node: Root | Element, inLink: boolean) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const name = child.properties.dataDirective; + if (typeof name === "string" && child.position) { + const { start, end } = child.position; + found.push({ + name, + attributes: directiveAttributes(child), + start: start.offset!, + end: end.offset!, + label: directiveLabel(markdown.slice(start.offset, end.offset)), + inLink, + }); + } + visit(child, inLink || child.tagName === "a"); + } + }; + visit( + parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + directives: CODEX_DIRECTIVES, + }), + false, + ); + return found; +} + +/** The label of a directive as written, `:name[label]{…}`: brackets nest in it, and `\` escapes. */ +function directiveLabel(written: string): string { + const open = written.indexOf("["); + if (open < 0) return ""; + let depth = 0; + for (let index = open; index < written.length; index++) { + const character = written[index]; + if (character === "\\") index++; + else if (character === "[") depth++; + else if (character === "]" && --depth === 0) return written.slice(open + 1, index); + } + return ""; +} + +/** + * Words' HTML for `markdown` as hast, unsanitized and without the chat's additions. Code blocks, + * links, list items and math carry source positions. + */ +export function markdownTree( + markdown: string, + options: { skipHtml?: boolean; singleTilde?: boolean; math?: boolean } = {}, +): Root { + return parse(markdown, { + windowsPaths: true, + autolinkBoundaries: true, + skipHtml: options.skipHtml === true, + singleTilde: options.singleTilde !== false, + math: options.math === true, + texDelimiters: options.math === true, + }); +} + +/** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */ +export function markdownMathRanges(text: string): Array<{ start: number; end: number }> { + if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return []; + const ranges: Array<{ start: number; end: number }> = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "svg") { + if (child.position) { + ranges.push({ start: child.position.start.offset!, end: child.position.end.offset! }); + } + continue; + } + visit(child); + } + }; + visit(parse(text, { math: true, texDelimiters: true })); + return ranges; +} + +/** The HTML comments Words reads as raw HTML in `markdown`, not as code or text, as source offsets. */ +export function markdownHtmlComments(markdown: string): Array<{ start: number; end: number }> { + const openers = [...markdown.matchAll(/", start + 4); + return { start, end: close < 0 ? markdown.length : close + 3 }; + }); +} + +/** + * The first definition of each label in `markdown`, as one line of Markdown. Words decides which + * `[label]:` text defines one: each label is looked up again after the text. + */ +export function markdownReferenceDefinitions(markdown: string): string[] { + const labels = new Map(); + for (const match of markdown.matchAll(/\[((?:[^\\[\]]|\\.){1,999})\]:/g)) { + const key = match[1]!.replace(/\s+/g, " ").trim().toLowerCase(); + // `[^1]:` is a footnote. + if (key !== "" && !key.startsWith("^") && !labels.has(key)) labels.set(key, match[1]!); + } + if (labels.size === 0) return []; + let probe = `${markdown}\n\n`; + const lookups = new Map(); + for (const label of labels.values()) { + lookups.set(probe.length, label); + probe += `[${label}]\n\n`; + } + const definitions: string[] = []; + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const label = lookups.get(child.position?.start.offset ?? -1); + if (child.tagName === "a" && label !== undefined) { + const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent); + const title = child.properties.title; + definitions.push( + `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`, + ); + } else visit(child); + } + }; + visit(parse(probe, { windowsPaths: true })); + return definitions; +} diff --git a/apps/web/src/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/session-logic.test.ts b/apps/web/src/session-logic.test.ts index f4670665add6c..2155fedaa83c1 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -290,7 +290,10 @@ describe("V2 session presentation", () => { }, }; }); - const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({ + const checkpoint = ( + ordinal: number, + status: "ready" | "missing" | "stale" | "error" = "ready", + ) => ({ runId: runId(ordinal), checkpointTurnCount: ordinal, checkpointRef: `checkpoint-${ordinal}` as never, @@ -326,6 +329,11 @@ describe("V2 session presentation", () => { "user-1": 0, "user-2": 1, }); + // A failed snapshot capture still pins the conversation; only file restore needs one. + expect(targets([1, 2], [checkpoint(1, "error")])).toEqual({ + "user-1": 0, + "user-2": 1, + }); }); it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 1122c3122aca0..99a1fc62a0bc3 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -245,6 +245,7 @@ const STANDALONE_V2_ITEM_TYPES = new Set) { - return checkpoint.status === "ready" || checkpoint.status === "missing"; + return checkpoint.status !== "stale"; } export function findRevertCheckpoint( diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index adeb858c23cab..4194e07834811 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -11,7 +11,7 @@ import { useNavigate, useRouter } from "@tanstack/react-router"; import { AsyncResult, Atom } from "effect/reactivity"; import type { TurnItemSource } from "../components/chat/timelineRowContext"; -import { useRightPanelStore } from "../rightPanelStore"; +import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; import { connectPairing, reachesEnvironment } from "../connection/onboarding"; import { openLinkedThreadRead } from "../lib/sideChatPane"; import type { LinkedThreadSurface } from "../linkedThreadSurface"; @@ -107,14 +107,17 @@ const tabViewAtom = Atom.family((key: string) => { const view = peerLinkEnvironment.threadView( targetOf({ viaEnvironmentId, environmentId, threadId }), ); - return Atom.make((get) => { - const live = get(view); - const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; - if (title && panelRef !== null) { - useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); - } - return live; - }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); + return Atom.readable( + (get) => { + const live = get(view); + const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; + if (title && panelRef !== null) { + useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + } + return live; + }, + (refresh) => refresh(view), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); }); /** @@ -203,8 +206,17 @@ export function useConnectLinkedEnvironment( const connect = async () => { setState({ phase: "connecting" }); const startedOn = router.state.location.href; + let tabClosed = false; + // A tab can close and reopen with the same ID while pairing is in flight. + const stopWatchingTab = + panelRef === null + ? undefined + : useRightPanelStore.subscribe((state) => { + const { surfaces } = selectThreadRightPanelState(state.byThreadKey, panelRef); + if (!surfaces.some((tab) => tab.id === surface.id)) tabClosed = true; + }); // Pairing takes a moment; a user who has gone elsewhere since is not moved again. - const stayed = () => router.state.location.href === startedOn; + const stayed = () => !tabClosed && router.state.location.href === startedOn; const outcome = await connectLinkedEnvironment({ label: surface.label, requestPairing: async () => { @@ -228,13 +240,14 @@ export function useConnectLinkedEnvironment( }); return result._tag === "Success"; }, - }); + }).finally(stopWatchingTab); if (outcome.type === "unreachable") { setState({ phase: "unreachable", label: outcome.label }); return outcome; } if (outcome.type === "connected") { setState({ phase: "idle" }); + if (tabClosed) return outcome; // The thread opens where every thread on a connected environment does, so its tab is done. if (panelRef !== null) useRightPanelStore.getState().closeSurface(panelRef, surface.id); if (!stayed()) return outcome; diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 8eaca1b774c85..0915810b47fed 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -22,7 +22,13 @@ import { AsyncResult, Atom } from "effect/reactivity"; import { formatEnvironmentQueryError } from "./query"; import { terminalEnvironment } from "./terminal"; -import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session"; +import { environmentAtomList, environmentIdsKey } from "./environmentAtomList"; +import { + environmentSession, + sessionHasScope, + useEnvironmentScope, + useEnvironmentsWithScope, +} from "./session"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; @@ -274,3 +280,43 @@ export function useThreadRunningTerminalIds(input: { const sessions = useKnownTerminalSessions(input); return selectRunningSubprocessTerminalIds(sessions ?? []); } + +// A string so status updates that keep every label notify no one. +const terminalLabelsFamily = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const metadata = get(terminalEnvironment.metadata({ environmentId, input: null })); + if (metadata._tag !== "Success") return "[]"; + return JSON.stringify( + Array.from(terminalMetadataIndex(metadata.value).byThreadId, ([threadId, summaries]) => [ + threadId, + summaries[0]!.label, + ]), + ); + }).pipe(Atom.withLabel(`web-terminal-labels:${environmentId}`)), +); +const terminalLabelsListAtom = environmentAtomList("web-terminal-labels", terminalLabelsFamily); +const terminalLabelsByResults = new WeakMap, ReadonlyMap>(); + +/** First terminal label of each thread that has one, keyed `${environmentId}:${threadId}`. */ +export function useTerminalLabelsByThreadKey( + environmentIds: ReadonlyArray, +): ReadonlyMap { + const readable = useEnvironmentsWithScope( + environmentIds.map((environmentId) => ({ environmentId })), + AuthTerminalReadScope, + ); + const readableIds = environmentIds.filter((environmentId) => readable.has(environmentId)); + const results = useAtomValue(terminalLabelsListAtom(environmentIdsKey(readableIds))); + let labels = terminalLabelsByResults.get(results); + if (!labels) { + const next = new Map(); + results.forEach((encoded, index) => { + for (const [threadId, label] of JSON.parse(encoded) as Array<[string, string]>) { + next.set(`${readableIds[index]}:${threadId}`, label); + } + }); + labels = next; + terminalLabelsByResults.set(results, labels); + } + return labels; +} diff --git a/apps/web/src/timestampFormat.test.ts b/apps/web/src/timestampFormat.test.ts index 5f6513ab69623..e94bffea49fbe 100644 --- a/apps/web/src/timestampFormat.test.ts +++ b/apps/web/src/timestampFormat.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vite-plus/test"; +import { describe, expect, it, vi } from "vite-plus/test"; import { formatChatTimestampTooltip, @@ -18,6 +18,20 @@ function useTimeZone(timeZone: string): Disposable { }; } +it("localizes the day period while honoring the system clock and explicit 24-hour mode", async () => { + using _zone = useTimeZone("UTC"); + vi.stubGlobal("window", { desktopBridge: { getSystemLocale: () => "en-US" } }); + vi.resetModules(); + try { + const { formatShortTimestamp } = await import("./timestampFormat"); + const date = "2026-11-19T18:05:00.000Z"; + expect(formatShortTimestamp(date, "locale", "zh")).toBe("下午6:05"); + expect(formatShortTimestamp(date, "24-hour", "zh")).toBe("18:05"); + } finally { + vi.unstubAllGlobals(); + } +}); + describe("timestamps in an explicit time zone", () => { // 23:00 UTC on July 1 is 7 PM on July 1 in New York, whatever the host zone. const now = Date.parse("2026-07-01T23:00:00.000Z"); diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index 836020c20bbec..273b5989366f2 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -84,15 +84,21 @@ function getTimestampFormatter( timestampFormat: TimestampFormat, includeSeconds: boolean, timeZone = "UTC", + locale = timestampLocale, ): Intl.DateTimeFormat { - const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}`; + const cacheKey = `${timestampFormat}:${includeSeconds ? "seconds" : "minutes"}:${timeZone}:${locale ?? ""}`; const cachedFormatter = timestampFormatterCache.get(cacheKey); if (cachedFormatter) { return cachedFormatter; } - const formatter = new Intl.DateTimeFormat(timestampLocale, { + const hourCycle = + timestampFormat === "locale" && locale !== timestampLocale + ? getTimestampFormatter(timestampFormat, includeSeconds).resolvedOptions().hourCycle + : undefined; + const formatter = new Intl.DateTimeFormat(locale, { ...getTimestampFormatOptions(timestampFormat, includeSeconds), + ...(hourCycle === undefined ? {} : { hourCycle }), timeZone, }); timestampFormatterCache.set(cacheKey, formatter); @@ -175,10 +181,14 @@ export function formatFullTimestamp(isoDate: string, timestampFormat: TimestampF ); } -export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string { +export function formatShortTimestamp( + isoDate: string, + timestampFormat: TimestampFormat, + locale?: string, +): string { const date = parseTimestampDate(isoDate); if (!date) return ""; - return formatTime(date, timestampFormat); + return getTimestampFormatter(timestampFormat, false, "UTC", locale).format(wallClockAsUtc(date)); } const dateTimeFormatterCache = new Map(); diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index 4e11917a0aeff..7c1d17587813e 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -129,6 +129,21 @@ describe("chat file links into another project", () => { ).toBeNull(); }); + it("opens nothing when a project left ambiguous by case also has the name", () => { + expect( + pickProjectLinkMatch("handoff.txt", [ + { root: "/reports", entries: [{ path: "notes/HANDOFF.txt", kind: "file" }] }, + { + root: "/support", + entries: [ + { path: "current/Handoff.txt", kind: "file" }, + { path: "archive/HANDOFF.txt", kind: "file" }, + ], + }, + ]), + ).toBeNull(); + }); + it("opens nothing when overlapping projects also list a second suffix match", () => { expect( pickProjectLinkMatch("docs/handoff.txt", [ diff --git a/apps/web/test/fakeEnvironment.ts b/apps/web/test/fakeEnvironment.ts index 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/bun.lock b/bun.lock index 0b0a626cc6861..5dad52996da57 100644 --- a/bun.lock +++ b/bun.lock @@ -275,6 +275,7 @@ "@noble/hashes": "catalog:", "@pierre/diffs": "catalog:", "@pierre/trees": "1.0.0-beta.6", + "@pierre/words": "file:deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz", "@t3tools/client-runtime": "workspace:*", "@t3tools/contracts": "workspace:*", "@t3tools/provider-core": "workspace:*", @@ -315,24 +316,16 @@ "jszip": "3.10.1", "katex": "^0.18.2", "lucide-react": "^0.564.0", - "mdast-util-from-markdown": "^2.0.3", - "micromark-util-combine-extensions": "^2.0.1", "pdfjs-dist": "6.4.299", "pele": "catalog:", + "property-information": "^7.2.0", "react": "catalog:", "react-dom": "catalog:", - "react-markdown": "^10.1.0", - "remark-gfm": "catalog:", - "remark-math": "6.0.0", - "remark-parse": "catalog:", - "remark-rehype": "catalog:", "saxes": "6.0.0", "sql.js": "1.15.0", "tailwind-merge": "^3.4.0", "tiff": "7.1.3", - "unified": "catalog:", "use-sync-external-store": "^1.6.0", - "vfile": "^6.0.3", "zustand": "^5.0.11", }, "devDependencies": { @@ -344,7 +337,6 @@ "@types/compression": "^1.8.1", "@types/culori": "^4.0.1", "@types/hast": "^3.0.4", - "@types/mdast": "^4.0.4", "@types/react": "catalog:", "@types/react-dom": "catalog:", "@types/sql.js": "1.4.11", @@ -354,7 +346,6 @@ "@vitest/browser-playwright": "5.0.5", "compression": "^1.8.2", "gt": "2.27.0", - "micromark-util-types": "catalog:", "oxc-transform-react": "~0.152.0", "playwright": "1.64.1", "tailwindcss": "^4.0.0", @@ -460,16 +451,16 @@ "effect": "catalog:", "gt-i18n": "1.0.40", "jszip": "3.10.1", - "remark-gfm": "catalog:", - "remark-parse": "catalog:", "three": "0.180.0", "unbash": "^5.0.0", - "unified": "catalog:", }, "devDependencies": { "@effect/vitest": "catalog:", "@types/mdast": "^4.0.4", "@types/three": "0.180.0", + "remark-gfm": "catalog:", + "remark-parse": "catalog:", + "unified": "catalog:", "vite-plus": "catalog:", }, }, @@ -761,6 +752,7 @@ "ffi-rs": "1.3.2", "get-east-asian-width": "^1.6.0", "gt-i18n": "1.0.40", + "hast-util-sanitize": "^5.0.2", "mdast-util-directive": "catalog:", "mdast-util-to-hast": "^13.2.1", "micromark-extension-directive": "catalog:", @@ -780,8 +772,10 @@ "devDependencies": { "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", + "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "@types/node": "catalog:", + "hast-util-to-html": "^9.0.5", "micromark-util-types": "catalog:", "vite-plus": "catalog:", }, @@ -1048,9 +1042,11 @@ "@alchemy.run/test@2.0.0-beta.85": "patches/@alchemy.run__test@2.0.0-beta.85.patch", "@clerk/expo-native-components@0.4.4": "patches/@clerk__expo-native-components@0.4.4.patch", "expo-modules-core@58.0.30": "patches/expo-modules-core@58.0.30.patch", + "effect@4.1.5": "patches/effect@4.1.5.patch", "micromark@4.0.2": "patches/micromark@4.0.2.patch", "micromark-extension-llm-math@3.1.0": "patches/micromark-extension-llm-math@3.1.0.patch", "dbus-next@0.10.2": "patches/dbus-next@0.10.2.patch", + "@legendapp/list@3.7.3": "patches/@legendapp__list@3.7.3.patch", "@react-navigation/native-stack@7.21.0": "patches/@react-navigation%2Fnative-stack@7.21.0.patch", "app-builder-lib@26.16.1": "patches/app-builder-lib@26.16.1.patch", "@muse-code/sdk@1.4.6": "patches/@muse-code__sdk@1.4.6.patch", @@ -2435,6 +2431,8 @@ "@pierre/trees": ["@pierre/trees@1.0.0-beta.6", "", { "dependencies": { "@pierre/theming": "1.0.2", "preact": "11.0.0-beta.0", "preact-render-to-string": "6.6.5" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-zxeuSFM9TveM7b5XofweJALCtm/tGYV9HZzdbf7Uf+kBxIlUyz24/EHaGRjB0dsmmfDQl2ETz7AWwJ15lhSnpw=="], + "@pierre/words": ["@pierre/words@apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz", { "peerDependencies": { "@pierre/highlights": ">=0.5.1", "react": "^18.3.1 || ^19.0.0" }, "optionalPeers": ["@pierre/highlights", "react"] }, "sha512-EuIvU8imMY3c/deOHm9/gEh9VJga8R7jjWiIKfjKHbDXjgMo/O3NDN15H0dLc/vo+YTf/QpY0xinfnv7xpf7Rw=="], + "@pinojs/redact": ["@pinojs/redact@0.4.0", "", {}, "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg=="], "@polka/url": ["@polka/url@1.0.0-next.29", "", {}, "sha512-wwQAWhWSuHaag8c4q/KN/vCoeOJYshAIvMQwD4GpSb3OiZklFfvAgmj0VCBBImRpuF/aFgIRzllXlVX93Jevww=="], @@ -4529,8 +4527,6 @@ "react-is": ["react-is@18.3.1", "", {}, "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg=="], - "react-markdown": ["react-markdown@10.1.0", "", { "dependencies": { "@types/hast": "3.0.5", "@types/mdast": "4.0.4", "devlop": "1.1.0", "hast-util-to-jsx-runtime": "2.3.6", "html-url-attributes": "3.0.1", "mdast-util-to-hast": "13.2.1", "remark-parse": "11.0.0", "remark-rehype": "11.1.2", "unified": "11.0.5", "unist-util-visit": "5.1.0", "vfile": "6.0.3" }, "peerDependencies": { "@types/react": ">=18", "react": ">=18" } }, "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ=="], - "react-native": ["react-native@0.88.1", "", { "dependencies": { "@react-native/asset-utils": "0.88.1", "@react-native/codegen": "0.88.1", "@react-native/community-cli-plugin": "0.88.1", "@react-native/gradle-plugin": "0.88.1", "@react-native/normalize-colors": "0.88.1", "@react-native/virtualized-lists": "0.88.1", "anser": "1.4.10", "ansi-regex": "5.0.1", "base64-js": "1.5.1", "flow-enums-runtime": "0.0.6", "flow-parser": "0.327.0", "hermes-compiler": "260318099.0.5", "invariant": "2.2.4", "memoize-one": "5.2.1", "metro-runtime": "0.87.1", "metro-source-map": "0.87.1", "nullthrows": "1.1.1", "pretty-format": "29.7.0", "promise": "8.3.0", "react-devtools-core": "6.1.5", "react-refresh": "0.14.2", "regenerator-runtime": "0.13.11", "scheduler": "0.28.0", "semver": "7.8.5", "stacktrace-parser": "0.1.11", "tinyglobby": "0.2.17", "whatwg-fetch": "3.6.20", "ws": "7.5.11", "yargs": "17.7.2" }, "peerDependencies": { "@types/react": "^19.1.1", "react": "^19.3.0" }, "optionalPeers": ["@types/react"], "bin": { "react-native": "cli.js" } }, "sha512-wajWcLZ93GCN7k4Uwh4CS4L2Ah8ohcvkOXnvIYmh4Yvuqho5j3APZ9qozK+nQrHWSgauq4h8D3HN5DKK84SrHA=="], "react-native-enriched-markdown": ["react-native-enriched-markdown@apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.18-16db4c75.tgz", { "peerDependencies": { "katex": ">=0.16.0", "react": "*", "react-native": "*" }, "optionalPeers": ["katex"], "hasInstallScript": true }, "sha512-TdP2nTxn8W4jPJ5EU+9Ctgf6aOncENP/kMa9aEZpJDmWNLXkxPpcugHMWyZJt2o5WDYE4SPi0V6zV6mOl3+8cA=="], 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/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/user/outside-agents.md b/docs/user/outside-agents.md index 8bcf36d360139..6c5d9976c4cd5 100644 --- a/docs/user/outside-agents.md +++ b/docs/user/outside-agents.md @@ -135,6 +135,14 @@ 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. Each of these is an event type it can poll or stream, narrowed to +projects or threads. 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 the threads it cares about. + ## Scripts on the host On the machine that runs the environment, `t3 thread` uses the same tools diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 84c13d30c4c84..00b27e02ae23d 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -63,8 +63,8 @@ When you return to a large thread after Claude's prompt cache expires, a **Compact** chip with the thread's token count shows next to the send button. While it is on, Enter summarizes the history first, then sends your message. Click the chip to switch it to **Keep** and keep the full -history for that message. The mobile app shows no chip: an eligible message sent -from it summarizes first. The cache lasts about an hour on a Claude +history for that message. The mobile app shows the same chip, labelled with the +token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using composer commands. diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 99255db9ac8cb..051445f03eb07 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -468,8 +468,10 @@ an address you trust: the code is sent there. machine's own threads, projects or settings, and they skip its project setup scripts. - The link shows up in that machine's **Settings → Sharing & access** like any - outside agent. Revoke it there to end it. **Forget** on this machine only - removes it here. + outside agent, and can be revoked there. **Forget** on this machine also ends + it there when that machine confirms it. If it can't, such as when it is + offline or on an older T3 Code, Forget says so; revoke it in that machine's + Sharing & access. - A link stays valid while agents use it. One unused for 30 days expires, as does one to a machine on an older T3 Code after 30 days; link again with a new pairing code. diff --git a/docs/user/source-control.md b/docs/user/source-control.md index fa193bf0e87a8..ba951c3fe9bda 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -160,7 +160,9 @@ Alternatively, open **Settings → Source control & issues**, expand **TanStack from `https://source.tanstack.com/settings/tokens`. A saved token is used before `SRC_TOKEN`, which is used before the `src` login. With several `src` logins, pick the account there too. -Pull requests show the runs of TanStack Source CI with their logs, and update live while open. Issues +Pull requests show the runs of TanStack Source CI with their logs, and update live while open. An +agent can open a private pull request on a public repository when you ask for one: its branch goes +to the repository's private companion and never to the repository itself. Issues can be listed, filed, edited, commented on and closed. Reactions and picking reviewers or assignees from a list are not available yet. @@ -414,7 +416,9 @@ To list Linear issues beside a project's, connect Linear with an API key under Settings → Source control & issues, then pick one or more teams for that project there. Pick another team at any time to add it; uncheck every team to unbind the project. Each team's issues appear in the Linear group of the issue list, sorted with the rest by last update, and -each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. +each can be loaded further on its own. Agents file new issues in the first team picked unless you name another bound team. To +connect another Linear workspace or user, add another account in the same place; each project +reads its teams through the account you picked them under. Select an issue to open it beside the list: description, comments, state changes, linked pull requests, labels, assignees, and reactions. Linked pull requests open in the same panel. You can diff --git a/docs/user/telemetry.md b/docs/user/telemetry.md index 2f2ccc8932769..4c6b3f20eaad5 100644 --- a/docs/user/telemetry.md +++ b/docs/user/telemetry.md @@ -10,7 +10,56 @@ available. Child-agent token counts are reported separately from the main agent' are sent only when they appear in a provider's public model list. Product events do not include prompts, responses, file contents, authentication tokens, conversation IDs, -raw provider events, or child-agent output. +raw provider events, or child-agent output. The one exception is [agent feedback](#agent-feedback), +which is off unless you turn it on. + +## Agent feedback + +Agent feedback lets agents tell the T3 team about T3 Code: a T3 tool or `t3` command that did not +do what they expected, a confusing instruction, or a missing capability. Choose a mode in +**Agent feedback** in **Settings > Labs**: + +- **Off**, the default: agents do not see the feedback tools, and `t3 feedback` stops with a + message pointing to Labs. +- **When I ask**: agents send a report only when you ask them to, about anything in T3 Code. +- **Automatic**: agents also report T3 Code problems they hit on their own, such as a T3 tool that + failed and made them find another way. These reports carry no outline and no message text, and + go out without asking you. `t3 feedback --kind bug --subject "t3 thread send" --expected "…" --actual "…"` + sends one the same way, so it works only in this mode. + +When you ask your agent for a report, in either mode, T3 Code shows it in the thread as a card +with exactly what would leave your machine, and sends it only if you press **Send**. The agent +carries on without waiting and never learns your answer. The card stays open until you answer it, +even after the turn ends or the server restarts; **Don't send** sends nothing, and the agent is +told not to send it another way. Only someone who can run agents on that machine can answer the +card; people on a guest link cannot. + +Each report has the kind of problem, the T3 tool or command it concerns (or `general`), and up to +300 characters each of expected behavior, actual behavior, and workaround, written by the agent, +which is told not to quote your messages or code. The agent also says how many recent turns the +problem spans. A report you approved carries an outline of those turns, and of at least the last 5, +from when the agent asked: who spoke, how long each message was, and which tools ran, whether they +worked, and how long they took. The outline has no text. Tools from your other MCP servers appear +only as `mcp`. Turn on **Include the conversation** in the card to attach the text of your +messages and the agent's replies in the turns the problem spans, up to 1,000 characters per +message and 16 KB in all, oldest text dropped first; the card shows that text before you send it. +To change a report, such as the turns it covers, ask the agent in the chat: it shows a new card, +and you can decline the old one. Tool inputs and outputs, files, and attachments are never sent. An agent can +show you at most 3 report cards and send 3 reports on its own per turn, and `t3 feedback` can +send at most 10 an hour. + +Before anything is saved, T3 Code removes file paths (when text mentions one, the rest of that line +goes with it), your user name, machine name, project title, branch, and git remote, and anything +that looks like a key, token, email address, or URL with a password. It cannot recognise your code +or a name written in a sentence, so only include the conversation when it holds nothing you would +not send. Reports from agents also name the provider, and the model when it is from the provider's +public model list. No thread IDs or project IDs are sent. + +Reports are saved on your machine first, and a declined one is not saved at all; its card keeps +only what you would have sent without the conversation. When product usage +data is turned off, saved reports stay there and are not sent. `t3 feedback list` shows recent +reports, the thread each came from, and a line for each outline; `t3 feedback list --json` shows +exactly what each one holds. ## Relay connection diagnostics diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 7f2aabacf70fc..e0cad998ded70 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -1,7 +1,8 @@ # Working with threads Use a new thread for a separate task. Choose **New worktree** when its code changes -need a separate branch and working directory. +need a separate branch and working directory. Threads in the same checkout share its +branch, so T3 Code refuses a branch switch there while one of them is working. ## Start a thread 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, @@ -555,6 +568,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); /** @@ -575,12 +590,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)), ); @@ -595,6 +612,7 @@ const claudeQueryOptions = ( device = true, browser = true, delegatedChild = false, + agentFeedback: Contracts.AgentFeedbackMode = "off", ) => { // Refs whose text follows a capability read its flag; older ones ignore it. const input: Parameters[0] & { @@ -606,6 +624,7 @@ const claudeQueryOptions = ( resume: false, cwd: null, mcpServers: { "t3-code": { type: "http", url: "http://127.0.0.1/mcp" } }, + agentFeedback, deviceToolsAvailable: device, browserToolsAvailable: browser, delegatedChild, @@ -619,8 +638,15 @@ export const t3SystemAppend = ( device = true, browser = true, delegatedChild = false, + agentFeedback: Contracts.AgentFeedbackMode = "off", ) => { - const { systemPrompt } = claudeQueryOptions(model, device, browser, delegatedChild); + const { systemPrompt } = claudeQueryOptions( + model, + device, + browser, + delegatedChild, + agentFeedback, + ); if (isRecord(systemPrompt) && systemPrompt.type === "preset" && systemPrompt.append) { return systemPrompt.append; } @@ -710,6 +736,8 @@ export const buildBase = ( readonly deviceAccess?: boolean; /** false: the thread has no agent browser access, so T3's text leaves the browser out. */ readonly browserAccess?: boolean; + /** The Agent feedback mode: on, T3 lists its tools and its text includes the mode's line. */ + readonly agentFeedback?: Contracts.AgentFeedbackMode; readonly arm?: Arm; }, ) => { @@ -737,7 +765,13 @@ export const buildBase = ( const append = options.nativeSubagent ? "" : forArm( - t3SystemAppend(model, options.deviceAccess, options.browserAccess, options.subagent), + t3SystemAppend( + model, + options.deviceAccess, + options.browserAccess, + options.subagent, + options.agentFeedback, + ), options.arm, ); const modelLine = `You are powered by the model named ${MODELS[model]}. The exact model ID is ${model}.`; @@ -809,6 +843,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 => { @@ -844,7 +880,12 @@ const buildCodexBase = ( return [JSON.parse(clean(JSON.stringify(item))) as Block]; }); const context = buildCodexAdditionalContext( - { model: options.model, reasoningEffort: effort, delegatedChild: options.subagent === true }, + { + model: options.model, + reasoningEffort: effort, + delegatedChild: options.subagent === true, + agentFeedback: options.agentFeedback ?? "off", + }, { browser: options.browserAccess ?? true, device: options.deviceAccess ?? true }, ); input.push( @@ -2122,6 +2163,8 @@ const savedSecretFile = ( } }; +const decodeFeedbackInput = Schema.decodeUnknownResult(FeedbackInput); + /** The result for one tool call. */ const FORGE_WRITE_TOOLS = new Set([ "pull_request_create", @@ -2278,6 +2321,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); @@ -3238,6 +3314,7 @@ const main = Effect.gen(function* () { browserAccess: boolean, links: boolean, forge: boolean, + agentFeedback: Contracts.AgentFeedbackMode = "off", ): Effect.Effect => codex ? decodeCodexCapture(template).pipe( @@ -3251,6 +3328,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }), ), @@ -3266,6 +3344,7 @@ const main = Effect.gen(function* () { forge, deviceAccess, browserAccess, + agentFeedback, arm: flags.arm, }); return role === "native-subagent" @@ -3277,18 +3356,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, @@ -3298,6 +3378,7 @@ const main = Effect.gen(function* () { browser === "true", links === "true", forge === "true", + feedback as Contracts.AgentFeedbackMode, ), ); } diff --git a/package.json b/package.json index 6b4a766312604..9e6308dedf391 100644 --- a/package.json +++ b/package.json @@ -248,6 +248,7 @@ "react-native-image-viewing@0.2.2": "patches/react-native-image-viewing@0.2.2.patch", "mdast-util-math@3.0.0": "patches/mdast-util-math@3.0.0.patch", "micromark-extension-llm-math@3.1.0": "patches/micromark-extension-llm-math@3.1.0.patch", + "@legendapp/list@3.7.3": "patches/@legendapp__list@3.7.3.patch", "micromark-extension-gfm-table@2.1.1": "patches/micromark-extension-gfm-table@2.1.1.patch", "micromark@4.0.2": "patches/micromark@4.0.2.patch", "mdast-util-to-hast@13.2.1": "patches/mdast-util-to-hast@13.2.1.patch", @@ -278,7 +279,8 @@ "@cursor/sdk@1.4.2": "patches/@cursor__sdk@1.4.2.patch", "alchemy@2.0.0-beta.85": "patches/alchemy@2.0.0-beta.85.patch", "react-native-svg@15.16.1": "patches/react-native-svg@15.16.1.patch", - "react-native-pdf-jsi@6.1.0": "patches/react-native-pdf-jsi@6.1.0.patch" + "react-native-pdf-jsi@6.1.0": "patches/react-native-pdf-jsi@6.1.0.patch", + "effect@4.1.5": "patches/effect@4.1.5.patch" }, "trustedDependencies": [ "esbuild", diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index fee70319c71de..d20a890bf90da 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -103,6 +103,10 @@ "types": "./src/secretRequest.ts", "default": "./src/secretRequest.ts" }, + "./feedback-request": { + "types": "./src/feedbackRequest.ts", + "default": "./src/feedbackRequest.ts" + }, "./link-batch": { "types": "./src/linkBatch.ts", "default": "./src/linkBatch.ts" @@ -654,6 +658,10 @@ "./provider-instance-ids": { "types": "./src/providerInstanceIds.ts", "default": "./src/providerInstanceIds.ts" + }, + "./pull-request-references": { + "types": "./src/pullRequestReferences.ts", + "default": "./src/pullRequestReferences.ts" } }, "scripts": { @@ -680,16 +688,16 @@ "effect": "catalog:", "gt-i18n": "1.0.40", "jszip": "3.10.1", - "remark-gfm": "catalog:", - "remark-parse": "catalog:", "three": "0.180.0", - "unbash": "^5.0.0", - "unified": "catalog:" + "unbash": "^5.0.0" }, "devDependencies": { "@effect/vitest": "catalog:", "@types/mdast": "^4.0.4", "@types/three": "0.180.0", + "remark-gfm": "catalog:", + "remark-parse": "catalog:", + "unified": "catalog:", "vite-plus": "catalog:" } } diff --git a/packages/client-runtime/src/clock.test.ts b/packages/client-runtime/src/clock.test.ts index 1f45860addf7c..f26f830d5b88c 100644 --- a/packages/client-runtime/src/clock.test.ts +++ b/packages/client-runtime/src/clock.test.ts @@ -1,6 +1,12 @@ import { EnvironmentId } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; -import { deadlineStore, recordServerClock, secondTick, toServerClock } from "./clock.ts"; +import { + deadlineStore, + observeServerTime, + recordServerClock, + secondTick, + toServerClock, +} from "./clock.ts"; describe("deadlineStore", () => { afterEach(() => { @@ -172,4 +178,24 @@ describe("server clock", () => { }); expect(toServerClock(environmentId, 12_345)).toBe(12_345); }); + + it("raises a stale negative offset when a host timestamp arrives ahead of it", () => { + const environmentId = EnvironmentId.make("caught-up"); + recordServerClock(environmentId, { + serverTimeMs: 1_000, + requestedAtMs: 2 * HOUR + 900, + receivedAtMs: 2 * HOUR + 1_050, + }); + expect(toServerClock(environmentId, 2 * HOUR + 10_050)).toBe(10_150); + + observeServerTime(environmentId, 2 * HOUR + 10_000, 2 * HOUR + 10_050); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + observeServerTime(environmentId, 5_000, 2 * HOUR + 20_100); + expect(toServerClock(environmentId, 2 * HOUR + 20_050)).toBe(2 * HOUR + 20_000); + + const unrecorded = EnvironmentId.make("unrecorded"); + observeServerTime(unrecorded, HOUR, 1_000); + expect(toServerClock(unrecorded, 1_000)).toBe(1_000); + }); }); diff --git a/packages/client-runtime/src/clock.ts b/packages/client-runtime/src/clock.ts index f8f1290730084..67693220883b8 100644 --- a/packages/client-runtime/src/clock.ts +++ b/packages/client-runtime/src/clock.ts @@ -104,6 +104,29 @@ export function recordServerClock( ); } +/** + * A timestamp stamped by the host is never in its own future, so it gives a + * lower bound on the host's clock. Raises a stale negative offset (for example + * when a VM or WSL clock catches up after host sleep) without shifting a clock + * that already agrees. + */ +export function observeServerTime( + environmentId: EnvironmentId, + serverTimeMs: number, + receivedAtMs: number, +): void { + const currentOffset = serverClockOffsets.get(environmentId); + if ( + currentOffset === undefined || + !Number.isFinite(serverTimeMs) || + !Number.isFinite(receivedAtMs) + ) { + return; + } + if (receivedAtMs + currentOffset >= serverTimeMs) return; + serverClockOffsets.set(environmentId, serverTimeMs - receivedAtMs); +} + /** Converts client epoch milliseconds to the environment's clock. */ export function toServerClock(environmentId: EnvironmentId, clientMs: number): number { return clientMs + (serverClockOffsets.get(environmentId) ?? 0); diff --git a/packages/client-runtime/src/device/stream.test.ts b/packages/client-runtime/src/device/stream.test.ts index ad930680fbeb5..9050e6c18504f 100644 --- a/packages/client-runtime/src/device/stream.test.ts +++ b/packages/client-runtime/src/device/stream.test.ts @@ -140,6 +140,35 @@ describe("native device stream transport", () => { }, ); + it.each([ + ["ios", { button: "home" }, { button: "app_switcher" }], + ["android", { type: "home" }, { type: "recents" }], + ] as const)( + "opens the %s app switcher on a double-tapped home button", + async (platform, home, switcher) => { + const { client, opened } = setup(platform); + client.start(); + const socket = await opened; + socket.onopen?.(); + if (platform === "ios") socket.onmessage?.({ data: Uint8Array.of(0x83).buffer }); + socket.send.mockClear(); + + client.pressButton("home"); + client.pressButton("home"); + client.pressButton("home"); + vi.advanceTimersByTime(1000); + client.pressButton("home"); + + const sent = socket.send.mock.calls.map(([payload]) => + JSON.parse( + typeof payload === "string" ? payload : new TextDecoder().decode(payload.subarray(1)), + ), + ); + expect(sent).toEqual([home, switcher, home, home]); + client.stop(); + }, + ); + it.each(["ios", "android"] as const)( "does not renew credentials or reconnect a stopped %s stream", async (platform) => { diff --git a/packages/client-runtime/src/device/stream.ts b/packages/client-runtime/src/device/stream.ts index c570ee107ad55..45824149a8c66 100644 --- a/packages/client-runtime/src/device/stream.ts +++ b/packages/client-runtime/src/device/stream.ts @@ -1,4 +1,4 @@ -// @effect-diagnostics globalFetch:off globalTimers:off - This browser and WebView transport runs without an Effect runtime. +// @effect-diagnostics globalFetch:off globalTimers:off globalDate:off - This browser and WebView transport runs without an Effect runtime. import { createDuoControl, @@ -157,6 +157,7 @@ const SOFT_DECODE_QUEUE = 8; const ANDROID_MAX_TEXT_BYTES = 300; // The pinned hub queue depth is 128; the client does not read queue rejections. const ANDROID_MAX_TEXT_CHUNKS = 64; +const HOME_DOUBLE_TAP_MS = 400; const IOS_MSG_TOUCH = 0x03; const IOS_MSG_BUTTON = 0x04; @@ -428,6 +429,7 @@ export function createDeviceStreamClient( isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg && !serveSimOnly); let stopped = true; + let lastHomePress = -Infinity; let socket: WebSocket | null = null; let controller: AbortController | null = null; const retryTimers = new Map<"video" | "input", ReturnType>(); @@ -1460,7 +1462,11 @@ export function createDeviceStreamClient( } if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk })); }, - pressButton: (button) => { + pressButton: (pressed) => { + const now = Date.now(); + const doubleHome = pressed === "home" && now - lastHomePress < HOME_DOUBLE_TAP_MS; + lastHomePress = pressed === "home" && !doubleHome ? now : -Infinity; + const button = doubleHome ? "appSwitcher" : pressed; if (avcc) { const name = button === "home" diff --git a/packages/client-runtime/src/feedbackRequest.test.ts b/packages/client-runtime/src/feedbackRequest.test.ts new file mode 100644 index 0000000000000..8c1d5b6cae4bd --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + feedbackConversationHint, + feedbackPreviewFields, + feedbackRequestDisplay, + feedbackTraceLines, + feedbackTraceSummary, +} from "./feedbackRequest.ts"; + +describe("feedbackRequestDisplay", () => { + it("lets only the thread that asked answer, and names how each card ended", () => { + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "local")).toEqual({ + kind: "pending", + }); + expect(feedbackRequestDisplay({ feedbackStatus: "pending" }, "inherited").kind).toBe( + "pending-elsewhere", + ); + expect( + (["sent", "declined", "cancelled"] as const).map((feedbackStatus) => + feedbackRequestDisplay({ feedbackStatus }, "local"), + ), + ).toEqual([ + { kind: "answered", outcome: "sent", label: "Sent" }, + { kind: "answered", outcome: "not-sent", label: "Not sent" }, + { kind: "answered", outcome: "not-sent", label: "Closed without sending" }, + ]); + }); +}); + +describe("feedback preview", () => { + it("shows every field that is sent, and each outline entry with its text", () => { + const trace = { + turns: 1, + textTurns: 1, + truncated: false, + entries: [ + { turn: 1, type: "user" as const, length: 5, text: "Hello" }, + { + turn: 1, + type: "tool" as const, + tool: "t3_thread_read", + outcome: "error" as const, + durationMs: 1_500, + }, + ], + }; + expect( + feedbackPreviewFields({ + kind: "bug", + subject: "t3_thread_read", + expected: "Items.", + actual: "None.", + workaround: "", + trace, + }).map((field) => field.label), + ).toEqual(["Kind", "About", "Expected", "Happened"]); + expect(feedbackTraceLines(trace)).toEqual([ + { key: "0", line: "Turn 1 · You · 5 characters", text: "Hello" }, + { key: "1", line: "Turn 1 · t3_thread_read · error · 1.5 s" }, + ]); + // Text only in turn 4 of 5: the wording reaches back to it, not "the last turn". + const older = { + turns: 5, + textTurns: 1, + truncated: false, + entries: [ + { turn: 4, type: "user" as const, length: 5, text: "Hello" }, + { turn: 5, type: "tool" as const, tool: "shell", outcome: "ok" as const }, + ], + }; + expect(feedbackTraceSummary(older)).toBe( + "Outline of 5 recent turns, message text of the last 2 turns", + ); + expect(feedbackConversationHint(older)).toBe( + "Adds the text of your messages and the agent's replies in the last 2 turns.", + ); + }); +}); diff --git a/packages/client-runtime/src/feedbackRequest.ts b/packages/client-runtime/src/feedbackRequest.ts new file mode 100644 index 0000000000000..f6b0079213ebc --- /dev/null +++ b/packages/client-runtime/src/feedbackRequest.ts @@ -0,0 +1,145 @@ +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; +import type { AgentFeedbackPreview, OrchestrationV2TurnItem } from "@t3tools/contracts"; + +export type FeedbackRequestItem = Extract< + OrchestrationV2TurnItem, + { readonly type: "feedback_request" } +>; + +export type FeedbackRequestDisplay = + | { readonly kind: "pending" } + /** Inherited by a fork: only the thread that asked can answer it. */ + | { readonly kind: "pending-elsewhere"; readonly label: string } + | { readonly kind: "answered"; readonly outcome: "sent" | "not-sent"; readonly label: string }; + +export function feedbackRequestDisplay( + item: Pick, + visibility: "local" | "inherited" | "synthetic", + resolve: MFunctionType = mFallback, +): FeedbackRequestDisplay { + switch (item.feedbackStatus) { + case "pending": + return visibility === "local" + ? { kind: "pending" } + : { kind: "pending-elsewhere", label: resolve(msg("Waiting in the original thread")) }; + case "sent": + return { kind: "answered", outcome: "sent", label: resolve(msg("Sent")) }; + case "declined": + return { kind: "answered", outcome: "not-sent", label: resolve(msg("Not sent")) }; + case "cancelled": + return { + kind: "answered", + outcome: "not-sent", + label: resolve(msg("Closed without sending")), + }; + } +} + +/** Exactly what Send sends: the outline, or with the conversation included, its text too. */ +export function feedbackCardPreview( + item: Pick, + includeConversation: boolean, +): AgentFeedbackPreview { + return includeConversation && item.conversationTrace !== undefined + ? { ...item.preview, trace: item.conversationTrace } + : item.preview; +} + +const KIND_LABELS: Record = { + bug: msg("Bug"), + confusing: msg("Confusing"), + missing_capability: msg("Missing capability"), + wrong_docs: msg("Wrong docs"), + other: msg("Other"), +}; + +/** The report's fields in reading order, the empty workaround left out. */ +export function feedbackPreviewFields( + preview: AgentFeedbackPreview, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly label: string; readonly value: string }> { + return [ + { label: resolve(msg("Kind")), value: resolve(KIND_LABELS[preview.kind]) }, + { label: resolve(msg("About")), value: preview.subject }, + { label: resolve(msg("Expected")), value: preview.expected }, + { label: resolve(msg("Happened")), value: preview.actual }, + { label: resolve(msg("Did instead")), value: preview.workaround }, + ].filter((field) => field.value !== ""); +} + +const seconds = (ms: number) => `${(ms / 1_000).toFixed(ms < 10_000 ? 1 : 0)} s`; + +/** One line per outline entry, plus the message text that goes with it. */ +export function feedbackTraceLines( + trace: NonNullable, + resolve: MFunctionType = mFallback, +): ReadonlyArray<{ readonly key: string; readonly line: string; readonly text?: string }> { + return trace.entries.map((entry, index) => { + const what = + entry.type === "tool" + ? [ + entry.tool ?? "tool", + entry.outcome, + entry.durationMs === undefined ? undefined : seconds(entry.durationMs), + ] + .filter((part) => part !== undefined) + .join(" · ") + : resolve( + msg("{speaker} · {count} characters", { + speaker: resolve(entry.type === "user" ? msg("You") : msg("Agent")), + count: entry.length ?? 0, + }), + ); + return { + key: `${index}`, + line: resolve(msg("Turn {turn} · {what}", { turn: entry.turn, what })), + ...(entry.text === undefined ? {} : { text: entry.text }), + }; + }); +} + +type Trace = NonNullable; + +// Counted back to the oldest turn with text, so a newer turn without any is still inside it. +const textSpan = (trace: Trace) => { + const withText = trace.entries.filter((entry) => entry.text !== undefined); + return withText.length === 0 + ? 0 + : trace.turns - Math.min(...withText.map((entry) => entry.turn)) + 1; +}; + +/** What the outline holds, in one line. */ +export function feedbackTraceSummary(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Outline of {turns, plural, one {{turns} recent turn} other {{turns} recent turns}}, {textTurns, plural, =0 {no message text} one {message text of the last turn} other {message text of the last {textTurns} turns}}{truncated, select, yes {, shortened to fit} other {}}", + { turns: trace.turns, textTurns: textSpan(trace), truncated: trace.truncated ? "yes" : "no" }, + ), + ); +} + +/** What the conversation switch adds: the text of the turns the agent said the problem spans. */ +export function feedbackConversationHint(trace: Trace, resolve: MFunctionType = mFallback): string { + return resolve( + msg( + "Adds the text of your messages and the agent's replies in the last {textTurns, plural, one {turn} other {{textTurns} turns}}.", + { textTurns: textSpan(trace) }, + ), + ); +} + +/** The server's own message for a failed answer, else a generic one. */ +export function feedbackRequestFailureMessage( + failure: unknown, + resolve: MFunctionType = mFallback, +): string { + return typeof failure === "object" && + failure !== null && + "_tag" in failure && + failure._tag === "AgentFeedbackRequestError" && + "message" in failure && + typeof failure.message === "string" + ? failure.message + : resolve(msg("Could not send your answer. Try again.")); +} diff --git a/packages/client-runtime/src/issueLinks.test.ts b/packages/client-runtime/src/issueLinks.test.ts index 661dfe1a94cae..1f2683f92cd59 100644 --- a/packages/client-runtime/src/issueLinks.test.ts +++ b/packages/client-runtime/src/issueLinks.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + IssueTrackerAccountId, IssueTrackerKind, ProjectId, SourceControlProviderKind, @@ -138,6 +139,25 @@ describe("resolveIssueLinkTarget", () => { expect( resolveIssueLinkTarget({ url: "https://linear.app/acme/issue/WEB-17", projects }), ).toBeNull(); + + // A second account reaches its own workspace, through only the projects bound with it. + const accountId = IssueTrackerAccountId.make("second"); + const [p1, p2] = [ProjectId.make("p1"), ProjectId.make("p2")]; + const both = (url: string) => + resolveIssueLinkTarget({ + url, + projects, + trackers: { + ...trackers, + accounts: [{ ...trackers.trackers[0]!, accountId, workspace: "othercorp" }], + bindings: { [p1]: trackers.bindings[p1]! }, + accountBindings: { [p2]: { ...trackers.bindings[p2]!, accountId } }, + }, + })?.ref.projectId; + expect([ + both("https://linear.app/othercorp/issue/WEB-17"), + both("https://linear.app/acme/issue/WEB-17"), + ]).toEqual(["p2", "p1"]); }); it.each([ diff --git a/packages/client-runtime/src/issueLinks.ts b/packages/client-runtime/src/issueLinks.ts index db06b1b0a218f..a81ac7831396d 100644 --- a/packages/client-runtime/src/issueLinks.ts +++ b/packages/client-runtime/src/issueLinks.ts @@ -82,8 +82,8 @@ export function mayContainStandaloneIssueLink(text: string): boolean { /** * A standalone tracker link resolves through the project bound to its scope, else any bound to - * the tracker, and only when it names the workspace the credential reaches: team keys repeat - * across workspaces, so a link elsewhere stays an ordinary link. + * the tracker, and only through an account whose credential reaches the workspace it names: team + * keys repeat across workspaces, so a link elsewhere stays an ordinary link. */ function resolveStandaloneIssueLink( url: string, @@ -94,14 +94,23 @@ function resolveStandaloneIssueLink( const parsed = trackers === undefined ? null : parseStandaloneIssueLink(url); if (parsed === null || trackers === undefined) return null; const { tracker, link } = parsed; - const workspace = trackers.trackers.find( - (connection) => connection.tracker === tracker && connection.account !== null, - )?.workspace; - if (workspace?.toLowerCase() !== link.workspace.toLowerCase()) return null; - const { bindings } = trackers; + const accounts = new Set( + [...trackers.trackers, ...(trackers.accounts ?? [])] + .filter( + (connection) => + connection.tracker === tracker && + connection.account !== null && + connection.workspace?.toLowerCase() === link.workspace.toLowerCase(), + ) + .map((connection) => connection.accountId ?? null), + ); + if (accounts.size === 0) return null; + const bindings = { ...trackers.bindings, ...trackers.accountBindings }; const onTracker = projects.flatMap((project) => { const binding = bindings[project.id]; - return binding?.tracker === tracker ? [{ project, binding }] : []; + return binding?.tracker === tracker && accounts.has(binding.accountId ?? null) + ? [{ project, binding }] + : []; }); const preferFirst = (candidates: typeof onTracker) => candidates.find((candidate) => candidate.project.id === preferredProjectId) ?? candidates[0]; diff --git a/packages/client-runtime/src/issueList.test.ts b/packages/client-runtime/src/issueList.test.ts index 5085c10e51887..49bab599b4f51 100644 --- a/packages/client-runtime/src/issueList.test.ts +++ b/packages/client-runtime/src/issueList.test.ts @@ -144,6 +144,35 @@ describe("issueFilterScopes", () => { expect(issueFilterScopes(held, [])).toEqual([{ environmentId, input: scope }]); }); + it("offers the same team key of two Linear accounts as two scopes", () => { + const first = { + projectId: api, + tracker: "linear" as IssueTrackerKind, + host: "linear.app", + scope: "ENG", + }; + const second = hold( + answer({ + trackers: [tracker({})], + scopes: [first, { ...first, projectId: "home" as ProjectId }], + }), + ); + const other = hold( + answer({ trackers: [tracker({})], scopes: [{ ...first, projectId: "o" as ProjectId }] }), + ); + // Older servers name no scopes; their rows stand in, once per team on that server. + const older = hold( + answer({ trackers: [tracker({})], entries: [linearRow, { ...linearRow, key: "ENG-2" }] }), + ); + const count = (...pages: ReadonlyArray>) => + issueFilterScopes( + new Map(pages.map((page, index) => [`env-${index}` as EnvironmentId, page])), + [], + ).length; + expect([count(second), count(second, other), count(other, second)]).toEqual([2, 3, 3]); + expect([count(older), count(older, second), count(second, older)]).toEqual([1, 3, 3]); + }); + it("skips a tracker that cannot be read", () => { const held = new Map([ [ diff --git a/packages/client-runtime/src/issueList.ts b/packages/client-runtime/src/issueList.ts index 5e01c4683830d..1a99f54e0f580 100644 --- a/packages/client-runtime/src/issueList.ts +++ b/packages/client-runtime/src/issueList.ts @@ -170,6 +170,9 @@ export function issueFilterScopes( ) { const scopes: Array<{ readonly environmentId: EnvironmentId; readonly input: IssueScopeRef }> = []; + // A repository's scope is the same scope on every server. A bound tracker's scope is not: two + // accounts, or two servers, may both have an ENG team, so those are deduplicated per server only. + const fromRepository = new Set(); for (const [environmentId, page] of held) { for (const project of projects) { if (project.environmentId !== environmentId) continue; @@ -186,10 +189,9 @@ export function issueFilterScopes( ) ) continue; - scopes.push({ - environmentId, - input: { projectId: project.id, tracker: tracker.tracker, host, scope }, - }); + const input = { projectId: project.id, tracker: tracker.tracker, host, scope }; + fromRepository.add(input); + scopes.push({ environmentId, input }); } } // A tracker bound in settings (a Linear team) is no repository's; the answer names its scope, @@ -209,9 +211,12 @@ export function issueFilterScopes( ); if (!tracker?.configured) continue; if (!tracker.capabilities?.labels && !tracker.capabilities?.assignees) continue; + // An answer names each scope once per account; rows standing in for one repeat. if ( scopes.some( (s) => + (fromRepository.has(s.input) || + (page.answer.scopes === undefined && s.environmentId === environmentId)) && s.input.scope.toLowerCase() === input.scope.toLowerCase() && s.input.host?.toLowerCase() === host, ) diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 2004f514df4a4..dc98322c225da 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - The probe fixture uses a Node macrotask boundary. +import * as NodeTimersPromises from "node:timers/promises"; import { EnvironmentId, EventId, @@ -254,16 +256,22 @@ describe("connectLinkedEnvironment", () => { credential: "ONE-TIME", expiresAt: DateTime.makeUnsafe(0), }; + const unsupported: PeerLinkClientPairingResult = { + type: "unsupported", + reason: "link_access", + ...target, + }; const connect = ( pairing: PeerLinkClientPairingResult | null, - reachable: ReadonlyArray, + reachable: ReadonlyArray | ((host: string) => Promise), paired = true, ) => { const pairs: Array<{ host: string; pairingCode: string }> = []; return connectLinkedEnvironment({ label: "vm (saved name)", requestPairing: async () => pairing, - reaches: async (host) => reachable.includes(host), + reaches: + typeof reachable === "function" ? reachable : async (host) => reachable.includes(host), pair: async (input) => { pairs.push(input); return paired; @@ -279,6 +287,42 @@ describe("connectLinkedEnvironment", () => { expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan); }); + it.each([ + { + name: "redeems at an alternate after the preferred probe fails", + pairing: credential, + preferredReachable: false, + expected: { + outcome: { type: "connected" }, + pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }], + }, + }, + { + name: "prefills the preferred address even when an alternate answers first", + pairing: unsupported, + preferredReachable: true, + expected: { outcome: { type: "manual", label: "VM", host: lan }, pairs: [] }, + }, + ])("$name without waiting for a silent last address", async (row) => { + const last = "https://other.example.test"; + const preferred = Promise.withResolvers(); + const silent = Promise.withResolvers(); + const connecting = connect({ ...row.pairing, urls: [lan, tailnet, last] }, (host) => { + if (host === lan) return preferred.promise; + if (host === last) return silent.promise; + queueMicrotask(() => preferred.resolve(row.preferredReachable)); + return Promise.resolve(true); + }); + try { + // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Let the already runnable probe continuations finish while the last probe stays pending. + const pending = NodeTimersPromises.setImmediate("still waiting for an address"); + expect(await Promise.race([connecting, pending])).toEqual(row.expected); + } finally { + silent.resolve(false); + preferred.resolve(false); + } + }); + it("says the machine is out of reach, and spends nothing, when no address answers", async () => { expect(await connect(credential, [])).toEqual({ outcome: { type: "unreachable", label: "VM" }, @@ -287,11 +331,6 @@ describe("connectLinkedEnvironment", () => { }); it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => { - const unsupported: PeerLinkClientPairingResult = { - type: "unsupported", - reason: "link_access", - ...target, - }; const manual = (host: string | null) => ({ outcome: { type: "manual", label: "VM", host }, pairs: [], diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 69b179e08f671..9e2b4487f59b4 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -89,8 +89,17 @@ export async function connectLinkedEnvironment(options: { if (pairing === null) return { type: "manual", label: options.label, host: null }; const { label, urls } = pairing; // Asked together, taken in the linking environment's order of preference. - const answers = await Promise.all(urls.map((url) => options.reaches(url))); - const host = urls.find((_, index) => answers[index]) ?? null; + const probes = urls.map((url) => + options.reaches(url).then( + (reached) => (reached ? url : null), + () => null, + ), + ); + let host: string | null = null; + for (const probe of probes) { + host = await probe; + if (host !== null) break; + } if (pairing.type === "unsupported") { return { type: "manual", label, host: host ?? urls[0] ?? null }; } diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index b2535a81123e1..941fdcd9b389e 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -28,6 +28,7 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as TestClock from "effect/testing/TestClock"; import { RpcClientError } from "effect/rpc"; @@ -45,6 +46,7 @@ import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFix import { archiveThread, interruptThreadTurn, + promoteQueuedRun, revertThreadCheckpoint, resumeThreadQueue, startThreadTurn, @@ -55,6 +57,8 @@ const layerTestRandom = Layer.succeed( SecureRandom.make((size) => new Uint8Array(size)), ); +class Refused extends Schema.TaggedError()("Refused", {}) {} + const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), label: "Test environment", @@ -634,6 +638,121 @@ describe("V2 environment commands", () => { }).pipe(Effect.provide(layerTestRandom)), ); + const turnSends = [ + { + name: "new thread's first message", + method: ORCHESTRATION_V2_WS_METHODS.launchThread, + send: (commandId: CommandId) => + startThreadTurn({ + commandId, + threadId: v2ThreadId, + message: { + messageId: MessageId.make(commandId), + role: "user", + text: "hi", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: ProjectId.make("project-1"), + title: "Thread", + modelSelection: v2Projection.thread.modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-06-20T00:00:00.000Z", + }, + }, + }), + }, + { + name: "queued message sent now", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + resumeThreadQueue({ commandId, threadId: v2ThreadId, runId: RunId.make("queued") }), + }, + { + name: "queued message steered", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + promoteQueuedRun({ + commandId, + threadId: v2ThreadId, + queuedRunId: RunId.make("queued"), + targetRunId: RunId.make("running"), + }), + }, + ] as const; + + const sendFailingFirstAttempt = Effect.fn("TestEnvironmentCommands.sendFailingFirstAttempt")( + function* (turnSend: (typeof turnSends)[number], failure: Effect.Effect) { + const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches: [] }); + const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session)); + const attempts: string[] = []; + const firstAttemptFailed = yield* Deferred.make(); + const healthyMethod = ( + healthySession.client as unknown as Record< + string, + (input: unknown) => Effect.Effect + > + )[turnSend.method]!; + const failingClient = { + ...healthySession.client, + [turnSend.method]: (input: { readonly commandId: CommandId }) => + Effect.gen(function* () { + attempts.push(input.commandId); + if (attempts.length > 1) return yield* healthyMethod(input); + yield* SubscriptionRef.set(supervisor.session, Option.none()); + yield* Deferred.succeed(firstAttemptFailed, undefined); + return yield* failure; + }), + } as unknown as WsRpcProtocolClient; + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + const sendFiber = yield* turnSend + .send(CommandId.make("command-turn-send")) + .pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.forkChild, + ); + yield* Deferred.await(firstAttemptFailed); + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + return { exit: yield* Fiber.await(sendFiber), attempts }; + }, + ); + + it.effect.each(turnSends)("resends a $name lost to a session close", (turnSend) => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSend, + Effect.failCause(Cause.interrupt()), + ); + + expect(attempts).toEqual(["command-turn-send", "command-turn-send"]); + expect(Exit.isSuccess(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + + it.effect("doesn't resend a new thread's first message the server refused", () => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSends[0], + Effect.fail(new Refused()), + ); + + expect(attempts).toEqual(["command-turn-send"]); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + it.effect("Stop with no run left ends the thread's pull request watches", () => Effect.gen(function* () { const link = { diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index ee17123e8839f..0ea95420460a7 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -315,28 +315,12 @@ const MAX_LOST_TRANSPORT_RESENDS = 2; // alone would leave the send pending forever. const MESSAGE_DISPATCH_TIMEOUT = "60 seconds"; -const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( - command: Extract, - resendAfterSocketLoss: boolean, -) { +const resendAfterSocketLoss = Effect.fn("EnvironmentCommands.resendAfterSocketLoss")(function* < + A, + E, + R, +>(attempt: Effect.Effect) { const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; - const attempt = dispatch(command).pipe( - Effect.timeoutOrElse({ - duration: MESSAGE_DISPATCH_TIMEOUT, - orElse: () => - Effect.fail( - new EnvironmentRpcUnavailableError({ - environmentId: supervisor.target.environmentId, - ...translatableMessage( - msg("{host} did not confirm the message within 60 seconds.", { - host: supervisor.target.label, - }), - ), - }), - ), - }), - ); - if (!resendAfterSocketLoss) return yield* attempt; for (let resends = 0; ; resends += 1) { const attemptSession = yield* SubscriptionRef.get(supervisor.session); const exit = yield* Effect.exit(attempt); @@ -365,6 +349,30 @@ const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(functio } }); +const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( + command: Extract, + resend: boolean, +) { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const attempt = dispatch(command).pipe( + Effect.timeoutOrElse({ + duration: MESSAGE_DISPATCH_TIMEOUT, + orElse: () => + Effect.fail( + new EnvironmentRpcUnavailableError({ + environmentId: supervisor.target.environmentId, + ...translatableMessage( + msg("{host} did not confirm the message within 60 seconds.", { + host: supervisor.target.label, + }), + ), + }), + ), + }), + ); + return yield* resend ? resendAfterSocketLoss(attempt) : attempt; +}); + const getProjection = (threadId: ThreadId) => request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }); @@ -784,6 +792,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( input.message.attachments, attachments, ); + const resend = input.resendAfterSocketLoss ?? true; const bootstrap = input.bootstrap?.createThread; const prepareWorktree = input.bootstrap?.prepareWorktree; if (bootstrap !== undefined || prepareWorktree !== undefined) { @@ -815,7 +824,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ? {} : { branch: bootstrap.branch }), }; - return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { + const launch = request(ORCHESTRATION_V2_WS_METHODS.launchThread, { commandId, creationSource: input.creationSource ?? "web", threadId: input.threadId, @@ -834,10 +843,10 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( attachments, }, }); + return yield* resend ? resendAfterSocketLoss(launch) : launch; } const requestedMode = input.dispatchMode ?? "auto"; - const resendAfterSocketLoss = input.resendAfterSocketLoss ?? true; if (requestedMode === "start") { return yield* dispatchMessage( { @@ -868,7 +877,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(input.freshContext ? { freshContext: true } : {}), dispatchMode: { type: "start_immediately" }, }, - resendAfterSocketLoss, + resend, ); } @@ -899,7 +908,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}), dispatchMode, }, - resendAfterSocketLoss, + resend, ); }); @@ -1065,9 +1074,9 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea ); if ( checkpoint === undefined || - // Missing snapshots support conversation rewind only. + // Missing or failed snapshots support conversation rewind only. (checkpoint.status !== "ready" && - !(input.restoreFiles === false && checkpoint.status === "missing")) + !(input.restoreFiles === false && checkpoint.status !== "stale")) ) { const target = input.checkpointId === undefined @@ -1156,25 +1165,29 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")( export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* ( input: ResumeThreadQueueInput, ) { - return yield* dispatch({ - ...(input.runId === undefined - ? { type: "queue.resume" as const } - : { type: "queued-run.start" as const, runId: input.runId }), - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + ...(input.runId === undefined + ? { type: "queue.resume" as const } + : { type: "queued-run.start" as const, runId: input.runId }), + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + }), + ); }); export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* ( input: PromoteQueuedRunInput, ) { - return yield* dispatch({ - type: "queued-message.promote-to-steer", - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - queuedRunId: input.queuedRunId, - targetRunId: input.targetRunId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + type: "queued-message.promote-to-steer", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + queuedRunId: input.queuedRunId, + targetRunId: input.targetRunId, + }), + ); }); export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* ( diff --git a/packages/client-runtime/src/operations/threadTitle.ts b/packages/client-runtime/src/operations/threadTitle.ts index 0f57de34036a5..bb1fcd7648dbf 100644 --- a/packages/client-runtime/src/operations/threadTitle.ts +++ b/packages/client-runtime/src/operations/threadTitle.ts @@ -3,6 +3,7 @@ import type { MFunctionType } from "gt-i18n/types"; import type { ChatAttachment } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { truncate } from "@t3tools/shared/String"; import { collectComposerModelMentions } from "../composerModelMentions.ts"; @@ -45,7 +46,7 @@ export function threadTitleTextFromPrompt( return reference.label; }); return ( - normalizeTitleSeed(modelMentionsAsSlugs(prose)) || + normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) || (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "") ); } diff --git a/packages/client-runtime/src/pullRequestMarkdown.test.ts b/packages/client-runtime/src/pullRequestMarkdown.test.ts index d4f19173758ec..7d9d162d76a05 100644 --- a/packages/client-runtime/src/pullRequestMarkdown.test.ts +++ b/packages/client-runtime/src/pullRequestMarkdown.test.ts @@ -4,19 +4,39 @@ import remarkParse from "remark-parse"; import { unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; +import { splitPullRequestBody, type PullRequestBodySegment } from "./pullRequestMarkdown.ts"; import { changeRequestReferenceAutolinker, resolveChangeRequestMediaUrl, - splitPullRequestBody, - type PullRequestBodySegment, -} from "./pullRequestMarkdown.ts"; +} from "./pullRequestReferences.ts"; + +const definitionParser = unified().use(remarkParse).use(remarkGfm); + +// The finder a client passes: each first definition, joined onto one line out of its quote. +const split = (body: string) => + splitPullRequestBody(body, (markdown) => { + const definitions = new Map(); + const visit = (node: Root | RootContent, quotes: number) => { + if (node.type === "definition" && !definitions.has(node.identifier)) { + const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "gu"); + const source = markdown.slice(node.position?.start.offset, node.position?.end.offset); + definitions.set(node.identifier, source.replace(wrap, " ")); + } + if ("children" in node) { + for (const child of node.children) + visit(child, quotes + (node.type === "blockquote" ? 1 : 0)); + } + }; + visit(definitionParser.parse(markdown), 0); + return [...definitions.values()]; + }); describe("pull request body segmentation", () => { // GitHub writes a dropped image into the body as an `` tag, so a bare attachment link on // its own line is the shape it uses for a video — every one sampled in the wild was one. it("lifts a dropped video out and keeps the prose around it", () => { expect( - splitPullRequestBody( + split( "Before\n\nhttps://github.com/user-attachments/assets/2f8c1a90-1b2c-4d5e-8f90-abcdef123456\n\nAfter", ), ).toEqual([ @@ -43,7 +63,7 @@ describe("pull request body segmentation", () => { ? segment.rows.flat().flatMap((cell) => prose(cell.segments)) : [], ); - const runs = prose(splitPullRequestBody(body)); + const runs = prose(split(body)); expect(runs.map((segment) => segment.text)).toEqual([ "- [ ] Before", " - [ ] code\n- [x] After", @@ -59,9 +79,7 @@ describe("pull request body segmentation", () => { it("reads the source out of a video tag, including a multi-line one", () => { expect( - splitPullRequestBody( - '', - ), + split(''), ).toEqual([ { id: "attachment:0", @@ -75,21 +93,21 @@ describe("pull request body segmentation", () => { it("leaves the img tag GitHub writes for a dropped image as markdown", () => { const body = 'image'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("leaves an ordinary link alone, whether it is bare or written as markdown", () => { const body = "https://example.com/page\n\n[the docs](https://example.com/docs)"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("never lifts a link inside fenced code out of it", () => { const body = "```\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -97,14 +115,14 @@ describe("pull request body segmentation", () => { // GitHub keeps CRLF in a body written in its web editor. it("recognizes fences in a body with CRLF line endings", () => { const body = "```\r\nhttps://example.com/demo.mp4\r\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("closes a CRLF fence, so a video after it still lifts out", () => { const code = '```html\r\n\r\n```'; - expect(splitPullRequestBody(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ + expect(split(`${code}\r\n\r\nhttps://example.com/demo.mp4\r\n`)).toEqual([ { id: "markdown:0", kind: "markdown", text: code, sourceOffset: 0 }, { id: "attachment:1", @@ -117,21 +135,21 @@ describe("pull request body segmentation", () => { it("does not let a different fence marker close an open fence", () => { const body = "```\n~~~\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("keeps a video tag that shares its line with prose as markdown", () => { const body = 'Before after'; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); it("treats an info-string fence as a nested opener, not a close", () => { const body = "```\n```javascript\nhttps://example.com/demo.mp4\n```"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -139,9 +157,7 @@ describe("pull request body segmentation", () => { it("does not open a fence on a line of inline triple-backtick code", () => { const code = "```\nhttps://example.com/b.png\n```"; expect( - splitPullRequestBody( - `\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`, - ), + split(`\`\`\`npm test\`\`\` passes.\n\nhttps://example.com/demo.mp4\n\n${code}`), ).toEqual([ { id: "markdown:0", kind: "markdown", text: "```npm test``` passes.", sourceOffset: 0 }, { @@ -153,14 +169,14 @@ describe("pull request body segmentation", () => { { id: "markdown:2", kind: "markdown", text: code, sourceOffset: 54 }, ]); const multilineSpan = "```foo`\nhttps://example.com/demo.mp4\nbar```"; - expect(splitPullRequestBody(multilineSpan)).toEqual([ + expect(split(multilineSpan)).toEqual([ { id: "markdown:0", kind: "markdown", text: multilineSpan, sourceOffset: 0 }, ]); }); it("leaves an indented code line alone even when it is only a video link", () => { const body = " https://example.com/demo.mp4"; - expect(splitPullRequestBody(body)).toEqual([ + expect(split(body)).toEqual([ { id: "markdown:0", kind: "markdown", text: body, sourceOffset: 0 }, ]); }); @@ -169,14 +185,14 @@ describe("pull request body segmentation", () => { const body = ['
    ( + method: string, + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.timeoutOrElse({ + duration: startupRequestTimeout, + orElse: () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + operation: "call-rpc", + method, + detail: `${method} timed out waiting for RPC response`, + cause: undefined, + }), + ), + }), + ); + const runLoggedRequest = ( method: string, payload: unknown, @@ -2297,7 +2318,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const initializeResult = yield* runLoggedRequest( "initialize", initializePayload, - acp.agent.initialize(initializePayload), + withStartupTimeout("initialize", acp.agent.initialize(initializePayload)), ); yield* options.onInitialized?.(initializeResult) ?? Effect.void; return initializeResult; @@ -2445,7 +2466,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( sessionSetupResult = yield* runLoggedRequest( "session/resume", resumePayload, - acp.agent.resumeSession(resumePayload), + withStartupTimeout("session/resume", acp.agent.resumeSession(resumePayload)), ); } else { return yield* new EffectAcpErrors.AcpRequestError({ @@ -2462,7 +2483,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const created = yield* runLoggedRequest( "session/new", createPayload, - acp.agent.createSession(createPayload), + withStartupTimeout("session/new", acp.agent.createSession(createPayload)), ); sessionId = created.sessionId; sessionSetupResult = created; @@ -3061,10 +3082,25 @@ const handleSessionUpdate = ); } const parsed = parseSessionUpdateEvent(params); - if (parsed.modeId) { + const modeId = parsed.modeId; + if (modeId) { yield* Ref.update(modeStateRef, (current) => - current === undefined ? current : updateModeState(current, parsed.modeId!), + current === undefined ? current : updateModeState(current, modeId), ); + // A mode-only update would otherwise leave the mode option showing the old mode. + const configOptions = yield* SubscriptionRef.get(configOptionsRef); + const isStaleMode = (option: (typeof configOptions)[number]) => + option.category === "mode" && option.type === "select" && option.currentValue !== modeId; + if (configOptions.some(isStaleMode)) { + yield* SubscriptionRef.set( + configOptionsRef, + configOptions.map((option) => + option.category === "mode" && option.type === "select" + ? { ...option, currentValue: modeId } + : option, + ), + ); + } } for (const event of parsed.events) { if (event._tag === "ToolCallUpdated") { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index cf12ac771aa07..5a4916ec374fe 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -637,6 +637,15 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Finalize a settled turn held only by running commands once the session has been silent for + * `timeout`, so a command that never reports back cannot leave the thread in Working forever. + * Other holds (questions, schedules, subagents) keep the turn open as before. + */ + readonly postSettleCommandHold?: { + readonly timeout: Duration.Input; + readonly isCommand: (toolCall: AcpToolCallState) => boolean; + }; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -2305,6 +2314,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const activeSelection = yield* Ref.make(null); const activeInteractionMode = yield* Ref.make(null); + // Mode values configureSession left the agent in; a later difference is the agent's own change. + const configuredModes = yield* Ref.make>(new Map()); + const readModes = Effect.gen(function* () { + const modes = new Map(); + for (const option of yield* runtime.getConfigOptions) { + if ( + option.type === "select" && + (option.category === "mode" || option.category === "collaboration_mode") + ) { + modes.set(option.id, option.currentValue); + } + } + const modeId = (yield* runtime.getModeState)?.currentModeId; + if (modeId !== undefined && !modes.has(ACP_SESSION_MODE_OPTION_ID)) { + modes.set(ACP_SESSION_MODE_OPTION_ID, modeId); + } + return modes; + }); const configuredRuntimeMode = yield* Ref.make< ProviderAdapter.ProviderAdapterV2RuntimePolicy["runtimeMode"] | null >(null); @@ -2724,7 +2751,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const notePromptProgress = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) { - if (promptInactivityTimeoutMillis === undefined) return; + if ( + promptInactivityTimeoutMillis === undefined && + flavor.postSettleCommandHold === undefined + ) { + return; + } if ( notification !== undefined && !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate) @@ -4256,11 +4288,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isMonitorEndNoticeText = (text: string): boolean => /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); - const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + const hasDeferredBackgroundWork = ( + context: ActiveAcpTurn, + ignoreTool?: (tool: AcpToolCallState) => boolean, + ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { + if (ignoreTool?.(tool) === true) continue; if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) return true; } @@ -8357,6 +8393,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } yield* validateModelSelection(modelSelection); + yield* Ref.set(configuredModes, yield* readModes); yield* Ref.set(configuredRuntimeMode, runtimePolicy.runtimeMode); yield* ( flavor.onSessionConfigurationUpdate?.( @@ -8545,6 +8582,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }); + // Re-applying the thread's mode would undo a deliberate exit, such as leaving plan mode once + // the plan was approved. Report it instead, so picking the old mode again is a real change. + const reportAgentModeChanges = Effect.fnUntraced(function* (threadId: ThreadId) { + const selection = yield* Ref.get(activeSelection); + if (selection === null || selection.options === undefined) return; + const configured = yield* Ref.get(configuredModes); + const live = yield* readModes; + const changes: Array<{ id: string; from: string; to: string }> = []; + const options = selection.options.map((option) => { + const value = live.get(option.id); + if ( + value === undefined || + typeof option.value !== "string" || + value === configured.get(option.id) || + value === option.value + ) { + return option; + } + changes.push({ id: option.id, from: option.value, to: value }); + return { ...option, value }; + }); + if (changes.length === 0) return; + yield* Ref.set(activeSelection, { ...selection, options }); + yield* Ref.set(configuredModes, live); + yield* emitProviderEvent({ + type: "thread_model_selection.updated", + driver, + threadId, + instanceId: selection.instanceId, + changes, + }); + }); + const finalizeTurn = Effect.fnUntraced(function* ( context: ActiveAcpTurn, status: "completed" | "interrupted" | "failed" | "cancelled", @@ -8640,6 +8710,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }, }); } + yield* reportAgentModeChanges(context.input.threadId); const turn = providerTurnPayload(context, settledStatus, now); yield* Ref.update(providerTurns, (current) => { const updated = new Map(current); @@ -8782,6 +8853,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); + const schedulePostSettleHoldExpiry = Effect.fn("AcpAdapterV2.schedulePostSettleHoldExpiry")( + function* (context: ActiveAcpTurn) { + const hold = flavor.postSettleCommandHold; + if (hold === undefined) return; + if (!context.promptSettled || context.finalized) return; + const timeoutMillis = Duration.toMillis(hold.timeout); + const isRunningCommand = (tool: AcpToolCallState) => + toolStatus(tool.status) === "running" && hold.isCommand(tool); + let quietSince = yield* Clock.currentTimeMillis; + // Armed even without a command yet: a pending reply can still start one. + yield* Effect.gen(function* () { + while (!context.finalized) { + quietSince = Math.max(quietSince, context.lastProgressAt); + const now = yield* Clock.currentTimeMillis; + const remaining = quietSince + timeoutMillis - now; + if (remaining > 0) { + yield* Effect.sleep(Duration.millis(remaining)); + continue; + } + if ( + context.tools.values().some(isRunningCommand) && + !hasDeferredBackgroundWork(context, isRunningCommand) + ) { + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + return; + } + // Something else still holds the turn; count silence again once it clears. + quietSince = now; + } + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { @@ -8988,6 +9092,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const sessionSetup = yield* Ref.get(activeSessionSetup); const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: instructionState.hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: flavor.runtimeHarness ?? driver, model: turnInput.modelSelection.model, delegatedChild: turnInput.appThread.lineage.relationshipToParent === "subagent", @@ -9213,6 +9318,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + yield* schedulePostSettleHoldExpiry(context); if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9613,6 +9719,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (!context.finalized) { + yield* schedulePostSettleHoldExpiry(context); if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else { diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index c8371fb7020e8..592bf47553494 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -263,7 +263,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi // Agents that send shell source write bash; Node's shell on Windows is cmd.exe. const gitExecutable = isWindows && options.shellCommands === true - ? resolveExecutable("git", "win32", environment) + ? yield* Effect.promise(async () => resolveExecutable("git", "win32", environment)) : undefined; const posixShell = gitExecutable === undefined ? undefined : gitForWindowsBash(gitExecutable); diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index ae1160a57d76a..5d49337e048a2 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -1,5 +1,6 @@ import type { OrchestrationV2HistoricalMessage } from "@t3tools/contracts"; import { + type AgentFeedbackMode, ChatAttachment, CheckpointId, MessageId, @@ -8,6 +9,7 @@ import { OrchestrationV2AppThread, OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, + OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderSession, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, @@ -118,6 +120,17 @@ export const ProviderAdapterV2Event = Schema.Union([ sessionScoped: Schema.optional(Schema.Boolean), retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)), }), + /** The agent changed selected options itself, such as leaving plan mode once its plan ran. */ + Schema.Struct({ + type: Schema.Literal("thread_model_selection.updated"), + driver: ProviderDriverKind, + threadId: ThreadId, + instanceId: ProviderInstanceId, + /** Applies only where the thread still holds `from`, so newer user picks win. */ + changes: Schema.Array( + Schema.Struct({ id: Schema.String, from: Schema.String, to: Schema.String }), + ), + }), Schema.Struct({ type: Schema.Literal("provider_turn.updated"), driver: ProviderDriverKind, @@ -165,6 +178,14 @@ export const ProviderAdapterV2Event = Schema.Union([ providerTurnId: ProviderTurnId, pending: Schema.Boolean, }), + // The query process exited under a live session before this work reported back. + Schema.Struct({ + type: Schema.Literal("background_work.lost"), + driver: ProviderDriverKind, + threadId: ThreadId, + providerThreadId: ProviderThreadId, + tasks: Schema.Array(OrchestrationV2PendingBackgroundTask), + }), /** Unpersisted deltas go only to clients showing the row; final output arrives in turn_item.updated. */ Schema.Struct({ type: Schema.Literal("command_output.delta"), @@ -202,6 +223,8 @@ export const ProviderAdapterV2Event = Schema.Union([ failure: Schema.Null, reason: Schema.optional(Schema.String), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), }), Schema.Struct({ @@ -216,6 +239,8 @@ export const ProviderAdapterV2Event = Schema.Union([ retry: Schema.optional(OrchestrationV2ProviderRetry), retryStartedAt: Schema.optional(Schema.DateTimeUtc), threadDisposition: Schema.Literals(["reusable", "broken"]), + /** The provider dropped this turn's request before persisting it to native history. */ + promptDropped: Schema.optional(Schema.Literal(true)), /** Child turns outlive root failure and report their own terminals; otherwise open children settle. */ childTurnsContinue: Schema.optional(Schema.Literal(true)), retainedRuntimeRequestIds: Schema.optional(Schema.Array(RuntimeRequestId)), @@ -558,6 +583,7 @@ export interface ProviderAdapterV2EnsureThreadInput { } export interface ProviderAdapterV2TurnInput { + readonly agentFeedback?: AgentFeedbackMode; readonly appThread: OrchestrationV2AppThread; readonly threadId: ThreadId; readonly runId: RunId; diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index a29b60d4d25ae..7f4b790927488 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -132,6 +132,16 @@ it("preserves actionable T3 errors wrapped by turn startup", () => { }); assert.equal(makeProviderFailure({ cause: Cause.fail(cause) }).message, error.message); } + const unanswered = { + _tag: "CodexAppServerUnresponsiveError", + message: "Codex app-server did not answer turn/start within 2 minutes.", + }; + assert.equal( + makeProviderFailure({ + cause: Cause.fail({ _tag: "ProviderAdapterEventStreamError", cause: unanswered }), + }).message, + unanswered.message, + ); }); it("names how the provider process exited and the stage it failed in, without its output", () => { diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index cfdb0eb3df9a6..e7d47cdb2175e 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -139,6 +139,8 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeConversationNotFoundError": case "CursorModelUnavailableError": case "CodexGoalObjectiveTooLongError": + case "CodexAppServerUnresponsiveError": + case "CodexAppServerRetiredError": case "ProviderSetupError": case "ProviderAdapterThreadInUseError": case "ProviderCompactionUnsupportedError": diff --git a/packages/provider-core/src/server/runtimeInstructions.test.ts b/packages/provider-core/src/server/runtimeInstructions.test.ts index d3437343c745d..dfd63ca4ce7fe 100644 --- a/packages/provider-core/src/server/runtimeInstructions.test.ts +++ b/packages/provider-core/src/server/runtimeInstructions.test.ts @@ -1,6 +1,7 @@ import { assert, describe, it } from "@effect/vitest"; import { + AGENT_FEEDBACK_INSTRUCTIONS, buildRuntimeInstructions, PULL_REQUEST_LINKING_INSTRUCTIONS, } from "./runtimeInstructions.ts"; @@ -84,6 +85,22 @@ describe("buildRuntimeInstructions", () => { ); }); + it("carries the feedback line of the agent feedback mode, and none while it is off", () => { + assert.notInclude(buildRuntimeInstructions({ harness: "Codex" }), "t3_feedback"); + assert.notInclude( + buildRuntimeInstructions({ harness: "Codex", agentFeedback: "off" }), + "t3_feedback", + ); + for (const agentFeedback of ["on-request", "auto"] as const) { + for (const pullRequestLinking of [true, false]) { + assert.include( + buildRuntimeInstructions({ harness: "Codex", agentFeedback, pullRequestLinking }), + AGENT_FEEDBACK_INSTRUCTIONS[agentFeedback], + ); + } + } + }); + it("lists a multi-folder thread's folders and leaves single-folder text unchanged", () => { const base = { runtimeMode: "full-access", interactionMode: "default" } as const; const single = buildRuntimeInstructions({ harness: "Codex" }); @@ -113,6 +130,21 @@ describe("buildRuntimeInstructions", () => { }, }); assert.isTrue(listed.startsWith(`${single}\n\n\n`)); + const withFeedback = buildRuntimeInstructions({ harness: "Codex", agentFeedback: "auto" }); + assert.isTrue( + buildRuntimeInstructions({ + harness: "Codex", + agentFeedback: "auto", + runtimePolicy: { + ...base, + cwd: "/work/app", + workspace: { + folders: [{ name: "api", path: "/work/api", isGitRepository: true }], + extraRoots: [], + }, + }, + }).startsWith(`${withFeedback}\n\n\n`), + ); assert.deepEqual( listed .slice(single.length + 2) diff --git a/packages/provider-core/src/server/runtimeInstructions.ts b/packages/provider-core/src/server/runtimeInstructions.ts index ea7a454457387..b124a3e1bdc72 100644 --- a/packages/provider-core/src/server/runtimeInstructions.ts +++ b/packages/provider-core/src/server/runtimeInstructions.ts @@ -1,3 +1,5 @@ +import type { AgentFeedbackMode } from "@t3tools/contracts"; + import type { ProviderAdapterV2RuntimePolicy } from "./ProviderAdapter.ts"; const LINK_PULL_REQUESTS = @@ -9,6 +11,13 @@ const PULL_REQUEST_TOOLS = const LINK_ISSUES = "If available, call link_issue for each issue you take on or file, even via CLI; skip issues you only read."; +/** None while agent feedback is off, so users who never opt in pay no context for it. */ +export const AGENT_FEEDBACK_INSTRUCTIONS = { + off: "", + "on-request": "Use `t3_feedback` only when the user asks you to send T3 feedback.", + auto: "`t3_feedback` reports are wanted and cheap. Send one, then continue, when a T3 tool or `t3` command fails or gives a wrong result, the user corrects how you use T3 Code, or a T3 capability you looked for is missing. Once per problem; also when the user asks. Only about T3 Code, never the user's code or other tools.", +} satisfies Record; + /** Session-invariant; harnesses with a native system-prompt append can carry it once per session. */ export const PULL_REQUEST_LINKING_INSTRUCTIONS = ` ${LINK_PULL_REQUESTS} Call watch_pull_request when asked to monitor or babysit, or when work you were asked to do, such as a merge, still waits on checks or reviews, even after an earlier unwatch. Finish any needed branch update and push first, then watch and end your turn. Otherwise act now or hand back. Delegated children never watch, even if the brief says babysit. After PR work, a child's last line is: PR , head , checks and reviews . Links and watches persist across pushes. For PR waits, no sleep, loops, gh --watch, Monitor or ScheduleWakeup. Before handback, call unwatch_pull_request on any PR you watch. ${PULL_REQUEST_TOOLS} @@ -26,6 +35,7 @@ ${LINK_ISSUES} /** Omit model and effort when the harness manages them dynamically. */ export function buildRuntimeInstructions(runtime: { readonly harness: string; + readonly agentFeedback?: AgentFeedbackMode; readonly model?: string | undefined; readonly modelName?: string | undefined; readonly reasoningEffort?: string | undefined; @@ -45,6 +55,8 @@ export function buildRuntimeInstructions(runtime: { const modelInfo = model && model !== "auto" && model !== "default" ? `, as ${modelLabel}` : ""; const effortInfo = effort ? ` with ${effort} reasoning effort` : ""; const runtimeInfo = `In case you're asked: you are running in T3 Code through the ${harness} harness${modelInfo}${effortInfo}. No need to mention this otherwise. You can embed images, video, and audio using Markdown image syntax with absolute file paths. Link every other file you cite or produce by its absolute path, as in [http.ts:42](/abs/path/http.ts:42), so the user can open it in T3 Code's files viewer.`; + const feedbackLine = AGENT_FEEDBACK_INSTRUCTIONS[runtime.agentFeedback ?? "off"]; + const feedback = feedbackLine ? `\n${feedbackLine}` : ""; const workspace = runtime.runtimePolicy === undefined ? "" : buildWorkspaceInstructions(runtime.runtimePolicy); const pullRequests = @@ -53,7 +65,8 @@ export function buildRuntimeInstructions(runtime: { : runtime.pullRequestLinking === false ? [] : [PULL_REQUEST_LINKING_INSTRUCTIONS]; - return [runtimeInfo, ...pullRequests, ...(workspace === "" ? [] : [workspace])].join("\n\n"); + const linked = [runtimeInfo, ...pullRequests].join("\n\n"); + return [linked + feedback, ...(workspace === "" ? [] : [workspace])].join("\n\n"); } function toSingleLine(value: string): string { diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 5c0a1940d671c..dfa1ac4865269 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -756,6 +756,149 @@ describe("CursorAdapterV2", () => { ), ); + it.effect("marks failed turns as promptDropped only when Cursor did not checkpoint the run", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const workspace = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "cursor-v2-dropped-", + }); + const checkpointedRuns = new Set(); + let sendCalls = 0; + const instanceId = ProviderInstanceId.make("cursor"); + const threadId = ThreadId.make("cursor-dropped-thread"); + const modelSelection = { instanceId, model: "gemini-4-neon" }; + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: workspace, + }); + const adapter = yield* makeCursorAdapterV2({ + instanceId, + environment: { HOME: workspace }, + }).pipe( + Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { + assertComplete: Effect.void, + open: () => + Effect.succeed({ + agentId: "native-cursor-dropped", + listMessages: Effect.succeed([]), + close: Effect.void, + runCheckpointed: (runId) => + Effect.succeed(runId !== undefined && checkpointedRuns.has(runId)), + send: () => + Effect.sync(() => { + sendCalls += 1; + const runId = `native-cursor-run-${sendCalls}`; + return { + agentId: "native-cursor-dropped", + runId, + cancel: Effect.void, + wait: Effect.succeed({ + id: runId, + status: "error" as const, + error: { + message: + 'AI Model Not Found Invalid parameters for registry model: "gemini-4-neon"', + }, + }), + }; + }), + }), + textGenerate: () => Effect.die("unused"), + }), + Effect.provide(TestProviderHost.layer({ cwd: workspace })), + ); + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("cursor-dropped-session"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const appThread = { + id: threadId, + projectId: ProjectId.make("cursor-dropped-project"), + createdBy: "user" as const, + creationSource: "web" as const, + title: "Cursor dropped prompt", + providerInstanceId: instanceId, + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + activeProviderThreadId: providerThread.id, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; + const runFailed = (ordinal: number) => + Effect.gen(function* () { + yield* runtime.startTurn({ + threadId, + providerThread, + modelSelection, + runtimePolicy, + runId: RunId.make(`cursor-dropped-run-${ordinal}`), + runOrdinal: ordinal, + providerTurnOrdinal: ordinal, + attemptId: RunAttemptId.make(`cursor-dropped-attempt-${ordinal}`), + rootNodeId: NodeId.make(`cursor-dropped-root-${ordinal}`), + appThread, + message: { + messageId: MessageId.make(`cursor-dropped-message-${ordinal}`), + createdBy: "user", + creationSource: "web", + text: "Resume", + attachments: [], + }, + }); + const events = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + ); + const terminal = events.find((event) => event.type === "turn.terminal"); + const turn = events.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ); + return { + terminal: terminal?.type === "turn.terminal" ? terminal : undefined, + turn: turn?.type === "provider_turn.updated" ? turn.providerTurn : undefined, + }; + }); + + // Uncheckpointed failure: Cursor never persisted the prompt. + const uncheckpointed = yield* runFailed(1); + assert.equal(uncheckpointed.terminal?.status, "failed"); + assert.equal(uncheckpointed.terminal?.promptDropped, true); + assert.equal(uncheckpointed.turn?.promptDropped, true); + + // Checkpointed failure: Cursor kept the run's prompt in its store. + checkpointedRuns.add("native-cursor-run-2"); + const checkpointed = yield* runFailed(2); + assert.equal(checkpointed.terminal?.status, "failed"); + assert.isUndefined(checkpointed.terminal?.promptDropped); + assert.isUndefined(checkpointed.turn?.promptDropped); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer), + ), + ), + ); + it.effect("sends T3 instructions to each Cursor conversation that lacks them", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 19bc7b6aee6c8..a3571655531fb 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2510,6 +2510,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( readonly status: OrchestrationV2ProviderTurn["status"]; readonly completedAt: DateTime.Utc | null; readonly tokenUsage?: OrchestrationV2ProviderTurn["tokenUsage"]; + readonly promptDropped?: true; }): OrchestrationV2ProviderTurn => ({ id: input.context.providerTurnId, providerThreadId: input.context.input.providerThread.id, @@ -2525,6 +2526,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( startedAt: input.context.startedAt, completedAt: input.completedAt, ...(input.tokenUsage === undefined ? {} : { tokenUsage: input.tokenUsage }), + ...(input.promptDropped === true ? { promptDropped: true as const } : {}), ...(input.completedAt === null || input.context.usage === undefined ? {} : { @@ -2590,6 +2592,15 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }).pipe(Effect.as(undefined)), ), ); + // Cursor only keeps a run in conversation history once it saves its first checkpoint. + const promptDropped = + (input.status === "failed" || input.status === "cancelled") && + !input.context.compacted && + input.context.prompt !== undefined && + !(yield* ( + input.context.session.runCheckpointed?.(input.context.run.runId) ?? + Effect.succeed(false) + ).pipe(Effect.orElseSucceed(() => false))); yield* emitProviderEvent({ type: "provider_turn.updated", driver: CursorAgentSdk.CURSOR_PROVIDER, @@ -2597,6 +2608,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( context: input.context, status: input.status, completedAt, + ...(promptDropped ? { promptDropped: true as const } : {}), ...(contextUsage === undefined ? {} : { @@ -2633,6 +2645,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: input.failure ?? makeProviderFailure({ class: "provider_error" }), threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), } : { type: "turn.terminal", @@ -2643,6 +2656,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( status: input.status, failure: null, threadDisposition, + ...(promptDropped ? { promptDropped: true as const } : {}), }, ); if (input.context.runtimeInstructions !== undefined) { @@ -2889,12 +2903,13 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( }); } const runtimeInstructions = buildRuntimeInstructions({ + agentFeedback: mcpServers === undefined ? "off" : (turnInput.agentFeedback ?? "off"), harness: "Cursor", model: turnInput.modelSelection.model, delegatedChild: turnInput.appThread.lineage.relationshipToParent === "subagent", runtimePolicy: turnInput.runtimePolicy, }); - // Resend only on a new/compacted/rewound conversation or when the model changes. + // Resend only on a new/compacted/rewound conversation or when the instructions change. const sendRuntimeInstructions = delivered.runtime !== runtimeInstructions; const text = sendRuntimeInstructions ? userText.length === 0 diff --git a/packages/provider-muse/src/server/MuseUsageHome.ts b/packages/provider-muse/src/server/MuseUsageHome.ts index 1ced0d2578b01..329dce90c0e7b 100644 --- a/packages/provider-muse/src/server/MuseUsageHome.ts +++ b/packages/provider-muse/src/server/MuseUsageHome.ts @@ -66,7 +66,11 @@ const make = Effect.gen(function* () { if (Option.isSome(settled)) return settled; // Spawn failures surface asynchronously; without this a missing CLI would report as pending. const resolveExecutable = yield* SpawnExecutableResolution; - if (resolveExecutable(binaryPath, yield* HostProcess.Platform, environment) === undefined) { + const platform = yield* HostProcess.Platform; + const resolved = yield* Effect.promise(async () => + resolveExecutable(binaryPath, platform, environment), + ); + if (resolved === undefined) { return Option.some(undefined); } if (awaitRefresh) return Option.some(yield* Cache.get(cache, key)); diff --git a/packages/provider-muse/src/server/adapter.test.ts b/packages/provider-muse/src/server/adapter.test.ts index f23f7ca84d7ea..7e0375e99a3ec 100644 --- a/packages/provider-muse/src/server/adapter.test.ts +++ b/packages/provider-muse/src/server/adapter.test.ts @@ -388,7 +388,8 @@ vi.mock("node:fs/promises", { spy: true }); describe("MuseAdapterV2", () => { it.effect("connects the thread's MCP credential on native start and resume", () => Effect.gen(function* () { - yield* (yield* McpProviderSessions.McpProviderSessions).set({ + const sessions = yield* McpProviderSessions.McpProviderSessions; + const config = { environmentId: EnvironmentId.make("test-environment"), threadId: THREAD_ID, providerSessionId: "test-session", @@ -396,11 +397,12 @@ describe("MuseAdapterV2", () => { endpoint: "http://127.0.0.1:43210/mcp", authorizationHeader: "Bearer thread-scoped-test-token", browserToolsAvailable: true, - }); + }; for (const nativeId of [undefined, "saved-native-session"]) { + yield* sessions.set(config); const fake = yield* makeFakeMuse(); fake.host.initializeResult.grantedCapabilities.push("sessionMcp"); - yield* makeHarness(fake, INSTANCE_ID, nativeId); + const harness = yield* makeHarness(fake, INSTANCE_ID, nativeId); const call = yield* fake.takeCall(nativeId ? "session/resume" : "session/start"); assert.deepStrictEqual(call.params.config, { mcpServers: { @@ -412,6 +414,13 @@ describe("MuseAdapterV2", () => { }, }, }); + yield* sessions.clear(THREAD_ID); + yield* harness.runtime.startTurn({ + ...(yield* turnInput(harness.providerThread, 1, harness.policy)), + agentFeedback: "auto", + }); + const turn = yield* fake.takeCall("turn/start"); + assert.match(JSON.stringify(turn.params.input), /t3_feedback/); } }).pipe(Effect.scoped, Effect.provide(testLayer)), ); diff --git a/packages/provider-muse/src/server/adapter.ts b/packages/provider-muse/src/server/adapter.ts index e54af702eb1f1..c4243d55bf664 100644 --- a/packages/provider-muse/src/server/adapter.ts +++ b/packages/provider-muse/src/server/adapter.ts @@ -356,6 +356,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( let relaunchable = false; let nativeSessionId: string | undefined; let thread: OrchestrationV2ProviderThread | undefined; + let hasT3Mcp = false; let active: ActiveTurn | undefined; let lastProviderTurn: OrchestrationV2ProviderTurn | undefined; let latestSubscriptionUsage: MuseSubscriptionUsage | undefined; @@ -2013,6 +2014,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( createdAt, updatedAt: createdAt, }; + hasT3Mcp = mcpSession !== undefined; session = { ...session, model: result.session.modelId ?? args.modelSelection.model, @@ -2191,6 +2193,7 @@ export const makeMuseAdapterV2 = Effect.fn("makeMuseAdapterV2")(function* ( { type: "text", text: buildRuntimeInstructions({ + agentFeedback: hasT3Mcp ? (turnInput.agentFeedback ?? "off") : "off", harness: "Muse Code", model: session.model ?? undefined, reasoningEffort: effort, diff --git a/packages/provider-muse/src/server/sdk.test.ts b/packages/provider-muse/src/server/sdk.test.ts index 45ef56cb63458..6607640751092 100644 --- a/packages/provider-muse/src/server/sdk.test.ts +++ b/packages/provider-muse/src/server/sdk.test.ts @@ -263,7 +263,7 @@ describe("Muse launch", () => { const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) => museLaunch("muse", env).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => resolved), + Effect.provideService(SpawnExecutableResolution, async () => resolved), ); it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () => diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts index 6d6b4d5d51050..aece589b1e188 100644 --- a/packages/provider-muse/src/server/sdk.ts +++ b/packages/provider-muse/src/server/sdk.ts @@ -117,7 +117,8 @@ export const museLaunch = Effect.fn("museLaunch")(function* ( if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] }; const env = environment ?? (yield* HostProcess.Environment); const resolveExecutable = yield* SpawnExecutableResolution; - const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, "win32", env))) ?? binaryPath; if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] }; const systemRoot = windowsEnvironmentValue(env, "SystemRoot"); return { diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts index 3815cfce44321..d02271f44ff04 100644 --- a/packages/provider-muse/src/server/usage.test.ts +++ b/packages/provider-muse/src/server/usage.test.ts @@ -260,7 +260,7 @@ describe("Muse history discovery", () => { expect(create).not.toHaveBeenCalled(); }).pipe( Effect.provide([NodeServices.layer, MuseUsageHome.layer]), - Effect.provideService(SpawnExecutableResolution, () => undefined), + Effect.provideService(SpawnExecutableResolution, async () => undefined), ), ); diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index 5b2b5a6605ff2..d9d051908d976 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -13,6 +13,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; import { causeErrorTag } from "@t3tools/shared/observability"; import { + type AgentFeedbackMode, defaultInstanceIdForDriver, type ModelSelection, type OrchestrationV2AppThread, @@ -296,6 +297,7 @@ interface ActiveOpenCodeTurn { readonly appThread: OrchestrationV2AppThread; readonly modelSelection: ModelSelection; readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; + readonly agentFeedback: AgentFeedbackMode; readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; readonly providerThreadId: OrchestrationV2ProviderTurn["providerThreadId"]; readonly runOrdinal: number; @@ -2513,6 +2515,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: state.appThread, modelSelection: state.appThread.modelSelection, runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy, + agentFeedback: state.parentSubagent.parentTurn.agentFeedback, providerTurnId, providerThreadId: providerTurn.providerThreadId, runOrdinal: state.parentSubagent.parentTurn.runOrdinal, @@ -3516,6 +3519,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function harness: "OpenCode", model: turn.modelSelection.model, delegatedChild: turn.appThread.lineage.relationshipToParent === "subagent", + agentFeedback: hasT3Mcp ? turn.agentFeedback : "off", runtimePolicy: turn.runtimePolicy, }), ] @@ -3789,6 +3793,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function appThread: turnInput.appThread, modelSelection: turnInput.modelSelection, runtimePolicy: turnInput.runtimePolicy, + agentFeedback: turnInput.agentFeedback ?? "off", providerTurnId, providerThreadId: turnInput.providerThread.id, runOrdinal: turnInput.runOrdinal, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index a1d7aeb5b3b18..90cc7c3b3bce1 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4430,6 +4430,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr } const instructions = [ buildRuntimeInstructions({ + agentFeedback: mcpAvailable ? (turnInput.agentFeedback ?? "off") : "off", harness: "OpenCode", model: turnInput.modelSelection.model, delegatedChild: turnInput.appThread.lineage.relationshipToParent === "subagent", @@ -4727,7 +4728,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (commands.some((entry) => entry.name === command.name)) { // session.command neither accepts nor returns our ID; record the preceding history boundary. const newest = yield* client.message.list({ sessionID, order: "desc", limit: 1 }); - yield* markBefore(sessionId, newest.data[0]?.id ?? null); + const before = newest.data[0]?.id ?? null; + yield* markBefore(sessionId, before); if (!sending()) return; if (goalCommand?.type === "pause" || goalCommand?.type === "clear") { // OpenCode rejects pausing or clearing a missing goal; Codex treats that as a no-op. @@ -4740,7 +4742,44 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); return yield* finishControl; } - return yield* client.session.command({ sessionID, ...command }).pipe(Effect.asVoid); + yield* client.session.command({ sessionID, ...command }); + // A command that never prompts the model starts no execution, so no event ends its turn. + const idle = () => state.active === turn && !busy.has(sessionId); + if (!idle()) return; + const active = yield* client.session + .active() + .pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT), Effect.option); + if (active._tag === "None") { + return yield* Effect.logWarning("Could not check whether an OpenCode command started."); + } + if (sessionId in active.value) return; + // An execution that already ended left history behind; its events may still trail this reply. + const ran = yield* OpenCode2Client.paginate( + { sessionID, order: "desc" as const, limit: 1 }, + client.message.list, + ).pipe( + Stream.takeWhile((message) => message.id !== before), + Stream.filter( + (message) => + message.type === "user" || message.type === "assistant" || message.type === "idle", + ), + Stream.runHead, + Effect.timeout(ACTIVE_CHECK_TIMEOUT), + Effect.option, + ); + if (ran._tag === "None") { + return yield* Effect.logWarning("Could not check whether an OpenCode command ran."); + } + if (ran.value._tag === "Some") return; + return yield* lock.withPermit( + Effect.suspend(() => + idle() + ? endExecution(state, turn, { + status: turn.interrupted ? "interrupted" : "completed", + }) + : Effect.void, + ), + ); } } const mentions = skillMentions(text); diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 019af2a98783f..b3e54117f02ee 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4159,6 +4159,62 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("reports cached input as a share of input in live and completed token usage", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + fake.queueState({ + sessionFile: FAKE_SESSION_FILE, + model: { provider: "anthropic", id: "large", contextWindow: 1_000_000 }, + }); + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + // Pi's message usage counts uncached input, cache reads and cache writes separately. + const usage = { input: 6, cacheRead: 40_101, cacheWrite: 10_561, output: 123 }; + // Session stats total every message in the session, not this turn. + fake.queueStats({ + tokens: { + input: 1_206, + cacheRead: 90_202, + cacheWrite: 60_622, + output: 250, + total: 152_280, + }, + contextUsage: { tokens: 50_791, contextWindow: 1_000_000 }, + }); + yield* fake.emit({ type: "response", command: "prompt", success: true }); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "message_start", message: { role: "assistant" } }); + yield* fake.emit({ + type: "message_update", + usage: { ...usage, totalTokens: 50_791 }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ok" }, + }); + const live = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, + ); + assert.deepInclude( + live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.deepInclude( + completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each(["turn window", "full tree"] as const)( "finishes a turn whose %s has a parentId cycle", (cycleIn) => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index eae7f3eb6c2fa..e7803bbe9c5ee 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -359,6 +359,11 @@ function compactionTitle(status: PiCompactionStatus): string { } } +type PiMessageTokenUsage = Pick< + OrchestrationV2ProviderTurnTokenUsage, + "inputTokens" | "cachedInputTokens" | "outputTokens" +>; + interface ActivePiTurn { readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput; readonly providerTurn: OrchestrationV2ProviderTurn; @@ -377,6 +382,7 @@ interface ActivePiTurn { promptMayBeCommandOnly: boolean; latestCompactionAfterTokens: number | null; lastLiveUsedTokens: number | null; + lastMessageUsage: PiMessageTokenUsage | undefined; settleProbeGeneration: number; /** An extension may start compaction immediately after Pi emits agent_settled. */ settleWhenIdle: boolean; @@ -904,6 +910,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return value === undefined ? undefined : Math.max(0, Math.trunc(value)); }; + // Pi counts uncached input, cache reads and cache writes separately; input includes all three. + const piMessageTokenUsage = (usage: unknown): PiMessageTokenUsage => { + const uncachedInputTokens = nonNegativeInteger(usage, "input"); + const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); + const outputTokens = nonNegativeInteger(usage, "output"); + return { + ...(uncachedInputTokens === undefined + ? {} + : { + inputTokens: + uncachedInputTokens + + (cachedInputTokens ?? 0) + + (nonNegativeInteger(usage, "cacheWrite") ?? 0), + }), + ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), + ...(outputTokens === undefined ? {} : { outputTokens }), + }; + }; + const rememberModelContextWindow = (model: unknown): number | null => { const provider = recordString(model, "provider"); const id = recordString(model, "id"); @@ -994,6 +1019,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const tokenUsageFromStats = ( stats: unknown, fallbackUsedTokens: number | null, + messageUsage: PiMessageTokenUsage | undefined, updatedAt: DateTime.Utc, ): OrchestrationV2ProviderTurnTokenUsage | undefined => { const contextUsage = recordField(stats, "contextUsage"); @@ -1002,24 +1028,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined; if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0) return undefined; - - const totals = recordField(stats, "tokens"); - const inputTokens = nonNegativeInteger(totals, "input"); - const cachedInputTokens = nonNegativeInteger(totals, "cacheRead"); - const outputTokens = nonNegativeInteger(totals, "output"); - return { - usedTokens, - maxTokens, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), - updatedAt: DateTime.formatIso(updatedAt), - }; + // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message. + return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) }; }; - const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) => + const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) => request({ type: "get_session_stats" }, 2_000).pipe( - Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)), + Effect.map((stats) => + tokenUsageFromStats( + stats, + turn.latestCompactionAfterTokens, + turn.lastMessageUsage, + updatedAt, + ), + ), Effect.orElseSucceed(() => undefined), ); @@ -1030,6 +1052,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) { const usedTokens = nonNegativeInteger(usage, "totalTokens"); + if (usedTokens !== undefined && usedTokens > 0) { + turn.lastMessageUsage = piMessageTokenUsage(usage); + } if ( usedTokens === undefined || usedTokens === 0 || @@ -1040,9 +1065,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } turn.lastLiveUsedTokens = usedTokens; - const inputTokens = nonNegativeInteger(usage, "input"); - const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); - const outputTokens = nonNegativeInteger(usage, "output"); const updatedAt = yield* DateTime.now; yield* emit({ type: "provider_turn.updated", @@ -1053,9 +1075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( tokenUsage: { usedTokens, maxTokens: contextWindow, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), + ...turn.lastMessageUsage, updatedAt: DateTime.formatIso(updatedAt), }, }, @@ -2075,9 +2095,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } const treeRefs = turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs(); - const tokenUsage = readUsage - ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt) - : undefined; + const tokenUsage = readUsage ? yield* readTokenUsage(turn, completedAt) : undefined; const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure); yield* emit({ type: "provider_turn.updated", @@ -3474,6 +3492,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false), latestCompactionAfterTokens: null, lastLiveUsedTokens: null, + lastMessageUsage: undefined, settleProbeGeneration: 0, settleWhenIdle: false, compactionCancelled: false, diff --git a/packages/shared/package.json b/packages/shared/package.json index daa396dd07043..b727b976fe143 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -519,6 +519,14 @@ "types": "./src/markdownGithubAlerts.ts", "import": "./src/markdownGithubAlerts.ts" }, + "./markdownChunks": { + "types": "./src/markdownChunks.ts", + "import": "./src/markdownChunks.ts" + }, + "./markdownHast": { + "types": "./src/markdownHast.ts", + "import": "./src/markdownHast.ts" + }, "./markdownFrontmatter": { "types": "./src/markdownFrontmatter.ts", "import": "./src/markdownFrontmatter.ts" @@ -646,6 +654,18 @@ "./paletteSearchCopy": { "types": "./src/paletteSearchCopy.ts", "import": "./src/paletteSearchCopy.ts" + }, + "./markdownTaskEdits": { + "types": "./src/markdownTaskEdits.ts", + "import": "./src/markdownTaskEdits.ts" + }, + "./threadFindBlockTags": { + "types": "./src/threadFindBlockTags.ts", + "import": "./src/threadFindBlockTags.ts" + }, + "./assistantInsights": { + "types": "./src/assistantInsights.ts", + "import": "./src/assistantInsights.ts" } }, "scripts": { @@ -660,6 +680,7 @@ "ffi-rs": "1.3.2", "get-east-asian-width": "^1.6.0", "gt-i18n": "1.0.40", + "hast-util-sanitize": "^5.0.2", "mdast-util-directive": "catalog:", "mdast-util-to-hast": "^13.2.1", "micromark-extension-directive": "catalog:", @@ -679,8 +700,10 @@ "devDependencies": { "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", + "@types/hast": "^3.0.5", "@types/mdast": "^4.0.4", "@types/node": "catalog:", + "hast-util-to-html": "^9.0.5", "micromark-util-types": "catalog:", "vite-plus": "catalog:" } diff --git a/packages/shared/src/assistantInsights.ts b/packages/shared/src/assistantInsights.ts new file mode 100644 index 0000000000000..60f4ad1df349a --- /dev/null +++ b/packages/shared/src/assistantInsights.ts @@ -0,0 +1,3 @@ +export function shouldPreserveAssistantLineBreaks(text: string): boolean { + return /^★ Insight(?:\s|─)/mu.test(text); +} diff --git a/packages/shared/src/codexArtifactTemplates.ts b/packages/shared/src/codexArtifactTemplates.ts index 08fa5a28e3e58..9308c24d930dd 100644 --- a/packages/shared/src/codexArtifactTemplates.ts +++ b/packages/shared/src/codexArtifactTemplates.ts @@ -133,3 +133,29 @@ export function appendCodexArtifactTemplateUsePrompt( const needsLeadingSpace = draft.length > 0 && !/\s$/.test(draft); return `${draft}${needsLeadingSpace ? " " : ""}${prompt}`; } + +export const CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES = [ + "dataCodexArtifactTemplate", + "dataArtifactKind", + "dataDisplayName", + "dataGalleryKind", + "dataSkillDirectory", + "dataSkillName", +] as const; + +export function artifactTemplateFromHastProperties( + properties: Readonly> | null | undefined, +): CodexArtifactTemplate | null { + if (properties?.dataCodexArtifactTemplate !== "true") return null; + const stringProperty = (name: string) => { + const value = properties[name]; + return typeof value === "string" ? value : undefined; + }; + return resolveCodexArtifactTemplate({ + artifact_kind: stringProperty("dataArtifactKind"), + display_name: stringProperty("dataDisplayName"), + gallery_kind: stringProperty("dataGalleryKind"), + skill_directory: stringProperty("dataSkillDirectory"), + skill_name: stringProperty("dataSkillName"), + }); +} diff --git a/packages/shared/src/codexMarkdownDirectives.ts b/packages/shared/src/codexMarkdownDirectives.ts index 6ff396eddb12a..fecbdb99fe0ac 100644 --- a/packages/shared/src/codexMarkdownDirectives.ts +++ b/packages/shared/src/codexMarkdownDirectives.ts @@ -23,15 +23,6 @@ const CODEX_FILE_CITATION_NAME = "codex-file-citation"; const CODEX_FOLLOW_UP_NAME = "codex-followup"; const CODEX_ARTIFACT_TEMPLATE_NAME = "artifact-template"; -export const CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES = [ - "dataCodexArtifactTemplate", - "dataArtifactKind", - "dataDisplayName", - "dataGalleryKind", - "dataSkillDirectory", - "dataSkillName", -] as const; - interface MarkdownPosition { readonly start: { readonly offset?: number }; readonly end: { readonly offset?: number }; @@ -404,20 +395,3 @@ export function splitCodexArtifactTemplateMarkdown( } return segments; } - -export function artifactTemplateFromHastProperties( - properties: Readonly> | null | undefined, -): CodexArtifactTemplate | null { - if (properties?.dataCodexArtifactTemplate !== "true") return null; - const stringProperty = (name: string) => { - const value = properties[name]; - return typeof value === "string" ? value : undefined; - }; - return resolveCodexArtifactTemplate({ - artifact_kind: stringProperty("dataArtifactKind"), - display_name: stringProperty("dataDisplayName"), - gallery_kind: stringProperty("dataGalleryKind"), - skill_directory: stringProperty("dataSkillDirectory"), - skill_name: stringProperty("dataSkillName"), - }); -} diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index 0f53299089bfc..c8c17b84a9b7b 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -1,8 +1,19 @@ import { describe, expect, it } from "vite-plus/test"; -import { collectComposerInlineTokens, composerMathRanges } from "./composerInlineTokens.ts"; +import { + collectComposerInlineTokens as collectWithoutMath, + type CollectComposerInlineTokensOptions, + composerFileLinksToPlainText, + composerMathRanges, +} from "./composerInlineTokens.ts"; +import { markdownMathRanges } from "./markdownMath.ts"; import { serializeComposerFileLink } from "./composerTrigger.ts"; +const collectComposerInlineTokens = ( + text: string, + options: CollectComposerInlineTokensOptions = {}, +) => collectWithoutMath(text, { findMath: markdownMathRanges, ...options }); + describe("collectComposerInlineTokens", () => { it("collects file links, mentions, and skills with source ranges", () => { const text = "Use $ui and inspect [Chat.tsx](src/Chat.tsx) with @AGENTS.md please"; @@ -215,8 +226,21 @@ describe("collectComposerInlineTokens", () => { it("still finds a formula after a mention that starts the line", () => { const link = serializeComposerFileLink("app/routes/posts.$postId.tsx"); - expect(composerMathRanges(`${link} sets $x_i$`).map((formula) => formula.source)).toEqual([ - "$x_i$", - ]); + expect( + composerMathRanges(`${link} sets $x_i$`, markdownMathRanges).map((formula) => formula.source), + ).toEqual(["$x_i$"]); + }); +}); + +describe("composerFileLinksToPlainText", () => { + it("shows file mentions by name and leaves other links as written", () => { + const mentions = ["src/foo.ts", ".gitignore", "pkg/__init__.py", "docs/My File (draft).md"] + .map(serializeComposerFileLink) + .join(" "); + expect(composerFileLinksToPlainText(`Review ${mentions}`)).toBe( + "Review foo.ts .gitignore __init__.py My File (draft).md", + ); + const links = "See [docs](https://example.com) and [the config](src/config.ts)"; + expect(composerFileLinksToPlainText(links)).toBe(links); }); }); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index 992a9d08e4774..80a1b4d6916ae 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,4 +1,9 @@ -import { markdownMathRanges } from "./markdownMath.ts"; +import { fileBasename } from "./path.ts"; + +/** The formulas a Markdown parser finds in text, as source offsets. */ +export type FindMathRanges = ( + text: string, +) => ReadonlyArray<{ readonly start: number; readonly end: number }>; export type ComposerInlineToken = | { @@ -18,6 +23,8 @@ export type ComposerInlineToken = export interface CollectComposerInlineTokensOptions { readonly preserveTrailingFrom?: ReadonlyArray; + /** Formulas keep their literal tokens; without it, nothing is read as math. */ + readonly findMath?: FindMathRanges; } const SKILL_MENTION_SOURCE = @@ -100,6 +107,7 @@ function collectMentionTokens(text: string): ComposerInlineToken[] { */ export function composerMathRanges( text: string, + findMath: FindMathRanges, mentions: ReadonlyArray = collectMentionTokens(text), ) { let masked = text; @@ -110,7 +118,7 @@ export function composerMathRanges( "x".repeat(mention.end - mention.start) + masked.slice(mention.end); } - return markdownMathRanges(masked).map(({ start, end }) => ({ + return findMath(masked).map(({ start, end }) => ({ start, end, source: text.slice(start, end), @@ -157,10 +165,26 @@ export function collectComposerInlineTokens( // TeX can contain literal skill and file tokens, especially inside \text{}. // They remain formula source rather than becoming composer context chips. // Confirmed trailing file links are masked too, so a kept chip is not read as TeX. - const math = matches.length > 0 ? composerMathRanges(text, matches) : []; + const math = + matches.length > 0 && options.findMath + ? composerMathRanges(text, options.findMath, matches) + : []; return matches .filter( (match) => !math.some((formula) => match.start < formula.end && match.end > formula.start), ) .sort((left, right) => left.start - right.start); } + +/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */ +export function composerFileLinksToPlainText(text: string): string { + let result = ""; + let cursor = 0; + // The composer reads a link as a mention only before whitespace, so one may end the text. + for (const token of collectMentionTokens(`${text} `)) { + if (!token.source.startsWith("[")) continue; + result += text.slice(cursor, token.start) + fileBasename(token.value); + cursor = token.end; + } + return result + text.slice(cursor); +} diff --git a/packages/shared/src/markdownChunks.test.ts b/packages/shared/src/markdownChunks.test.ts new file mode 100644 index 0000000000000..a5cf2a8017b35 --- /dev/null +++ b/packages/shared/src/markdownChunks.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { splitMarkdown } from "./markdownChunks.ts"; + +const splitLargeMarkdown = (text: string, targetChars?: number) => + splitMarkdown(text, targetChars).chunks; + +const starts = (text: string) => + splitLargeMarkdown(text, 1).map((chunk) => chunk.text.split("\n")[0]); + +describe("splitMarkdown", () => { + it("cuts only where a new top-level block starts, and keeps every byte", () => { + const text = [ + "# Title", + "Intro paragraph", + "", + "- item one", + "", + " continued item", + "- item two", + "", + "2. ordered", + "", + "```md", + "# not a heading", + "", + "Not a paragraph", + "```", + "", + "> quote", + "", + "Closing paragraph", + "## Next", + "---", + "", + "| a | b |", + ].join("\n"); + const chunks = splitLargeMarkdown(text, 1); + expect(chunks.map((chunk) => chunk.text).join("\n")).toBe(text); + expect(chunks.reduce((sum, chunk) => sum + chunk.lines, 0)).toBe(text.split("\n").length); + expect(starts(text)).toEqual([ + "# Title", + "```md", + "> quote", + "Closing paragraph", + "## Next", + "| a | b |", + ]); + }); + + it("keeps a fence open until a matching closer", () => { + const text = ["````", "```", "", "# inside", "````", "", "after"].join("\n"); + expect(starts(text)).toEqual(["````", "after"]); + }); + + it("keeps HTML blocks and display math open across blank lines", () => { + const text = [ + "", + "", + "$$", + "", + "Inside math", + "$$", + "", + "

    ",
    +      "",
    +      "Preformatted",
    +      "
    ", + "", + "", + "", + "
    ", + "# literal", + "
    ", + "", + "after", + ].join("\n"); + expect(starts(text)).toEqual(["/], + [/^ {0,3}<\?/, /\?>/], + [/^ {0,3}/], + [/^ {0,3}/], + [/^ {0,3}\$\$/, /\$\$/], +]; + +// A tag name, not an autolink such as . +const HTML_BLOCK_START = /^ {0,3}<\/?[A-Za-z][A-Za-z0-9-]*(?=[\s/>]|$)/; + +/** Returns how to recognize the end of a block that `line` opens, or null for none. */ +function blockCloser(line: string): ((line: string) => boolean) | null { + const fence = FENCE_OPEN.exec(line)?.[1]; + if (fence) { + return (next) => { + const closer = FENCE_OPEN.exec(next)?.[1]; + return ( + closer !== undefined && + closer[0] === fence[0] && + closer.length >= fence.length && + !next.trim().slice(closer.length) + ); + }; + } + for (const [open, close] of SPANNING_BLOCKS) { + const opener = open.exec(line)?.[0]; + if (opener === undefined) continue; + return close.test(line.slice(opener.length)) ? null : (next) => close.test(next); + } + // Other HTML blocks (CommonMark types 6 and 7) run until a blank line. + return HTML_BLOCK_START.test(line) ? (next) => next.trim() === "" : null; +} + +export interface MarkdownChunk { + readonly text: string; + readonly lines: number; +} + +const FRONTMATTER_OPEN = /^\uFEFF?---[ \t]*\r?$/; +const FRONTMATTER_CLOSE = /^(?:---|\.\.\.)[ \t]*\r?$/; +// An opening rule with no closer is a thematic break, not frontmatter; stop waiting for one. +const FRONTMATTER_MAX_LINES = 1000; + +// A one-line link reference definition; footnotes are left alone so each piece does not grow +// a footnote section. +const LINK_DEFINITION = + /^ {0,3}\[(?!\^)(?:[^\]\\]|\\.)+\]:[ \t]*(?:<[^<>\n]*>|[^\s<]\S*)(?:[ \t]+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?[ \t]*\r?$/; +// Definitions past this are not repeated into every piece; their parse cost would outweigh links. +const SHARED_DEFINITIONS_MAX_CHARS = 16 * 1024; + +export interface SplitMarkdown { + readonly chunks: readonly MarkdownChunk[]; + readonly definitions: string; +} + +/** + * Cuts Markdown into pieces of roughly `targetChars`, only at column-0 headings or paragraphs + * that start a new top-level block. Leading frontmatter stays in the first piece. Link + * definitions are collected so every piece can resolve them; footnotes resolve only inside their + * own piece, and duplicate heading slugs restart per piece. + */ +export function splitMarkdown(text: string, targetChars = CHUNK_TARGET_CHARS): SplitMarkdown { + const chunks: MarkdownChunk[] = []; + const definitions: string[] = []; + let lines: string[] = []; + let first = true; + let chars = 0; + let closes: ((line: string) => boolean) | null = null; + let afterBlankLine = false; + let afterDefinition = false; + let afterHeading = false; + let definitionChars = 0; + const flush = () => { + chunks.push({ text: lines.join("\n"), lines: lines.length }); + lines = []; + chars = 0; + }; + for (const line of text.split("\n")) { + if (closes !== null) { + if (closes(line)) closes = null; + } else if (first && FRONTMATTER_OPEN.test(line)) { + let seen = 0; + closes = (next) => FRONTMATTER_CLOSE.test(next) || ++seen >= FRONTMATTER_MAX_LINES; + } else { + const cut = + chars >= targetChars && + (ATX_HEADING.test(line) || + (afterBlankLine && BLOCK_START.test(line) && !ORDERED_ITEM.test(line))); + if (cut) flush(); + closes = blockCloser(line); + // A definition cannot interrupt a paragraph, so it follows a blank line, a heading or + // another definition. + const definition: boolean = + (first || afterBlankLine || afterDefinition || afterHeading) && LINK_DEFINITION.test(line); + afterDefinition = definition; + if (definition && definitionChars + line.length < SHARED_DEFINITIONS_MAX_CHARS) { + definitions.push(line.trim()); + definitionChars += line.length + 1; + } + } + first = false; + lines.push(line); + chars += line.length + 1; + afterBlankLine = line.trim() === ""; + afterHeading = closes === null && (ATX_HEADING.test(line) || THEMATIC_BREAK.test(line)); + } + flush(); + return { chunks, definitions: definitions.join("\n") }; +} + +/** Appends shared link definitions after a piece, leaving its own offsets unchanged. */ +export function withMarkdownDefinitions(text: string, definitions: string): string { + return definitions ? `${text}\n\n${definitions}` : text; +} diff --git a/apps/web/src/markdownGithubAlerts.test.tsx b/packages/shared/src/markdownGithubAlerts.test.ts similarity index 70% rename from apps/web/src/markdownGithubAlerts.test.tsx rename to packages/shared/src/markdownGithubAlerts.test.ts index 0f01e322681a4..31a84b465f91a 100644 --- a/apps/web/src/markdownGithubAlerts.test.tsx +++ b/packages/shared/src/markdownGithubAlerts.test.ts @@ -1,14 +1,21 @@ -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; +import { toHtml } from "hast-util-to-html"; import remarkGfm from "remark-gfm"; +import remarkParse from "remark-parse"; +import remarkRehype from "remark-rehype"; +import { type PluggableList, unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; -import { remarkGithubAlerts } from "@t3tools/shared/markdownGithubAlerts"; +import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; + +const processor = unified() + .use(remarkParse) + .use([remarkGfm, remarkGithubAlerts] satisfies PluggableList) + .use(remarkRehype, { allowDangerousHtml: true }); function renderMarkdown(markdown: string): string { - return renderToStaticMarkup( - {markdown}, - ); + return toHtml(processor.runSync(processor.parse(markdown), markdown), { + allowDangerousHtml: true, + }); } describe("remarkGithubAlerts", () => { diff --git a/packages/shared/src/markdownHast.ts b/packages/shared/src/markdownHast.ts new file mode 100644 index 0000000000000..23a4b4d72ddd6 --- /dev/null +++ b/packages/shared/src/markdownHast.ts @@ -0,0 +1,211 @@ +import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; +import type { Root } from "hast"; +import { defaultSchema, sanitize, type Schema } from "hast-util-sanitize"; + +import { CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES } from "./codexArtifactTemplates.ts"; +import { isWindowsDrivePathHref, normalizeMarkdownLinkDestination } from "./markdownLinks.ts"; +import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; + +type MarkdownImageHastNode = { + type?: string; + value?: string; + tagName?: string; + properties?: Record; + children?: MarkdownImageHastNode[]; +}; + +function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] { + return (node.children ?? []).filter( + (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""), + ); +} + +const STANDALONE_IMAGE_BLOCKS = new Set([ + "p", + "div", + "li", + "td", + "th", + "figure", + "center", + "blockquote", +]); + +function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined { + const children = meaningfulHastChildren(node); + if (children.length !== 1) return undefined; + const only = children[0]; + if (only?.type !== "element") return undefined; + if (only.tagName === "img") return only; + return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em" + ? soleImageDescendant(only) + : undefined; +} + +function markStandaloneImages(node: MarkdownImageHastNode) { + if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) { + const image = soleImageDescendant(node); + if (image) image.properties = { ...image.properties, dataStandalone: true }; + } + node.children?.forEach((child) => { + if (child.type === "element") markStandaloneImages(child); + }); +} + +const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i; + +/** + * The renderer resolves an ``'s `src` (workspace files, host media) but never a ``'s + * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves + * onto the `` for the renderer to pick by theme; every source is then dropped. + */ +function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) { + if (!picture.children) return; + const image = picture.children.find((child) => child.tagName === "img"); + for (const source of picture.children) { + if (source.tagName !== "source" || !image) continue; + const media = source.properties?.media; + const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined; + const srcSet = source.properties?.srcSet; + const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet; + // A candidate's URL runs to the first space (a descriptor such as `2x` may follow). + const url = + typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : ""; + const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc"; + // As in a browser, the first source that matches a scheme is the one shown. + if (scheme && url && image.properties?.[key] === undefined) { + // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path. + const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url; + image.properties = { ...image.properties, [key]: value }; + } + } + picture.children = picture.children.filter((child) => child.tagName !== "source"); +} + +export function rehypePreserveImageSourceMeta() { + return (tree: MarkdownImageHastNode) => { + const visit = (node: MarkdownImageHastNode) => { + const src = node.properties?.src; + const title = node.properties?.title; + if (node.type === "element" && node.tagName === "picture") { + moveColorSchemeSourcesToImage(node); + } + if (node.type === "element" && node.tagName === "img") { + node.properties = { + ...node.properties, + ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}), + ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}), + }; + } + node.children?.forEach(visit); + }; + + visit(tree); + markStandaloneImages(tree); + }; +} + +const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"]; + +// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first. +function normalizeLocalEditorHref(href: string): string { + try { + const url = new URL(href); + return isLocalEditorFileUrl(url) ? url.href : href; + } catch { + // Not an absolute URL; the sanitizer decides. + return href; + } +} + +export function rehypeNormalizeLocalEditorLinks() { + return (tree: MarkdownImageHastNode) => { + const visit = (node: MarkdownImageHastNode) => { + const href = node.properties?.href; + if (node.type === "element" && node.tagName === "a" && typeof href === "string") { + const normalized = normalizeLocalEditorHref(href); + if (normalized !== href) node.properties = { ...node.properties, href: normalized }; + } + node.children?.forEach(visit); + }; + + visit(tree); + }; +} + +export const CHAT_MARKDOWN_SANITIZE_SCHEMA = { + ...defaultSchema, + attributes: { + ...defaultSchema.attributes, + "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), + // Fence languages plus the two math classes the web chat's math plugin emits. + code: [ + ["className", /^language-./, "math-inline", "math-display"], + "dataCodeMeta", + "dataInlineCode", + ], + blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], + // Spaces typed at the start of a user's line (keepLeadingWhitespace). + span: [...(defaultSchema.attributes?.span ?? []), "dataLeadingWhitespace"], + div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES], + a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"], + img: [ + ...(defaultSchema.attributes?.img ?? []), + "dataDarkSrc", + "dataLightSrc", + "dataLocalSrc", + "dataMarkdownTitle", + "dataStandalone", + ], + }, + protocols: { + ...defaultSchema.protocols, + href: [ + ...(defaultSchema.protocols?.href ?? []), + "file", + "t3-citation", + "t3-context", + THREAD_LINK_PROTOCOL, + // Scheme only: the renderer's URL transform checks the rest of the link shape. + ...LOCAL_FILE_LINK_SCHEMES, + ], + src: IMAGE_SRC_PROTOCOLS, + dataDarkSrc: IMAGE_SRC_PROTOCOLS, + dataLightSrc: IMAGE_SRC_PROTOCOLS, + }, +} satisfies Schema; + +/** Sanitizes one tree with the chat's schema, as the last rehype plugin does. */ +export const sanitizeChatHast = (tree: Root): Root => + sanitize(tree, CHAT_MARKDOWN_SANITIZE_SCHEMA) as Root; + +export type ChatMarkdownImageProperties = { + readonly src?: unknown; + readonly dataLocalSrc?: unknown; + readonly dataDarkSrc?: unknown; + readonly dataLightSrc?: unknown; +}; + +/** Keep the authored path for file links and normalize Windows separators for classification. */ +export function chatMarkdownImageSource( + properties?: ChatMarkdownImageProperties, + theme?: "dark" | "light", +) { + const themeSrc = + theme === undefined + ? undefined + : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; + const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; + const source = + typeof themeSrc === "string" + ? themeSrc + : typeof localSrc === "string" + ? localSrc + : properties?.src; + if (typeof source !== "string") return null; + const authoredSrc = normalizeMarkdownLinkDestination(source); + return { + authoredSrc, + classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, + }; +} diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index a1f0af927636d..80204d903892b 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -174,6 +174,9 @@ describe("extractMarkdownLinkHrefs", () => { ["[".repeat(32_000), []], ["[a]( invalid [b](ok)", [" { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index fe450406093b3..e3458f04f3484 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -519,41 +519,36 @@ function markdownLinkDestinationScanner(markdown: string) { } } const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart); - if (hrefEnd === null || hrefEnd === hrefStart) return null; + if (hrefEnd === null) return null; const end = bareTail(hrefEnd); return end === null ? null : { hrefStart, hrefEnd, end }; }; } -// The composer escapes brackets in labels (`[\[id\].tsx](...)`), and `\]` does not close one. -function unescapedLabelEnd(markdown: string, start: number): number { - let end = markdown.indexOf("]", start); - while (end !== -1) { - let backslashes = 0; - while (end - backslashes > start && markdown[end - backslashes - 1] === "\\") backslashes += 1; - if (backslashes % 2 === 0) return end; - end = markdown.indexOf("]", end + 1); - } - return -1; -} - +// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them +// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels. export function extractMarkdownLinkHrefs(markdown: string): string[] { const hrefs: string[] = []; const scanDestination = markdownLinkDestinationScanner(markdown); - let cursor = 0; - while (cursor < markdown.length) { - const labelStart = markdown.indexOf("[", cursor); - if (labelStart === -1) break; - const labelEnd = unescapedLabelEnd(markdown, labelStart + 1); - if (labelEnd === -1) break; - - // Skip a failed label once; nested openings share its closing bracket. - cursor = labelEnd + 1; - const destination = scanDestination(cursor); - if (!destination) continue; - cursor = destination.end; - const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); - if (href) hrefs.push(href); + const bracket = /[[\]\\]|\n[ \t\r]*\n/g; + let openBrackets = 0; + for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) { + if (match[0] === "\\") { + bracket.lastIndex = match.index + 2; + } else if (match[0].startsWith("\n")) { + openBrackets = 0; + } else if (match[0] === "[") { + openBrackets += 1; + } else if (openBrackets > 0) { + openBrackets -= 1; + const destination = scanDestination(match.index + 1); + if (!destination) continue; + // A link cannot contain a link, so the brackets still open around it become text. + openBrackets = 0; + bracket.lastIndex = destination.end; + const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); + if (href) hrefs.push(href); + } } return hrefs; } @@ -651,3 +646,6 @@ export function absoluteFilePathMatches(text: string): Array<{ index: number; pa } return paths; } + +// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`. +export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/; diff --git a/apps/web/src/markdownListIndentation.test.tsx b/packages/shared/src/markdownListIndentation.test.ts similarity index 72% rename from apps/web/src/markdownListIndentation.test.tsx rename to packages/shared/src/markdownListIndentation.test.ts index 895d22f8bdac6..bcf56845f6cae 100644 --- a/apps/web/src/markdownListIndentation.test.tsx +++ b/packages/shared/src/markdownListIndentation.test.ts @@ -1,16 +1,21 @@ -import { renderToStaticMarkup } from "react-dom/server"; -import ReactMarkdown from "react-markdown"; +import { toHtml } from "hast-util-to-html"; import remarkGfm from "remark-gfm"; +import remarkParse from "remark-parse"; +import remarkRehype from "remark-rehype"; +import { type PluggableList, unified } from "unified"; import { describe, expect, it } from "vite-plus/test"; -import { remarkNormalizeListItemIndentation } from "@t3tools/shared/markdownListIndentation"; +import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts"; + +const processor = unified() + .use(remarkParse) + .use([remarkGfm, remarkNormalizeListItemIndentation] satisfies PluggableList) + .use(remarkRehype, { allowDangerousHtml: true }); function renderMarkdown(markdown: string): string { - return renderToStaticMarkup( - - {markdown} - , - ); + return toHtml(processor.runSync(processor.parse(markdown), markdown), { + allowDangerousHtml: true, + }); } describe("remarkNormalizeListItemIndentation", () => { @@ -26,7 +31,7 @@ describe("remarkNormalizeListItemIndentation", () => { expect(html).not.toContain("
    ");
         expect(html).toContain("
  • for (const step of rest.steps) {
  • "); expect(html).toContain("
  • if (step.request.body) {
  • "); - expect(html).toContain("
  • step.request.body = "<redacted>";
  • "); + expect(html).toContain('
  • step.request.body = "";
  • '); }); it("preserves every recovered block separated by blank lines", () => { diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index 53b49a03762a3..6bb022f532942 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -1,4 +1,3 @@ -import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; import type { Heading, Link, @@ -15,7 +14,7 @@ import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import { find, html } from "property-information"; import rehypeRaw from "rehype-raw"; -import rehypeSanitize, { defaultSchema } from "rehype-sanitize"; +import rehypeSanitize from "rehype-sanitize"; import remarkBreaks from "remark-breaks"; import remarkGfm from "remark-gfm"; import { remarkGithubAlerts } from "./markdownGithubAlerts.ts"; @@ -25,17 +24,18 @@ import { remarkEnableLeadingWhitespace, remarkKeepLeadingWhitespace, } from "./markdownLeadingWhitespace.ts"; -import { - CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES, - remarkCodexDirectives, -} from "./codexMarkdownDirectives.ts"; -import { - absoluteFilePathMatches, - isWindowsDrivePathHref, - normalizeMarkdownLinkDestination, -} from "./markdownLinks.ts"; +import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts"; +import { absoluteFilePathMatches } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; -import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts"; +import { + CHAT_MARKDOWN_SANITIZE_SCHEMA, + chatMarkdownImageSource, + rehypeNormalizeLocalEditorLinks, + rehypePreserveImageSourceMeta, + type ChatMarkdownImageProperties, +} from "./markdownHast.ts"; + +export { chatMarkdownImageSource, type ChatMarkdownImageProperties }; export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts"; @@ -47,44 +47,6 @@ type MarkdownImageHastNode = { children?: MarkdownImageHastNode[]; }; -function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] { - return (node.children ?? []).filter( - (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""), - ); -} - -const STANDALONE_IMAGE_BLOCKS = new Set([ - "p", - "div", - "li", - "td", - "th", - "figure", - "center", - "blockquote", -]); - -function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined { - const children = meaningfulHastChildren(node); - if (children.length !== 1) return undefined; - const only = children[0]; - if (only?.type !== "element") return undefined; - if (only.tagName === "img") return only; - return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em" - ? soleImageDescendant(only) - : undefined; -} - -function markStandaloneImages(node: MarkdownImageHastNode) { - if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) { - const image = soleImageDescendant(node); - if (image) image.properties = { ...image.properties, dataStandalone: true }; - } - node.children?.forEach((child) => { - if (child.type === "element") markStandaloneImages(child); - }); -} - // Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag. const RAW_HTML_TAG_PATTERN = /|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g; @@ -133,121 +95,6 @@ function rehypePreserveBareAnchorPlaceholders() { }; } -const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i; - -/** - * The renderer resolves an ``'s `src` (workspace files, host media) but never a ``'s - * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves - * onto the `` for the renderer to pick by theme; every source is then dropped. - */ -function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) { - if (!picture.children) return; - const image = picture.children.find((child) => child.tagName === "img"); - for (const source of picture.children) { - if (source.tagName !== "source" || !image) continue; - const media = source.properties?.media; - const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined; - const srcSet = source.properties?.srcSet; - const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet; - // A candidate's URL runs to the first space (a descriptor such as `2x` may follow). - const url = - typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : ""; - const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc"; - // As in a browser, the first source that matches a scheme is the one shown. - if (scheme && url && image.properties?.[key] === undefined) { - // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path. - const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url; - image.properties = { ...image.properties, [key]: value }; - } - } - picture.children = picture.children.filter((child) => child.tagName !== "source"); -} - -function rehypePreserveImageSourceMeta() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const src = node.properties?.src; - const title = node.properties?.title; - if (node.type === "element" && node.tagName === "picture") { - moveColorSchemeSourcesToImage(node); - } - if (node.type === "element" && node.tagName === "img") { - node.properties = { - ...node.properties, - ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}), - ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}), - }; - } - node.children?.forEach(visit); - }; - - visit(tree); - markStandaloneImages(tree); - }; -} - -const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"]; - -// The sanitizer compares schemes case-sensitively, so lowercase accepted editor links first. -function rehypeNormalizeLocalEditorLinks() { - return (tree: MarkdownImageHastNode) => { - const visit = (node: MarkdownImageHastNode) => { - const href = node.properties?.href; - if (node.type === "element" && node.tagName === "a" && typeof href === "string") { - try { - const url = new URL(href); - if (isLocalEditorFileUrl(url)) node.properties = { ...node.properties, href: url.href }; - } catch { - // Not an absolute URL; the sanitizer decides. - } - } - node.children?.forEach(visit); - }; - - visit(tree); - }; -} - -const CHAT_MARKDOWN_SANITIZE_SCHEMA = { - ...defaultSchema, - attributes: { - ...defaultSchema.attributes, - "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"), - // Fence languages plus the two math classes the web chat's math plugin emits. - code: [ - ["className", /^language-./, "math-inline", "math-display"], - "dataCodeMeta", - "dataInlineCode", - ], - blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"], - div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES], - a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"], - img: [ - ...(defaultSchema.attributes?.img ?? []), - "dataDarkSrc", - "dataLightSrc", - "dataLocalSrc", - "dataMarkdownTitle", - "dataStandalone", - ], - }, - protocols: { - ...defaultSchema.protocols, - href: [ - ...(defaultSchema.protocols?.href ?? []), - "file", - "t3-citation", - "t3-context", - THREAD_LINK_PROTOCOL, - // Scheme only: the renderer's URL transform checks the rest of the link shape. - ...LOCAL_FILE_LINK_SCHEMES, - ], - src: IMAGE_SRC_PROTOCOLS, - dataDarkSrc: IMAGE_SRC_PROTOCOLS, - dataLightSrc: IMAGE_SRC_PROTOCOLS, - }, -} satisfies Parameters[0]; - export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkGfm, remarkEndAutolinksAtScriptPunctuation, @@ -752,10 +599,6 @@ function remarkNormalizeLinksAndTagInlineCode() { }; } -export function shouldPreserveAssistantLineBreaks(text: string): boolean { - return /^★ Insight(?:\s|─)/mu.test(text); -} - export function remarkAssistantInsights(this: Processor) { return (tree: Root, file: { value: unknown }) => { const source = String(file.value); @@ -840,37 +683,6 @@ const imageSourceProcessor = unified() .use(remarkRehype, { allowDangerousHtml: true }) .use(CHAT_MARKDOWN_REHYPE_PLUGINS); -export type ChatMarkdownImageProperties = { - readonly src?: unknown; - readonly dataLocalSrc?: unknown; - readonly dataDarkSrc?: unknown; - readonly dataLightSrc?: unknown; -}; - -/** Keep the authored path for file links and normalize Windows separators for classification. */ -export function chatMarkdownImageSource( - properties?: ChatMarkdownImageProperties, - theme?: "dark" | "light", -) { - const themeSrc = - theme === undefined - ? undefined - : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"]; - const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc; - const source = - typeof themeSrc === "string" - ? themeSrc - : typeof localSrc === "string" - ? localSrc - : properties?.src; - if (typeof source !== "string") return null; - const authoredSrc = normalizeMarkdownLinkDestination(source); - return { - authoredSrc, - classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc, - }; -} - interface ImageSourceNode { readonly type: string; readonly tagName?: string; diff --git a/packages/shared/src/markdownTaskEdits.ts b/packages/shared/src/markdownTaskEdits.ts new file mode 100644 index 0000000000000..2f33428613147 --- /dev/null +++ b/packages/shared/src/markdownTaskEdits.ts @@ -0,0 +1,28 @@ +/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ +export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { + const firstLineEnd = markdown.indexOf("\n", listItemStart); + const firstLine = markdown.slice( + listItemStart, + firstLineEnd === -1 ? markdown.length : firstLineEnd, + ); + const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); + if (!match?.[1]) return null; + return listItemStart + firstLine.indexOf(match[1]); +} + +export function setMarkdownTaskChecked( + markdown: string, + markerOffset: number, + checked: boolean, +): string { + if ( + markerOffset < 0 || + markdown[markerOffset] !== "[" || + !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || + markdown[markerOffset + 2] !== "]" + ) { + return markdown; + } + + return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; +} diff --git a/packages/shared/src/markdownTaskList.test.ts b/packages/shared/src/markdownTaskList.test.ts index 5e00a3926fa54..7f7519ce49ee5 100644 --- a/packages/shared/src/markdownTaskList.test.ts +++ b/packages/shared/src/markdownTaskList.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; -import { markdownTaskMarkerOffset, setMarkdownTaskChecked } from "./markdownTaskList.ts"; +import { markdownTaskMarkerOffset } from "./markdownTaskList.ts"; +import { setMarkdownTaskChecked } from "./markdownTaskEdits.ts"; describe("setMarkdownTaskChecked", () => { const markdown = "- [ ] First\n- [x] Second\n"; diff --git a/packages/shared/src/markdownTaskList.ts b/packages/shared/src/markdownTaskList.ts index fb02f757992b9..a4d18895505c6 100644 --- a/packages/shared/src/markdownTaskList.ts +++ b/packages/shared/src/markdownTaskList.ts @@ -3,36 +3,9 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import { unified } from "unified"; -const parser = unified().use(remarkParse).use(remarkGfm); - -/** Offset of the `[ ]` marker on the first line of the list item starting at `listItemStart`. */ -export function taskListMarkerOffset(markdown: string, listItemStart: number): number | null { - const firstLineEnd = markdown.indexOf("\n", listItemStart); - const firstLine = markdown.slice( - listItemStart, - firstLineEnd === -1 ? markdown.length : firstLineEnd, - ); - const match = firstLine.match(/^(?:\s*(?:[-+*]|\d+[.)])\s+)(\[[ xX]\])/); - if (!match?.[1]) return null; - return listItemStart + firstLine.indexOf(match[1]); -} - -export function setMarkdownTaskChecked( - markdown: string, - markerOffset: number, - checked: boolean, -): string { - if ( - markerOffset < 0 || - markdown[markerOffset] !== "[" || - !/[ xX]/.test(markdown[markerOffset + 1] ?? "") || - markdown[markerOffset + 2] !== "]" - ) { - return markdown; - } +import { taskListMarkerOffset } from "./markdownTaskEdits.ts"; - return `${markdown.slice(0, markerOffset + 1)}${checked ? "x" : " "}${markdown.slice(markerOffset + 2)}`; -} +const parser = unified().use(remarkParse).use(remarkGfm); /** Hard breaks as U+2028, as iOS draws them; soft breaks stay "\n". */ function plainText(node: Nodes): string { diff --git a/packages/shared/src/markdownWindowsPaths.ts b/packages/shared/src/markdownWindowsPaths.ts index c4c04490a2140..d7c827c8dba8c 100644 --- a/packages/shared/src/markdownWindowsPaths.ts +++ b/packages/shared/src/markdownWindowsPaths.ts @@ -1,5 +1,6 @@ import type { Processor } from "unified"; import { decodeString } from "micromark-util-decode-string"; +import { UNFINISHED_DRIVE_PATH } from "./markdownLinks.ts"; import { isWindowsAbsolutePath } from "./path.ts"; interface DestinationCompileContext { @@ -18,9 +19,6 @@ function keepWindowsPathDestination(this: DestinationCompileContext, token: unkn : decoded; } -// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`. -export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/; - interface EscapeCompileContext { readonly stack: ReadonlyArray<{ readonly type: string; diff --git a/packages/shared/src/orchestrationV2ManualContinuation.test.ts b/packages/shared/src/orchestrationV2ManualContinuation.test.ts index 137bf6cd8f205..e7670749f6c5a 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.test.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.test.ts @@ -108,4 +108,16 @@ describe("unsentManualContinuationSource", () => { unsentManualContinuationSource(run("c", "a" as RunId), projection([a, b], [], [])), ).toBeUndefined(); }); + + it("treats a turn with promptDropped as unsent", () => { + const source = run("src"); + const a1 = attempt("a1", "src", 1); + const dropped = { ...turn("a1"), promptDropped: true as const }; + expect( + unsentManualContinuationSource( + run("r2", "src" as RunId), + projection([source], [a1], [dropped]), + ), + ).toBe(source); + }); }); diff --git a/packages/shared/src/orchestrationV2ManualContinuation.ts b/packages/shared/src/orchestrationV2ManualContinuation.ts index 3fb6c8d5a1866..ad64b63483e14 100644 --- a/packages/shared/src/orchestrationV2ManualContinuation.ts +++ b/packages/shared/src/orchestrationV2ManualContinuation.ts @@ -1,4 +1,8 @@ -import type { OrchestrationV2Run, OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { + isDeliveredProviderTurn, + type OrchestrationV2Run, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; export function unsentManualContinuationSource( run: Pick | undefined, @@ -7,7 +11,9 @@ export function unsentManualContinuationSource( let sourceId = run?.manualContinuationOfRunId; if (sourceId === undefined) return undefined; const runs = new Map(projection.runs.map((source) => [source.id, source])); - const acceptedAttempts = new Set(projection.providerTurns.map((turn) => turn.runAttemptId)); + const acceptedAttempts = new Set( + projection.providerTurns.filter(isDeliveredProviderTurn).map((turn) => turn.runAttemptId), + ); const latestAttempt = ( runId: OrchestrationV2Run["id"], matches: (attempt: (typeof projection.attempts)[number]) => boolean, diff --git a/packages/shared/src/orchestrationV2ThreadError.ts b/packages/shared/src/orchestrationV2ThreadError.ts index 8987593a0b0a5..1e011eb1c64fd 100644 --- a/packages/shared/src/orchestrationV2ThreadError.ts +++ b/packages/shared/src/orchestrationV2ThreadError.ts @@ -86,6 +86,7 @@ export function orchestrationV2WorktreePending( (latest?.status === "preparing" || latest?.status === "failed" || latest?.status === "interrupted") && + latest.startedAt === null && latest.workspacePreparation?.type === "worktree" ); } diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index d9950edc60cfb..8f81723486f55 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -22,6 +22,8 @@ import { pathSetupCommand, CommandAvailability, CommandResolutionCache, + makePathDirectoryListings, + PathDirectoryListings, type CommandAvailabilityChecker, gitForWindowsBash, isCommandAvailable, @@ -39,7 +41,6 @@ import { windowsEnvironmentValueCommand, SpawnExecutableResolution, WindowsShellEnvironment, - withPathDirectoryListings, type WindowsShellEnvironmentReader, XcodeGitLocation, } from "./shell.ts"; @@ -576,7 +577,9 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ), ).toBe(path.join(directory, "audit-command")); const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); + expect( + yield* Effect.promise(async () => resolveExecutable("audit-command", "linux", env)), + ).toBe(executable); }), ); @@ -591,7 +594,8 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { stat: (filePath) => Effect.sync(() => { probed.push(filePath); - return { type: "Directory" } as FileSystem.File.Info; + // No mtime, so no listing: every candidate is probed directly. + return { type: "Directory", mtime: Option.none() } as FileSystem.File.Info; }), }), ), @@ -609,7 +613,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { }); // Windows PATH directories can be case-sensitive; preserve both spellings. - expect(probed).toHaveLength(8); + expect(probed.filter((file) => file.includes("definitely-not-installed"))).toHaveLength(8); }), ); @@ -635,7 +639,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ...fs, stat: (filePath) => fs.stat( - filePath === executable || filePath === decoy + [cwd, executable, decoy].includes(filePath) ? filePath : path.join(cwd, "missing"), ), @@ -646,38 +650,117 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { }), ); - it.effect("probes only listed PATH names and relists a directory that changes", () => + // Seconds; the tests below run their clock a minute later, past the window in which a listing is not kept. + const AGED_MTIME = 4_102_444_800; + const afterAgedMtime = TestClock.setTime((AGED_MTIME + 60) * 1000); + + it.effect("reuses PATH listings across lookups until a directory changes", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const first = yield* fs.makeTempDirectoryScoped(); const second = yield* fs.makeTempDirectoryScoped(); yield* fs.writeFileString(path.join(first, "cursor.CMD"), ""); + yield* fs.writeFileString(path.join(first, "MyToolLongName.cmd"), ""); yield* fs.writeFileString(path.join(second, "cursor.EXE"), ""); + yield* fs.utimes(first, AGED_MTIME, AGED_MTIME); + yield* fs.utimes(second, AGED_MTIME, AGED_MTIME); + yield* afterAgedMtime; const env = { PATH: `${first};${second}`, PATHEXT: ".EXE;.CMD" }; + // Windows resolves an 8.3 alias that a directory listing never names. + const alias = path.join(first, "MYTOOL~1.CMD"); const probed: Array = []; + const listed: Array = []; yield* Effect.gen(function* () { expect(yield* resolveCommandPath("cursor", { env })).toBe(path.join(first, "cursor.CMD")); expect(yield* isCommandAvailable("absent", { env })).toBe(false); + expect(yield* isCommandAvailable("also-absent", { env })).toBe(false); + expect(yield* resolveCommandPath("MYTOOL~1", { env })).toBe(alias); + expect(listed).toEqual([first, second]); yield* fs.writeFileString(path.join(second, "late.EXE"), ""); - yield* fs.utimes(second, 4_102_444_800, 4_102_444_800); + yield* fs.utimes(second, AGED_MTIME + 30, AGED_MTIME + 30); expect(yield* resolveCommandPath("late", { env })).toBe(path.join(second, "late.EXE")); + expect(listed).toEqual([first, second, second]); }).pipe( - withPathDirectoryListings, Effect.provideService(FileSystem.FileSystem, { ...fs, stat: (file) => { if (file !== first && file !== second) probed.push(file); - return fs.stat(file); + return fs.stat(file === alias ? path.join(first, "MyToolLongName.cmd") : file); + }, + readDirectory: (directory, options) => { + listed.push(directory); + return fs.readDirectory(directory, options); }, }), ); - expect(probed).toEqual([path.join(first, "cursor.CMD"), path.join(second, "late.EXE")]); + expect(probed).toEqual([ + path.join(first, "cursor.CMD"), + path.join(first, "MYTOOL~1.EXE"), + path.join(first, "MYTOOL~1.exe"), + alias, + path.join(second, "late.EXE"), + ]); }).pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(CommandResolutionCache, new Map()), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), ), ); + + it.effect("does not keep the listing of a PATH directory that changed moments ago", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped(); + yield* fs.utimes(directory, AGED_MTIME + 59, AGED_MTIME + 59); + yield* afterAgedMtime; + const env = { PATH: directory, PATHEXT: ".CMD" }; + let listings = 0; + yield* Effect.gen(function* () { + expect(yield* isCommandAvailable("absent", { env })).toBe(false); + expect(yield* isCommandAvailable("also-absent", { env })).toBe(false); + }).pipe( + Effect.provideService(FileSystem.FileSystem, { + ...fs, + readDirectory: (target, options) => { + listings += 1; + return fs.readDirectory(target, options); + }, + }), + ); + expect(listings).toBe(2); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + Effect.provideServiceEffect(PathDirectoryListings, makePathDirectoryListings), + ), + ); + + // A POSIX directory joined with win32 separators names nothing, so this needs a Windows host. + it.effect.skipIf(HostProcess.Platform.defaultValue() !== "win32")( + "relists a changed PATH directory in the spawn resolver", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(path.join(directory, "cursor.CMD"), ""); + yield* fs.utimes(directory, 946_684_800, 946_684_800); + const env = { PATH: directory, PATHEXT: ".EXE;.CMD" }; + const resolveExecutable = yield* SpawnExecutableResolution; + expect(yield* Effect.promise(async () => resolveExecutable("cursor", "win32", env))).toBe( + path.join(directory, "cursor.CMD"), + ); + expect( + yield* Effect.promise(async () => resolveExecutable("late", "win32", env)), + ).toBeUndefined(); + yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); + yield* fs.utimes(directory, 946_684_830, 946_684_830); + expect(yield* Effect.promise(async () => resolveExecutable("late", "win32", env))).toBe( + path.join(directory, "late.EXE"), + ); + }), + ); }); describe("runsGitWithoutConsole", () => { @@ -900,6 +983,73 @@ describe("npmShimExecutable", () => { }); effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { + it.effect("yields while discovering a Windows executable", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const executable = path.join(directory, "tool.EXE"); + yield* fs.writeFileString(executable, ""); + let settled = false; + const pending = Promise.resolve( + SpawnExecutableResolution.defaultValue()(executable, "win32", { PATHEXT: ".EXE;.CMD" }), + ).then((value) => { + settled = true; + return value; + }); + try { + yield* Effect.promise(() => Promise.resolve()); + expect(settled).toBe(false); + } finally { + expect(yield* Effect.promise(() => pending)).toBe(executable); + } + }), + ), + ); + + it.effect("preserves PATH and PATHEXT order and discovers executables after a miss", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const fixture = NodePath.join(directory, "tool.EXE"); + yield* fs.writeFileString(fixture, ""); + const stat = yield* Effect.promise(() => NodeFS.promises.stat(fixture)); + const files = new Set(); + using _stat = vi.spyOn(NodeFS.promises, "stat").mockImplementation(async (candidate) => { + if (!files.has(String(candidate))) throw new Error("not found"); + return stat; + }); + const lookup = resolveSpawnCommand("tool", ["status"], { + env: { PATH: "C:\\first;C:\\later", PATHEXT: ".EXE;.CMD" }, + }); + expect((yield* lookup).command).toBe("tool"); + files.add("C:\\first\\tool.CMD"); + files.add("C:\\first\\tool.EXE"); + files.add("C:\\later\\tool.EXE"); + expect(yield* lookup).toEqual({ + command: "C:\\first\\tool.EXE", + args: ["status"], + shell: false, + }); + files.delete("C:\\first\\tool.EXE"); + expect((yield* lookup).command).toBe("C:\\first\\tool.EXE"); + expect( + yield* Effect.promise(async () => + SpawnExecutableResolution.defaultValue()("tool", "win32", { + PATH: "C:\\first;C:\\later", + PATHEXT: ".EXE;.CMD", + }), + ), + ).toBe("C:\\first\\tool.CMD"); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + ), + ), + ); + it.effect("runs Windows executables directly without a shell", () => Effect.gen(function* () { const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 8ccb466775c1f..0ba42dc3078d6 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -7,6 +7,7 @@ import * as Cache from "effect/Cache"; import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -74,13 +75,13 @@ export type SpawnExecutableResolver = ( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -) => string | undefined; +) => string | undefined | Promise; -function resolveSpawnExecutableWithNode( +async function resolveSpawnExecutableWithNode( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -): string | undefined { +): Promise { const path = platform === "win32" ? NodePath.win32 : NodePath.posix; const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; const candidates = resolveCommandCandidates( @@ -89,28 +90,37 @@ function resolveSpawnExecutableWithNode( windowsPathExtensions, path.extname, ); - const isExecutable = (candidate: string) => { + const isExecutable = async (candidate: string) => { try { - if (!NodeFS.statSync(candidate).isFile()) return false; + if (!(await NodeFS.promises.stat(candidate)).isFile()) return false; if (platform === "win32") { return windowsPathExtensions.includes(path.extname(candidate).toUpperCase()); } - return canExecuteFile(candidate); + await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); + return true; } catch { return false; } }; if (command.includes("/") || command.includes("\\")) { - return candidates.find(isExecutable); + for (const candidate of candidates) { + if (await isExecutable(candidate)) return candidate; + } + return undefined; } for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { const normalizedPathEntry = normalizePathEntry(pathEntry, platform); if (normalizedPathEntry.length === 0) continue; + const names = + platform === "win32" + ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute) + : undefined; for (const candidate of candidates) { + if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); - if (isExecutable(candidatePath)) return candidatePath; + if (await isExecutable(candidatePath)) return candidatePath; } } return undefined; @@ -578,7 +588,38 @@ export const CommandResolutionCache = Context.Reference | undefined; + readonly reusable: boolean; +} + +const PATH_DIRECTORY_LISTINGS_MAX_ENTRIES = 1024; +// A directory changed within a coarse filesystem's timestamp step (FAT: 2 s) can change again +// without moving its mtime, so its listing serves the lookups waiting on it but is not kept. +const PATH_DIRECTORY_SETTLE_MS = 2_000; +const NO_DIRECTORY_NAMES: ReadonlySet = new Set(); + +// A listing only speaks for names Windows matches by ASCII case folding. It omits 8.3 aliases +// (`~`), Windows trims a trailing dot, and other characters fold differently than in JS. +const LISTED_NAME_PATTERN = /^[\w.+-]*[\w+-]$/; + +function isAbsentFromListing(names: ReadonlySet | undefined, candidate: string): boolean { + return ( + names !== undefined && + LISTED_NAME_PATTERN.test(candidate) && + !names.has(candidate.toLowerCase()) + ); +} + +// The listing must start after the mtime's timestamp step has passed, and a relative entry +// names another directory once the working directory changes. +function isReusableListing( + directory: string, + modified: number, + listedAtMs: number, + isAbsolute: (path: string) => boolean, +): boolean { + return isAbsolute(directory) && listedAtMs - modified >= PATH_DIRECTORY_SETTLE_MS; } const directoryMtime = (directory: string) => @@ -592,29 +633,77 @@ const directoryMtime = (directory: string) => // Timestamp before reading so concurrent additions change the next mtime check; missing listings fall back to direct probes. const listPathDirectory = Effect.fnUntraced(function* ( directory: string, -): Effect.fn.Return { +): Effect.fn.Return { + const path = yield* Path.Path; const modified = yield* directoryMtime(directory); - if (modified == null) return { modified, names: modified === null ? new Set() : undefined }; + if (modified === null) { + return { modified, names: NO_DIRECTORY_NAMES, reusable: path.isAbsolute(directory) }; + } + if (modified === undefined) return { modified, names: undefined, reusable: false }; + const listedAtMs = yield* Clock.currentTimeMillis; const entries = yield* FileSystem.FileSystem.use((fileSystem) => fileSystem.readDirectory(directory), ).pipe(Effect.orElseSucceed(() => undefined)); - return { modified, names: entries && new Set(entries.map((entry) => entry.toLowerCase())) }; + return { + modified, + names: entries && new Set(entries.map((entry) => entry.toLowerCase())), + reusable: + entries !== undefined && isReusableListing(directory, modified, listedAtMs, path.isAbsolute), + }; }); -const PathDirectoryListings = Context.Reference< - Cache.Cache | undefined ->("@t3tools/shared/shell/PathDirectoryListings", { defaultValue: () => undefined }); - -export const withPathDirectoryListings = - /* Directory reads are cached inside one shell operation; a span for each lookup adds noise. */ - Effect.fnUntraced(function* (effect: Effect.Effect) { - const listings = yield* Cache.make({ - capacity: 1024, - lookup: listPathDirectory, - requireServicesAt: "lookup", - }); - return yield* effect.pipe(Effect.provideService(PathDirectoryListings, listings)); - }); +export const makePathDirectoryListings = Cache.makeWith(listPathDirectory, { + capacity: PATH_DIRECTORY_LISTINGS_MAX_ENTRIES, + timeToLive: (exit) => + Exit.isSuccess(exit) && exit.value.reusable ? Duration.infinity : Duration.zero, + requireServicesAt: "lookup", +}); + +/** Windows PATH directory listings for the process; each use rechecks the directory's mtime. */ +export const PathDirectoryListings = Context.Reference( + "@t3tools/shared/shell/PathDirectoryListings", + { defaultValue: () => Effect.runSync(makePathDirectoryListings) }, +); + +const resolverPathDirectoryListings = new Map< + string, + { readonly modified: number; readonly names: ReadonlySet } +>(); + +// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules. +async function listResolverPathDirectory( + directory: string, + isAbsolute: (path: string) => boolean, +): Promise | undefined> { + let modified: number; + try { + const stats = await NodeFS.promises.stat(directory); + if (!stats.isDirectory()) return undefined; + modified = stats.mtimeMs; + } catch (error) { + return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; + } + const cached = resolverPathDirectoryListings.get(directory); + if (cached?.modified === modified) return cached.names; + resolverPathDirectoryListings.delete(directory); + // This resolver runs outside Effect, so it has no Clock to read. + // @effect-diagnostics-next-line globalDate:off + const listedAtMs = Date.now(); + let names: ReadonlySet; + try { + names = new Set((await NodeFS.promises.readdir(directory)).map((entry) => entry.toLowerCase())); + } catch { + return undefined; + } + if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { + if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = resolverPathDirectoryListings.keys().next().value; + if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest); + } + resolverPathDirectoryListings.set(directory, { modified, names }); + } + return names; +} // An injected resolver or locator may answer differently for the same search, so its // entries are kept apart from every other resolver's. @@ -685,7 +774,8 @@ const findOnPath = Effect.fnUntraced(function* ( pathEntries.push(pathEntry); } - const listings = yield* PathDirectoryListings; + // Only Windows multiplies the candidates per directory; elsewhere a listing saves no probe. + const listings = platform === "win32" ? yield* PathDirectoryListings : undefined; const matches: string[] = []; for (const pathEntry of pathEntries) { let listing = listings && (yield* Cache.get(listings, pathEntry)); @@ -694,7 +784,7 @@ const findOnPath = Effect.fnUntraced(function* ( listing = yield* Cache.get(listings, pathEntry); } for (const candidate of commandCandidates) { - if (listing?.names && !listing.names.has(candidate.toLowerCase())) continue; + if (isAbsentFromListing(listing?.names, candidate)) continue; const candidatePath = path.join(pathEntry, candidate); if (yield* isExecutableFile(candidatePath, platform, windowsPathExtensions)) { matches.push(candidatePath); @@ -916,18 +1006,21 @@ const resolveMacosGit = Effect.fnUntraced(function* ( const nowNanos = yield* Clock.currentTimeNanos; const cached = cache.get(cacheKey); // An Xcode update or removal deletes the binary; look again instead of failing the spawn. - if ( - cached !== undefined && - cached.expiresAtNanos > nowNanos && - (cached.resolvedPath === null || - resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined) - ) { - return cached.resolvedPath ?? "git"; + if (cached !== undefined && cached.expiresAtNanos > nowNanos) { + const cachedPath = cached.resolvedPath; + if ( + cachedPath === null || + (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== + undefined + ) { + return cachedPath ?? "git"; + } } - const located = - resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); + const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = - located !== undefined && resolveExecutable(located, "darwin", env) !== undefined + located !== undefined && + (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined ? located : null; cacheCommandResolution(cache, cacheKey, realGit, nowNanos); @@ -1007,10 +1100,8 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( shell: false, }; } - // The scan is synchronous and runs before every child process, so it shares - // the PATH scan cache above. Explicit paths stay uncached for the same reason, - // and so do misses: a failed spawn is how providers report "not installed", - // and that has to clear the moment the binary appears. + // Cache successful PATH lookups. Explicit paths and misses stay uncached so + // newly installed executables are discoverable immediately. const explicitPath = command.includes("/") || command.includes("\\"); const cache = yield* CommandResolutionCache; const cacheKey = [ @@ -1028,7 +1119,7 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( if (cached !== undefined && cached.expiresAtNanos > nowNanos) { resolvedExecutable = cached.resolvedPath; } else { - const found = resolveExecutable(command, platform, env); + const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env)); resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env); if (!explicitPath && resolvedExecutable !== null) { cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos); diff --git a/packages/shared/src/textDirection.ts b/packages/shared/src/textDirection.ts index 0d4a7d88fd837..1efe672108cad 100644 --- a/packages/shared/src/textDirection.ts +++ b/packages/shared/src/textDirection.ts @@ -2,8 +2,8 @@ export type TextDirection = "ltr" | "rtl"; // Hebrew through Arabic Extended-A, their presentation forms, and the // supplementary right-to-left blocks. -const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; -const LETTER = /\p{L}/u; +export const RTL_LETTER = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u; +export const LETTER = /\p{L}/u; const SENTENCE_END = /(?<=[.!?؟])(? { AzureDevOpsCli.azureCliInvocation().pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }), - Effect.provideService(SpawnExecutableResolution, () => launcher), + Effect.provideService(SpawnExecutableResolution, async () => launcher), Effect.provideService(AzureCliInstallLocation, () => install), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts index 6cffe9ab0b3ab..f289e7406950f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts @@ -495,7 +495,8 @@ export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(functio return { command: "az", args: [] } satisfies AzureCliInvocation; } const resolveExecutable = yield* SpawnExecutableResolution; - const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const launcher = yield* Effect.promise(async () => resolveExecutable("az", "win32", env)); const installFor = yield* AzureCliInstallLocation; const install = launcher === undefined ? undefined : installFor(launcher); // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode. diff --git a/packages/source-control-core/src/server/IssueTrackerHost.ts b/packages/source-control-core/src/server/IssueTrackerHost.ts index efc51b5046de2..eb85a2f711a5e 100644 --- a/packages/source-control-core/src/server/IssueTrackerHost.ts +++ b/packages/source-control-core/src/server/IssueTrackerHost.ts @@ -2,12 +2,12 @@ * What a standalone tracker package may ask of the server it runs in: the credential the user * saved in Settings. Git-host trackers never need it; their CLIs carry their own credentials. */ -import type { IssueTrackerKind } from "@t3tools/contracts"; +import type { IssueTrackerAccountId, IssueTrackerKind } from "@t3tools/contracts"; import * as Context from "effect/Context"; -import type * as Effect from "effect/Effect"; +import * as Effect from "effect/Effect"; import type * as Option from "effect/Option"; -import type { IssueTrackerError } from "./IssueTracker.ts"; +import type { IssueTrackerApi, IssueTrackerError } from "./IssueTracker.ts"; export class IssueTrackerHost extends Context.Service< IssueTrackerHost, @@ -20,3 +20,53 @@ export class IssueTrackerHost extends Context.Service< }; } >()("@t3tools/source-control-core/server/IssueTrackerHost") {} + +/** + * The account a standalone tracker call is made as, set by the server around each call; null is + * the tracker's first account. A tracker never reads it: `credentials.get` does. + */ +export const IssueTrackerAccount = Context.Reference( + "@t3tools/source-control-core/server/IssueTrackerHost/IssueTrackerAccount", + { defaultValue: () => null }, +); + +/** The tracker with every call made as one account, so no call site can forget to name it. */ +export function asIssueTrackerAccount( + api: IssueTrackerApi, + accountId: IssueTrackerAccountId | null, +): IssueTrackerApi { + if (accountId === null) return api; + const as = (effect: Effect.Effect) => + Effect.provideService(effect, IssueTrackerAccount, accountId); + const { + getIssueLink, + create, + comment, + update, + setState, + setReaction, + listTemplates, + listCandidates, + } = api; + // Every key is required here, so a method added to IssueTrackerApi fails to compile until it + // is wrapped instead of silently running as the first account. + const wrapped: { readonly [K in keyof IssueTrackerApi]-?: IssueTrackerApi[K] | undefined } = { + kind: api.kind, + capabilities: api.capabilities, + getViewer: (input) => as(api.getViewer(input)), + listIssues: (input) => as(api.listIssues(input)), + getIssue: (input) => as(api.getIssue(input)), + getComments: (input) => as(api.getComments(input)), + getIssueLink: getIssueLink && ((input) => as(getIssueLink(input))), + create: create && ((input) => as(create(input))), + comment: comment && ((input) => as(comment(input))), + update: update && ((input) => as(update(input))), + setState: setState && ((input) => as(setState(input))), + setReaction: setReaction && ((input) => as(setReaction(input))), + listTemplates: listTemplates && ((input) => as(listTemplates(input))), + listCandidates: listCandidates && ((input) => as(listCandidates(input))), + }; + return Object.fromEntries( + Object.entries(wrapped).filter(([, value]) => value !== undefined), + ) as unknown as IssueTrackerApi; +} diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index 4db5f263daba1..fffa0feb4014b 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -40,6 +40,7 @@ import type { PullRequestPreview, PullRequestUpdateMethod, PullRequestViewerPermissions, + PullRequestVisibility, SourceControlProviderKind, } from "@t3tools/contracts"; import { SourceControlProviderKind as SourceControlProviderKindSchema } from "@t3tools/contracts"; @@ -108,6 +109,8 @@ export interface ProviderChangeRequest { readonly labels: ReadonlyArray; readonly reviewDecision?: PullRequestReviewDecision | null | undefined; readonly checksState?: PullRequestChecksState | null | undefined; + /** Absent where the host has no private change requests or names no visibility. */ + readonly visibility?: PullRequestVisibility; } export interface ProviderChangeRequestSummary { diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index 4a6e93ab74f45..ccf23f59b2258 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -173,6 +173,18 @@ export class SourceControlProvider extends Context.Service< }) => Effect.Effect; /** True when `createChangeRequest` opens the change request as a draft when asked. */ readonly createsDraftChangeRequests?: boolean; + /** + * The private companion of the checkout's repository, made when it has none. The branch of + * a private change request is pushed to `url` and never to the repository itself, which + * everyone can read. Absent on a host without private change requests. + */ + readonly privateChangeRequestRemote?: (input: { + readonly cwd: string; + readonly context?: SourceControlProviderContext; + }) => Effect.Effect< + { readonly url: string; readonly repository: string }, + SourceControlProviderError + >; readonly listChangeRequests: (input: { readonly cwd: string; readonly context?: SourceControlProviderContext; @@ -202,6 +214,8 @@ export class SourceControlProvider extends Context.Service< readonly bodyFile: string; /** Honored only by a provider with `createsDraftChangeRequests`. */ readonly draft?: boolean; + /** Asked only of a provider with `privateChangeRequestRemote`, which holds the head. */ + readonly private?: boolean; }) => Effect.Effect; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; diff --git a/packages/source-control-core/src/server/discovery.ts b/packages/source-control-core/src/server/discovery.ts index 62ec94d7d67fe..0cc6654adf021 100644 --- a/packages/source-control-core/src/server/discovery.ts +++ b/packages/source-control-core/src/server/discovery.ts @@ -357,7 +357,8 @@ const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(fun return installHint; } const resolveExecutable = yield* SpawnExecutableResolution; - const path = resolveExecutable(executable, platform, yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const path = yield* Effect.promise(async () => resolveExecutable(executable, platform, env)); const architecture = yield* HostProcess.Architecture; return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`; }); diff --git a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts index 7b6e475f99152..1c088a58e8876 100644 --- a/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts +++ b/packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.ts @@ -24,6 +24,7 @@ import { unknownRemoteProvider, } from "@t3tools/source-control-core/shared/definition"; import { ForgejoPullRequestSchema, toForgejoChangeRequest } from "./forgejoPullRequests.ts"; +import * as ForgejoChangeRequestTemplate from "./forgejoChangeRequestTemplate.ts"; const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError); @@ -303,7 +304,7 @@ interface UnfilteredPulls { export const make = Effect.gen(function* () { const cli = yield* ForgejoCli.ForgejoCli; const fs = yield* FileSystem.FileSystem; - const { process } = yield* SourceControlHost.SourceControlHost; + const { git, process } = yield* SourceControlHost.SourceControlHost; const request = >( input: ForgejoCli.ForgejoApiInput, schema: S, @@ -488,6 +489,11 @@ export const make = Effect.gen(function* () { }, (effect, input) => effect.pipe(mapError("listChangeRequests", input.cwd)), ), + readChangeRequestTemplate: Effect.fn("ForgejoSourceControlProvider.readChangeRequestTemplate")( + function ({ cwd, treeish }) { + return ForgejoChangeRequestTemplate.detect(cwd, treeish, git.execute); + }, + ), getChangeRequest: Effect.fn("ForgejoSourceControlProvider.getChangeRequest")(function (input) { return getPull(input).pipe( Effect.map(toForgejoChangeRequest), diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts new file mode 100644 index 0000000000000..87f27e315406c --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.test.ts @@ -0,0 +1,100 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; +import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; + +import * as ForgejoCli from "./ForgejoCli.ts"; +import * as ForgejoSourceControlProvider from "./ForgejoSourceControlProvider.ts"; + +const templateRepository = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { git } = yield* SourceControlHost.SourceControlHost; + const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-forgejo-pr-template-" }); + const runGit = (args: ReadonlyArray) => + git.execute({ operation: "forgejoChangeRequestTemplate.test.git", cwd, args }); + yield* runGit(["init", "--initial-branch=main", "--template="]); + yield* runGit(["config", "user.email", "test@example.com"]); + yield* runGit(["config", "user.name", "Test User"]); + const provider = yield* ForgejoSourceControlProvider.make; + + return { + runGit, + writeTemplate: (relativePath: string, body: string) => + Effect.gen(function* () { + const file = path.join(cwd, relativePath); + yield* fs.makeDirectory(path.dirname(file), { recursive: true }); + yield* fs.writeFileString(file, body); + }), + commit: Effect.gen(function* () { + yield* runGit(["add", "-A"]); + yield* runGit(["commit", "--allow-empty", "-m", "Set pull request template"]); + }), + read: (treeish: string) => + provider.readChangeRequestTemplate?.({ cwd, treeish }) ?? Effect.succeedNone, + }; +}); + +const testLayer = Layer.mergeAll( + TestSourceControlHost.layerWithRealGit(), + Layer.mock(ForgejoCli.ForgejoCli)({}), + NodeServices.layer, +); + +it.live("reads the Gitea template committed to the target branch", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.commit; + yield* repo.runGit(["branch", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Expected on the PR"); + yield* repo.commit; + yield* repo.runGit(["checkout", "feature"]); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Working tree only"); + + assert.deepStrictEqual(yield* repo.read("main"), Option.some("## Expected on the PR")); + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.none()); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("uses the first non-empty Markdown template in Forgejo's lookup order", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + yield* repo.writeTemplate("pull_request_template.md", " \n"); + yield* repo.writeTemplate(".forgejo/PULL_REQUEST_TEMPLATE.md", "## Forgejo"); + yield* repo.writeTemplate(".gitea/pull_request_template.md", "## Gitea"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Forgejo")); + + yield* repo.writeTemplate("pull_request_template.md", "## Root"); + yield* repo.commit; + assert.deepStrictEqual(yield* repo.read("HEAD"), Option.some("## Root")); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); + +it.live("rejects a committed template symlink and caps the fallback blob", () => + Effect.gen(function* () { + const repo = yield* templateRepository; + const fallback = "x".repeat(9_000); + yield* repo.writeTemplate(".github/pull_request_template.md", fallback); + yield* repo.writeTemplate("link-target", "README.md"); + yield* repo.commit; + const linkBlob = yield* repo.runGit(["rev-parse", "HEAD:link-target"]); + yield* repo.runGit([ + "update-index", + "--add", + "--cacheinfo", + `120000,${linkBlob.stdout.trim()},pull_request_template.md`, + ]); + yield* repo.runGit(["commit", "-m", "Record a template symlink"]); + + assert.deepStrictEqual( + yield* repo.read("HEAD"), + Option.some(`${fallback.slice(0, 8_000)}\n\n[truncated]`), + ); + }).pipe(Effect.scoped, Effect.provide(testLayer)), +); diff --git a/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts new file mode 100644 index 0000000000000..0ffbc33956b7d --- /dev/null +++ b/packages/source-control-forgejo/src/server/forgejoChangeRequestTemplate.ts @@ -0,0 +1,63 @@ +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; + +import type * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; + +// Forgejo's Markdown lookup order also preserves Gitea's root, .gitea, .github order. +const TEMPLATE_PATHS = ["", ".forgejo/", ".gitea/", ".github/", "docs/"].flatMap((directory) => [ + `${directory}PULL_REQUEST_TEMPLATE.md`, + `${directory}pull_request_template.md`, +]); +const TEMPLATE_MAX_BYTES = 8_000; +const TREE_LIST_MAX_BYTES = 100_000; +const TRUNCATION_MARKER = "[truncated]"; + +type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"]; + +export const detect = Effect.fn("forgejoChangeRequestTemplate.detect")( + function* (cwd: string, treeish: string, executeGit: ExecuteGit) { + const listing = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.listTemplates", + cwd, + args: ["ls-tree", "-z", "--full-tree", treeish, "--", ...TEMPLATE_PATHS], + maxOutputBytes: TREE_LIST_MAX_BYTES, + appendTruncationMarker: true, + }); + if (listing.stdoutTruncated) { + return Option.none(); + } + + // Read only regular blobs from the target tree, including when the worktree has a symlink. + const objectsByPath = new Map(); + for (const record of listing.stdout.split("\0")) { + const entry = /^100(?:644|755) blob ([0-9a-f]{40,64})\t(.+)$/.exec(record); + if (entry?.[1] && entry[2]) { + objectsByPath.set(entry[2], entry[1]); + } + } + + for (const path of TEMPLATE_PATHS) { + const objectId = objectsByPath.get(path); + if (!objectId) { + continue; + } + const blob = yield* executeGit({ + operation: "forgejoChangeRequestTemplate.readTemplate", + cwd, + args: ["cat-file", "blob", objectId], + maxOutputBytes: TEMPLATE_MAX_BYTES, + appendTruncationMarker: true, + }); + const template = blob.stdout.trim(); + if (template.length > 0) { + return Option.some( + blob.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER) + ? `${template}\n\n${TRUNCATION_MARKER}` + : template, + ); + } + } + return Option.none(); + }, + Effect.orElseSucceed(() => Option.none()), +); diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts index c04145758f7b1..c944207d639ab 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts @@ -656,6 +656,15 @@ Redact secrets before uploading.`); ["referenced", "acme/web#50"], ["closed", null], ]); + // A cross-reference keeps what a surface needs to open its source, not only a label. + expect(issue.events.find((event) => event.kind === "referenced")).toMatchObject({ + reference: { + repository: "acme/web", + number: 50, + kind: "pull-request", + url: "https://github.com/acme/web/pull/50", + }, + }); }), ); }); diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index c3cc15097dfd5..9d155cab2b794 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -3949,13 +3949,25 @@ layer("GitHubPullRequestApi.layer", (it) => { name: "build", status: "COMPLETED", conclusion: "SUCCESS", - checkSuite: { workflowRun: { workflow: { name: "linux" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_linux", name: "linux" }, + }, + }, }), checkRun({ name: "build", status: "COMPLETED", conclusion: "FAILURE", - checkSuite: { workflowRun: { workflow: { name: "windows" } } }, + checkSuite: { + workflowRun: { + event: "push", + runNumber: 1, + workflow: { id: "W_windows", name: "windows" }, + }, + }, }), ], pageInfo: { hasNextPage: false, endCursor: null }, diff --git a/packages/source-control-github/src/server/gitHubIssueJson.ts b/packages/source-control-github/src/server/gitHubIssueJson.ts index e46ad7ec9e515..59e9b9efd118e 100644 --- a/packages/source-control-github/src/server/gitHubIssueJson.ts +++ b/packages/source-control-github/src/server/gitHubIssueJson.ts @@ -5,7 +5,6 @@ import type { IssueActor, IssueComment, IssueEvent, - IssueEventKind, IssueLabel, IssueLinkedPullRequest, IssueState, @@ -137,7 +136,7 @@ function toLinkedPullRequest( /** The change GitHub recorded, or null for a kind this page has no vocabulary for. */ function toEventFields( raw: TimelineItem, -): { readonly kind: IssueEventKind; readonly detail: string | null } | null { +): Pick | null { switch (raw.__typename) { case "ClosedEvent": return { kind: "closed", detail: null }; @@ -164,15 +163,28 @@ function toEventFields( case "RenamedTitleEvent": return { kind: "renamed", detail: trimmed(raw.currentTitle) }; case "CrossReferencedEvent": { - const repository = trimmed( - raw.source != null && "repository" in raw.source - ? raw.source.repository.nameWithOwner - : null, - ); - const number = raw.source != null && "number" in raw.source ? raw.source.number : 0; + const source = + raw.source.__typename === "PullRequest" || raw.source.__typename === "Issue" + ? raw.source + : null; + const repository = trimmed(source?.repository.nameWithOwner); + const url = trimmed(source?.url); + if (source === null || repository === null || source.number <= 0) { + return { kind: "referenced", detail: null }; + } return { kind: "referenced", - detail: repository === null || number <= 0 ? null : `${repository}#${number}`, + detail: `${repository}#${source.number}`, + ...(url === null + ? {} + : { + reference: { + repository, + number: source.number, + kind: source.__typename === "PullRequest" ? "pull-request" : "issue", + url, + }, + }), }; } default: diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index 09c3f511e1a3f..547344beee3f9 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -359,10 +359,18 @@ describe("pull request detail decoding", () => { checkSuite: { workflowRun: null }, ...fields, }; - const inWorkflow = ({ workflowName, ...fields }: Record) => + const inWorkflow = ({ + workflowName, + workflowId = `W_kwDORLtfbc4${String(workflowName)}`, + event = "pull_request", + runNumber = 95380, + ...fields + }: Record) => check({ ...fields, - checkSuite: { workflowRun: { workflow: { name: workflowName } } }, + checkSuite: { + workflowRun: { event, runNumber, workflow: { id: workflowId, name: workflowName } }, + }, }); const coreJson = ( @@ -683,6 +691,139 @@ describe("pull request detail decoding", () => { expect(checksOf([stuck, rerun])).toEqual([[["Changes", "pending"]], "pending"]); }); + it("drops a cancelled check whose workflow run was superseded by a newer run on the head", () => { + const superseded = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + status: "COMPLETED", + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:00:05Z", + }; + const replacement = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95380, + status: "COMPLETED", + conclusion: "SUCCESS", + startedAt: "2026-10-30T10:00:10Z", + completedAt: "2026-10-30T10:05:00Z", + }; + const rollup = [ + inWorkflow({ ...superseded, name: "check", conclusion: "CANCELLED" }), + inWorkflow({ + ...superseded, + name: "web browser tests (runner ${{ matrix.slice }} of 6)", + conclusion: "CANCELLED", + }), + inWorkflow({ ...replacement, name: "check" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 1 of 6)" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 2 of 6)" }), + ]; + const detail = detailOf(rollup); + + expect([detail.checks.map((check) => [check.name, check.status]), detail.checksState]).toEqual([ + [ + ["check", "success"], + ["web browser tests (runner 1 of 6)", "success"], + ["web browser tests (runner 2 of 6)", "success"], + ], + "passing", + ]); + }); + + it("keeps a cancelled check when the newer run is another workflow with the same name", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + conclusion: "CANCELLED", + }), + inWorkflow({ + name: "lint", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4ToKTh", + runNumber: 95380, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test", + "cancelled", + ]); + expect(detail.checksState).toBe("failing"); + }); + + it("drops a required cancelled check once a newer run reports it, whenever it finished", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 41, + conclusion: "CANCELLED", + isRequired: true, + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:09:00Z", + }), + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 42, + conclusion: "SUCCESS", + isRequired: true, + startedAt: "2026-10-30T10:01:00Z", + completedAt: "2026-10-30T10:05:00Z", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toEqual([["test", "success"]]); + expect(detail.checksState).toBe("passing"); + }); + + it.each([ + ["a push", "push", "push", "CANCELLED", false, "cancelled"], + ["another event", "pull_request", "pull_request_target", "CANCELLED", false, "cancelled"], + ["a pull request run", "pull_request", "pull_request", "FAILURE", false, "failure"], + [ + "a pull request run, if required", + "pull_request", + "pull_request", + "CANCELLED", + true, + "cancelled", + ], + ])( + "keeps an older run's check when the newer run is %s", + (_label, olderEvent, newerEvent, conclusion, isRequired, status) => { + const detail = detailOf([ + inWorkflow({ + name: "test (packages/shared)", + workflowName: "CI", + event: olderEvent, + runNumber: 41, + conclusion, + isRequired, + }), + inWorkflow({ + name: "test (apps/server)", + workflowName: "CI", + event: newerEvent, + runNumber: 42, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test (packages/shared)", + status, + ]); + expect(detail.checksState).toBe("failing"); + }, + ); + it("merges reviews with comments in time order and keeps a bodyless approval", () => { const detail = expectSuccess(activity(JSON.parse(detailJson) as Record)); expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 705c1a326f82e..216ad1ae7732f 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -131,6 +131,13 @@ interface LatestReviewFields { readonly isMinimized?: boolean | undefined; } +/** Run numbers count up per workflow file, whatever its name; database ids exceed int32. */ +interface WorkflowRunFields { + readonly event: string; + readonly runNumber: number; + readonly workflow: { readonly id: string }; +} + /** Check runs use status/conclusion; commit statuses use a single state. */ interface CheckFields { readonly name?: string | null | undefined; @@ -143,6 +150,8 @@ interface CheckFields { readonly targetUrl?: string | null | undefined; /** Empty for app-owned runs; absent for commit statuses. */ readonly workflowName?: string | null | undefined; + /** Absent for commit statuses and app-owned runs. */ + readonly workflowRun?: WorkflowRunFields | null | undefined; readonly startedAt?: string | null | undefined; readonly completedAt?: string | null | undefined; /** Branch protection requires this check; asked for on github.com only. */ @@ -619,16 +628,42 @@ function isNamelessCheck(raw: CheckFields): boolean { return trimmed(raw.name) === null && trimmed(raw.context) === null; } -/** Unfinished runs outrank finished runs of the same check across push/PR workflows. */ +const PULL_REQUEST_EVENTS = new Set(["pull_request", "pull_request_target"]); + +/** + * Unfinished runs outrank finished runs of the same check across push/PR workflows. A newer pull + * request run of a workflow supersedes the older one's cancelled checks, whose names can differ + * (an unexpanded matrix). Other events can run one commit in different scopes (a branch and a + * tag, dispatch inputs), so their runs replace nothing. + */ function toCheckEntries(raw: ReadonlyArray | null | undefined): ReadonlyArray<{ readonly check: PullRequestCheck; readonly workflowName: string | null; readonly at: string | null; }> { + const lineageOf = (run: WorkflowRunFields) => `${run.workflow.id} ${run.event}`; + const newestRunNumber = new Map(); + const note = (key: string, runNumber: number) => { + if (runNumber > (newestRunNumber.get(key) ?? Number.NEGATIVE_INFINITY)) { + newestRunNumber.set(key, runNumber); + } + }; + for (const check of raw ?? []) { + const run = check.workflowRun; + if (run == null || !PULL_REQUEST_EVENTS.has(run.event)) continue; + note(lineageOf(run), run.runNumber); + note(`${lineageOf(run)} ${trimmed(check.name) ?? ""}`, run.runNumber); + } return (raw ?? []).flatMap((check) => { const name = trimmed(check.name) ?? trimmed(check.context); if (name === null) return []; const status = toCheckStatus(check); + const run = check.workflowRun; + if (status === "cancelled" && run != null) { + // Branch protection names required checks, so only a newer same-name check replaces one. + const replacedBy = check.isRequired === true ? `${lineageOf(run)} ${name}` : lineageOf(run); + if (run.runNumber < (newestRunNumber.get(replacedBy) ?? run.runNumber)) return []; + } return [ { check: { @@ -1248,7 +1283,11 @@ export type GitHubCheckContext = CheckFields; function toCheckContexts(nodes: ReadonlyArray): ReadonlyArray { return nodes.map((check) => check.__typename === "CheckRun" - ? { ...check, workflowName: check.checkSuite.workflowRun?.workflow.name ?? null } + ? { + ...check, + workflowName: check.checkSuite.workflowRun?.workflow.name ?? null, + workflowRun: check.checkSuite.workflowRun, + } : check, ); } diff --git a/packages/source-control-github/src/server/issues.graphql b/packages/source-control-github/src/server/issues.graphql index 18c8cee3536a2..d8b28a08c7078 100644 --- a/packages/source-control-github/src/server/issues.graphql +++ b/packages/source-control-github/src/server/issues.graphql @@ -231,6 +231,7 @@ query IssueDetail($owner: String!, $name: String!, $number: Int!) { } ... on Issue { number + url repository { nameWithOwner } diff --git a/packages/source-control-github/src/server/issues.graphql.ts b/packages/source-control-github/src/server/issues.graphql.ts index 9d059396d26a0..fb393ef5ca4c6 100644 --- a/packages/source-control-github/src/server/issues.graphql.ts +++ b/packages/source-control-github/src/server/issues.graphql.ts @@ -487,6 +487,8 @@ export const SourceIssue = Schema.Struct({ __typename: Schema.Literal("Issue"), /** Identifies the issue number. */ number: Shared.Int, + /** The HTTP URL for this issue */ + url: Shared.URI, /** The repository associated with this node. */ repository: NodesRepositoryRepository }) @@ -584,7 +586,7 @@ export const IssueDetail = GraphQL.query("IssueDetail", { ], selections: [ { name: "viewer", body: ["{login}"] }, - { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number repository{nameWithOwner}}}}}}}}"] } + { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){viewerPermission issue(number:$", "number", "){...IssueRow assignees(first:100){pageInfo{hasNextPage endCursor}nodes{login name avatarUrl}}labels(first:100){pageInfo{hasNextPage endCursor}nodes{name color}}body viewerCanUpdate viewerCanClose viewerCanReopen...Reactions comments(last:100){totalCount pageInfo{hasPreviousPage startCursor}nodes{id author{__typename login avatarUrl}body createdAt url...Reactions}}closedByPullRequestsReferences(first:20 includeClosedPrs:true){pageInfo{hasNextPage endCursor}nodes{number title url state isDraft repository{nameWithOwner}}}timelineItems(last:100 itemTypes:[CLOSED_EVENT REOPENED_EVENT LABELED_EVENT UNLABELED_EVENT ASSIGNED_EVENT UNASSIGNED_EVENT RENAMED_TITLE_EVENT CROSS_REFERENCED_EVENT]){nodes{__typename...on ClosedEvent{id createdAt actor{__typename login avatarUrl}}...on ReopenedEvent{id createdAt actor{__typename login avatarUrl}}...on LabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on UnlabeledEvent{id createdAt actor{__typename login avatarUrl}label{name}}...on AssignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on UnassignedEvent{id createdAt actor{__typename login avatarUrl}assignee{__typename...on User{login name}...on Bot{login}}}...on RenamedTitleEvent{id createdAt actor{__typename login avatarUrl}currentTitle}...on CrossReferencedEvent{id createdAt actor{__typename login avatarUrl}source{__typename...on PullRequest{number title url state isDraft repository{nameWithOwner}}...on Issue{number url repository{nameWithOwner}}}}}}}}"] } ], fragments: [ { name: "IssueRow", body: ["on Issue{number title url state stateReason createdAt updatedAt closedAt author{__typename login avatarUrl...on User{name}}}"] }, diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql b/packages/source-control-github/src/server/pullRequestReads.graphql index 2799b67525a27..0b8c5350c1408 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql +++ b/packages/source-control-github/src/server/pullRequestReads.graphql @@ -42,7 +42,10 @@ fragment CheckContext on StatusCheckRollupContext { isRequired(pullRequestNumber: $number) @include(if: $required) checkSuite { workflowRun { + event + runNumber workflow { + id name } } diff --git a/packages/source-control-github/src/server/pullRequestReads.graphql.ts b/packages/source-control-github/src/server/pullRequestReads.graphql.ts index ab5e211a4dec2..d26912d6aee7b 100644 --- a/packages/source-control-github/src/server/pullRequestReads.graphql.ts +++ b/packages/source-control-github/src/server/pullRequestReads.graphql.ts @@ -23,6 +23,8 @@ export interface StatusContext extends Schema.Struct.Type {} /** A workflow run. */ export const WorkflowRun = Schema.Struct({ + /** The event that triggered the workflow run */ + event: Schema.String, + /** A number that uniquely identifies this workflow run in its parent workflow. */ + runNumber: Shared.Int, /** The workflow executed in this workflow run. */ workflow: Workflow }) @@ -565,7 +571,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", { { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt mergeCommit{oid}mergedBy{__typename login avatarUrl...on User{name}}closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}mergeQueueRemovals:timelineItems(last:1 itemTypes:[REMOVED_FROM_MERGE_QUEUE_EVENT])@include(if:$", "mergeQueue", "){nodes{__typename...on RemovedFromMergeQueueEvent{id createdAt reason}}}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { @@ -617,7 +623,7 @@ export const PullRequestCheckContexts = GraphQL.query("PullRequestCheckContexts" { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){headRefOid commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100 after:$", "after", "){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{event runNumber workflow{id name}}}}}"] } ] }, variables: { diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index b528c1ced5a8a..04a633bba7096 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -21,6 +21,8 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo import { decodeGitLabMergeRequestJson, decodeGitLabMergeRequestListJson, + type NormalizedGitLabMergeRequestRecord, + withSourceProjectPath, } from "./gitLabMergeRequests.ts"; import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; @@ -377,6 +379,10 @@ const decodeGitLabMergeRequestProject = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })), ); +const decodeGitLabProjectPath = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ path_with_namespace: TrimmedNonEmptyString })), +); + const RawGitLabNamespaceSchema = Schema.Struct({ id: Schema.Number, }); @@ -559,6 +565,35 @@ export const make = Effect.gen(function* () { ), ); + // glab's MR JSON names a fork's source project only by `source_project_id`. + const resolveSourceProjectPaths = Effect.fn("GitLabCli.resolveSourceProjectPaths")(function* ( + cwd: string, + records: ReadonlyArray, + paths: Map, + ) { + const ids = new Set(); + for (const record of records) { + const id = record.unresolvedSourceProjectId; + if (id !== undefined && !paths.has(id)) ids.add(id); + } + yield* Effect.forEach( + ids, + (id) => + execute({ cwd, args: ["api", `projects/${id}`] }).pipe( + Effect.flatMap((result) => decodeGitLabProjectPath(result.stdout.trim())), + Effect.map((project) => project.path_with_namespace), + Effect.orElseSucceed(() => null), + Effect.map((path) => void paths.set(id, path)), + ), + { concurrency: 8, discard: true }, + ); + return records.map((record) => + record.unresolvedSourceProjectId === undefined + ? record + : withSourceProjectPath(record, paths.get(record.unresolvedSourceProjectId) ?? null), + ); + }); + return GitLabCli.of({ execute, listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) { @@ -566,6 +601,7 @@ export const make = Effect.gen(function* () { let pageSize = limit; let page = 1; const items: GitLabMergeRequestSummary[] = []; + const sourceProjectPaths = input.source?.owner ? new Map() : null; while (items.length < limit) { const result = yield* execute({ cwd: input.cwd, @@ -600,7 +636,11 @@ export const make = Effect.gen(function* () { cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated", }); } - items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt)); + // Only a fork head can match a fork's merge request, so other lookups skip the API calls. + const records = sourceProjectPaths + ? yield* resolveSourceProjectPaths(input.cwd, decoded.success, sourceProjectPaths) + : decoded.success; + items.push(...records.map(toSummaryWithOptionalUpdatedAt)); // Count raw entries: the decoder drops invalid ones, which would end paging early. const entries = decodeJsonArray(raw); if ( @@ -635,7 +675,9 @@ export const make = Effect.gen(function* () { ); } - return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success)); + return resolveSourceProjectPaths(input.cwd, [decoded.success], new Map()).pipe( + Effect.map(([record]) => toSummaryWithOptionalUpdatedAt(record!)), + ); }), ), ), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts index 7c794de8b456e..d3bd6e01366bd 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts @@ -59,6 +59,13 @@ function answer(path: string): string { created_at: "2026-07-03T00:00:00Z", system: true, }, + { + id: 10, + body: "mentioned in merge request api!51", + author: { username: "theo" }, + created_at: "2026-07-04T00:00:00Z", + system: true, + }, ]); } if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) { @@ -206,7 +213,14 @@ describe("GitLabIssueTracker", () => { expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([ ["labeled", "bug"], ["closed", null], + ["referenced", "merge request api!51"], ]); + expect(issue.events.at(-1)?.reference).toEqual({ + repository: "acme/api", + number: 51, + kind: "pull-request", + url: "https://gitlab.com/acme/api/-/merge_requests/51", + }); // A closing merge request is not repeated as a related one. expect( issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts index f8b1f80c18b0e..4f4aeb3135034 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts @@ -25,6 +25,7 @@ import { decodeIssueDetailListJson, decodeIssueListJson, decodeIssueNotesJson, + withMentionReference, decodeLabelEventsJson, decodeLinkedMergeRequestsJson, decodeProjectLabelsJson, @@ -576,9 +577,12 @@ export const make: Effect.Effect = reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [], })), commentsCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null), - events: [...systemEvents, ...labelEvents].sort((left, right) => - left.createdAt.localeCompare(right.createdAt), - ), + events: [ + ...systemEvents.map((event) => + withMentionReference(event, issue.url, input.scope), + ), + ...labelEvents, + ].sort((left, right) => left.createdAt.localeCompare(right.createdAt)), // A merge request that closes the issue outranks its sighting as a mere mention. linkedPullRequests: [ ...closing, diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts index 7038e6a82d630..abd2f7b82f218 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts @@ -106,6 +106,97 @@ it.effect("lists a nested-group fork's merge requests by source branch and names }), ); +// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its +// source project only by `source_project_id`, never by a `source_project` path. +it.effect("names a fork merge request's source project from real glab list output", () => + Effect.gen(function* () { + const branch = "feature/fork-work"; + const mergeRequest = (iid: number, sourceProjectId: number) => ({ + id: 9000 + iid, + iid, + project_id: 100, + title: `Work ${iid}`, + state: "opened", + target_branch: "main", + source_branch: branch, + source_project_id: sourceProjectId, + target_project_id: 100, + draft: false, + sha: "0123456789abcdef0123456789abcdef01234567", + updated_at: "2026-04-07T15:00:00.000Z", + references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` }, + web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`, + }); + const output = JSON.stringify([ + mergeRequest(1, 101), + mergeRequest(2, 101), + mergeRequest(3, 100), + mergeRequest(4, 102), + ]); + const apiCalls: ReadonlyArray[] = []; + const provider = yield* GitLabSourceControlProvider.make.pipe( + Effect.provide( + GitLabCli.layer.pipe( + Layer.provideMerge( + TestSourceControlHost.layer({ + process: { + run: (input) => + Effect.sync(() => { + if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output); + apiCalls.push(input.args); + return TestSourceControlHost.processOutput( + input.args[1] === "projects/101" + ? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" }) + : "not json", + ); + }), + }, + }), + ), + Layer.provide(FileSystem.layerNoop({})), + ), + ), + ); + + const upstreamHead = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: branch, + state: "open", + limit: 20, + }); + expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toEqual([]); + + const changeRequests = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: `alice:${branch}`, + state: "open", + limit: 20, + }); + // GitManager drops a cross-repository MR whose head project is unnamed. + expect(changeRequests).toMatchObject([ + { + number: 1, + isCrossRepository: true, + headRepositoryNameWithOwner: "alice/upstream", + headRepositoryOwnerLogin: "alice", + }, + { number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" }, + { number: 3, isCrossRepository: false }, + { number: 4, isCrossRepository: true }, + ]); + expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toHaveLength(2); + expect(apiCalls).toEqual( + expect.arrayContaining([ + ["api", "projects/101"], + ["api", "projects/102"], + ]), + ); + }), +); + const withRepository = ( test: (input: { readonly git: (...args: string[]) => Effect.Effect; diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index 8e5077044c6b3..c5a2d56037172 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -210,6 +210,13 @@ it.effect( headSelectors: ["octocat:feature", "feature"], state: "open", }), + { headSelectors: ["octocat:feature"], limit: 100 }, + ); + assert.deepStrictEqual( + provider.headBranchProbe?.({ + headSelectors: ["feature", "octocat:feature"], + state: "open", + }), { headSelectors: ["feature"], limit: 100 }, ); }), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts index a7d5b71ca47d3..2a2d4ac3e199c 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts @@ -211,11 +211,17 @@ export const make = Effect.gen(function* () { return SourceControlProvider.SourceControlProvider.of({ kind: SourceControlProviderKind.make("gitlab"), - // GitLab lists fork merge requests by source branch with no owner filter, so read a full page. - headBranchProbe: ({ headSelectors }) => ({ - headSelectors: headSelectors.filter((selector) => !selector.includes(":")), - limit: 100, - }), + // GitLab lists fork merge requests by source branch with no owner filter, so read a full page + // once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork + // head, which tells the list to name fork source projects. + headBranchProbe: ({ headSelectors }) => { + const byBranch = new Map(); + for (const selector of headSelectors) { + const branch = SourceControlProvider.sourceBranch({ headSelector: selector }); + if (!byBranch.has(branch)) byBranch.set(branch, selector); + } + return { headSelectors: [...byBranch.values()], limit: 100 }; + }, readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")( function ({ cwd, treeish }) { return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute); diff --git a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts index 5458ed4f859ef..7a52667a4a425 100644 --- a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts @@ -250,6 +250,41 @@ function toSystemEvent( return null; } +// The path class excludes the sigil, so matching is linear on any input. +const MENTION = /^(?:merge request ([\w.\-/]*)!|issue ([\w.\-/]*)#)([1-9]\d*)$/; + +/** + * Where a "mentioned in merge request !12" note came from, addressed from the issue's own web URL + * so a self-managed host under a subpath resolves. A commit, epic or snippet mention gets none. + */ +export function withMentionReference( + event: IssueEvent, + issueUrl: string, + scope: string, +): IssueEvent { + const match = event.kind === "referenced" ? MENTION.exec(event.detail ?? "") : null; + const projectUrl = issueUrl.split("/-/")[0]!; + if (match === null || !projectUrl.toLowerCase().endsWith(`/${scope.toLowerCase()}`)) { + return event; + } + const [, mergeRequestPath, issuePath, digits] = match; + const isMergeRequest = mergeRequestPath !== undefined; + const path = mergeRequestPath ?? issuePath ?? ""; + // A project in the same namespace is named by its path alone. + const repository = + path === "" ? scope : path.includes("/") ? path : `${scope.replace(/[^/]*$/, "")}${path}`; + const base = projectUrl.slice(0, projectUrl.length - scope.length); + return { + ...event, + reference: { + repository, + number: Number(digits), + kind: isMergeRequest ? "pull-request" : "issue", + url: `${base}${repository}/-/${isMergeRequest ? "merge_requests" : "issues"}/${digits}`, + }, + }; +} + interface GitLabIssueNotes { readonly comments: ReadonlyArray; readonly events: ReadonlyArray; diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts index ef4438f5ff3ee..a40abd786cf85 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts @@ -23,6 +23,8 @@ export interface NormalizedGitLabMergeRequestRecord { readonly isCrossRepository?: boolean; readonly headRepositoryNameWithOwner?: string | null; readonly headRepositoryOwnerLogin?: string | null; + /** Set when a cross-repository MR names its source project only by id. */ + readonly unresolvedSourceProjectId?: number; } const GitLabProjectReferenceSchema = Schema.Struct({ @@ -122,6 +124,24 @@ function normalizeGitLabMergeRequestRecord( ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}), ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + ...(isCrossRepository === true && + !sourceProjectPath && + typeof raw.source_project_id === "number" + ? { unresolvedSourceProjectId: raw.source_project_id } + : {}), + }; +} + +export function withSourceProjectPath( + record: NormalizedGitLabMergeRequestRecord, + sourceProjectPath: string | null, +): NormalizedGitLabMergeRequestRecord { + const { unresolvedSourceProjectId: _, ...resolved } = record; + const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath); + return { + ...resolved, + ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), }; } diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts new file mode 100644 index 0000000000000..838309b037617 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts @@ -0,0 +1,138 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts"; + +const HOST = "source.tanstack.com"; + +/** + * Shaped like `GET /pulls/{n}` of a private pull request: its head is `owner:branch` in the + * companion repository, and Source has stored no file or line counts for it. + */ +const PRIVATE_PULL = { + number: 42, + title: "Fix the thing", + state: "open", + visibility: "private", + draft: false, + author: "bob", + head: "acme:fix/thing", + createdAt: 1_000, + body: null, + base: "main", + headRepo: "acme/web.private", + headSha: "c".repeat(40), + baseSha: "b".repeat(40), + mergeCommitSha: null, + mergedAt: null, + mergedBy: null, + mergeable: null, + changedFiles: null, + changedLines: null, +}; + +const FILES = { + baseSha: "b".repeat(40), + headSha: "c".repeat(40), + mergeBaseSha: "b".repeat(40), + available: true, + truncated: false, + files: [ + { path: "a.ts", status: "modified", additions: 3, deletions: 1 }, + { path: "b.ts", status: "added", additions: 4, deletions: 0 }, + ], +}; + +const RESPONSES: Record = { + "/repos/acme/web/pulls/42": PRIVATE_PULL, + "/repos/acme/web/pulls/42/files": FILES, + "/repos/acme/web/pulls/42/checks": { checks: [], upToDate: null, mayMerge: true }, + "/repos/acme/web/pulls/42/stack": { members: [] }, + [`/repos/acme/web/check-runs?sha=${"c".repeat(40)}`]: [], + "/repos/acme/web/ci/runs?pull=42&limit=30": { items: [], next: null }, + "/repos/acme/web/issues/42": { + timeline: [ + { id: 1, comment: "Looks good", author: "alice", at: 2_000 }, + { event: "head_updated", actor: "bob", at: 3_000 }, + ], + next: null, + }, + "/repos/acme/web/pulls/42/comments": [], + "/repos/acme/web/pulls/42/commits": { + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: true, + commits: [], + }, + "/user": { username: "alice" }, +}; + +const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => + input.path in RESPONSES + ? Effect.succeed(JSON.stringify(RESPONSES[input.path])) + : Effect.die(`unexpected ${input.path}`), + response: () => Effect.die("unexpected response read"), +}); + +const provider = TanStackSourcePullRequestProvider.make.pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provideService( + Credentials.TanStackSourceCredentials, + Credentials.TanStackSourceCredentials.of({ + get: () => Effect.die("unexpected credential read"), + invalidate: () => Effect.void, + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected http request")), + ), +); + +describe("TanStackSourcePullRequestProvider.getChangeRequest", () => { + // A client without this host's definition percent-encodes the owner's `@`; stored links + // keep the web's own spelling. + it.effect.each(["acme/web", "@acme/web", "%40acme/web"])( + "reads a private pull request of %s", + (repository) => + Effect.gen(function* () { + const detail = yield* (yield* provider).getChangeRequest({ + host: HOST, + repository, + number: 42, + cwd: "/repo", + }); + assert.strictEqual(detail.url, `https://${HOST}/@acme/web/pull/42`); + assert.strictEqual(detail.visibility, "private"); + assert.strictEqual(detail.headBranch, "fix/thing"); + assert.strictEqual(detail.headRepositoryNameWithOwner, "acme/web.private"); + // Source stores no counts for it, so they come from its files. + assert.deepStrictEqual( + [detail.changedFiles, detail.additions, detail.deletions], + [2, 7, 1], + ); + }), + ); +}); + +describe("TanStackSourcePullRequestProvider.getChangeRequestActivity", () => { + it.effect("reads the comments of a timeline that also holds events", () => + Effect.gen(function* () { + const activity = yield* (yield* provider).getChangeRequestActivity({ + host: HOST, + repository: "acme/web", + number: 42, + cwd: "/repo", + }); + assert.deepStrictEqual( + activity.comments.map((comment) => comment.body), + ["Looks good"], + ); + }), + ); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts index 509e03e1f41f4..0529ce6df17c7 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -35,6 +35,8 @@ const PULL = { function checkout(options: { readonly recordedOwner: string | null; readonly isAncestor: boolean; + readonly pull?: Partial; + readonly force?: boolean; }) { const git: Array = []; const config = new Map( @@ -43,14 +45,28 @@ function checkout(options: { const api = TanStackSourceApi.TanStackSourceApi.of({ request: (input) => input.path === "/repos/acme/web/pulls/42" - ? Effect.succeed(JSON.stringify(PULL)) + ? Effect.succeed(JSON.stringify({ ...PULL, ...options.pull })) : Effect.die(`unexpected ${input.path}`), response: () => Effect.die("unexpected response read"), }); const host = TestSourceControlHost.layer({ git: { resolvePrimaryRemoteName: () => Effect.succeed("origin"), - ensureRemote: () => Effect.succeed("origin"), + ensureRemote: (input) => + Effect.sync(() => { + git.push(`remote ${input.preferredName} ${input.url}`); + return input.url === REMOTE ? "origin" : input.preferredName; + }), + fetchRemoteBranch: (input) => + Effect.sync( + () => + void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`), + ), + fetchRemoteTrackingBranch: () => Effect.void, + setBranchUpstream: (input) => + Effect.sync( + () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`), + ), readConfigValue: (_cwd, key) => Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)), writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)), @@ -86,7 +102,13 @@ function checkout(options: { }, }); const run = TanStackSourceSourceControlProvider.make.pipe( - Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })), + Effect.flatMap((provider) => + provider.checkoutChangeRequest({ + cwd: "/repo", + reference: "42", + ...(options.force === undefined ? {} : { force: options.force }), + }), + ), Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))), ); @@ -129,4 +151,83 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { assert.isFalse(git.some((command) => command.startsWith("checkout"))); }); }); + + // Source publishes no `refs/pull//head` for a private pull request, on either repository. + it.effect("takes a private pull request's branch from the companion repository", () => { + const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" }; + const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull }); + const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true }); + return Effect.gen(function* () { + yield* forced.run; + assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --"); + yield* run; + assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme"); + assert.deepStrictEqual(git, [ + `remote source ${REMOTE}`, + "remote acme https://source.tanstack.com/@acme/web.private.git", + "fetch acme fix-thing:fix-thing", + "upstream fix-thing acme/fix-thing", + "switch fix-thing", + ]); + }); + }); +}); + +describe("TanStackSourceSourceControlProvider private pull requests", () => { + it.effect("asks Source for the companion and opens the pull request as private", () => { + const requests: Array<{ method: string; path: string; body: unknown }> = []; + const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => { + requests.push({ method: input.method ?? "GET", path: input.path, body: input.body }); + return Effect.succeed( + JSON.stringify({ + owner: "acme", + name: "web.private", + defaultBranch: null, + cloneUrl: "https://source.tanstack.com/@acme/web.private.git", + }), + ); + }, + response: () => Effect.die("unexpected response read"), + }); + const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") }); + return Effect.gen(function* () { + const provider = yield* TanStackSourceSourceControlProvider.make; + const companion = provider.privateChangeRequestRemote; + assert.isDefined(companion); + assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), { + url: "https://source.tanstack.com/@acme/web.private.git", + repository: "acme/web.private", + }); + yield* provider.createChangeRequest({ + cwd: "/repo", + baseRefName: "main", + headSelector: "sec/fix", + title: "Fix", + bodyFile: "/tmp/body.md", + private: true, + }); + assert.deepStrictEqual(requests, [ + { method: "POST", path: "/repos/acme/web/private-remote", body: undefined }, + { + method: "POST", + path: "/repos/acme/web/pulls", + body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true }, + }, + ]); + }).pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provide( + Layer.merge( + TestSourceControlHost.layer({ + git: { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + readConfigValue: () => Effect.succeed(REMOTE), + }, + }), + files, + ), + ), + ); + }); }); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index a1abb376b472d..f194848611361 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -395,6 +395,18 @@ export const make = Effect.gen(function* () { }, ), createsDraftChangeRequests: true, + privateChangeRequestRemote: Effect.fn( + "TanStackSourceSourceControlProvider.privateChangeRequestRemote", + )(function* (input) { + const target = yield* resolveTarget("privateChangeRequestRemote", input); + const companion = yield* read( + "privateChangeRequestRemote", + input.cwd, + { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` }, + Repository, + ); + return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` }; + }), createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")( function* (input) { const target = yield* resolveTarget("createChangeRequest", { @@ -437,6 +449,7 @@ export const make = Effect.gen(function* () { base: input.target?.refName ?? input.baseRefName, ...(body.trim().length === 0 ? {} : { body }), ...(input.draft === true ? { draft: true } : {}), + ...(input.private === true ? { private: true } : {}), }, }) .pipe( @@ -494,7 +507,8 @@ export const make = Effect.gen(function* () { return repository.defaultBranch; }, ), - // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too. + // A pull request's head is published as `refs/pull//head`, forks and GitHub sync too. A + // private one has no such ref: its branch is read from the companion repository. checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")( function* (input) { const pull = yield* getPull(input); @@ -519,9 +533,26 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); - if (!pull.isCrossRepository) { + const companion = + pullRepository !== null && + pull.headRepositoryNameWithOwner?.toLowerCase() === + `${pullRepository}.private`.toLowerCase() + ? pull.headRepositoryNameWithOwner + : null; + if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; - const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch }; + const remoteBranch = { + cwd: input.cwd, + remoteName: + companion === null + ? remoteName + : yield* git.ensureRemote({ + cwd: input.cwd, + preferredName: companion.split("/")[0] ?? "private", + url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`, + }), + remoteBranch: localBranch, + }; if (input.force !== true && !branches.includes(localBranch)) yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); else yield* git.fetchRemoteTrackingBranch(remoteBranch); @@ -535,11 +566,18 @@ export const make = Effect.gen(function* () { "--no-track", "-B", localBranch, - `refs/remotes/${remoteName}/${localBranch}`, + `refs/remotes/${remoteBranch.remoteName}/${localBranch}`, "--", ], }); yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); + // Whatever push defaults say, this branch must not be published to the public remote. + if (companion !== null) + yield* git.writeConfigValue({ + cwd: input.cwd, + key: `branch.${localBranch}.pushRemote`, + value: remoteBranch.remoteName, + }); yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); return; } diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts new file mode 100644 index 0000000000000..ac43a46ccdcad --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { tanStackSourceRepositoryPath } from "./tanStackSourceHosts.ts"; + +describe("tanStackSourceRepositoryPath", () => { + it.each([ + ["acme/web", "acme/web"], + ["@acme/web", "acme/web"], + // Clients without this host's definition percent-encode the owner's `@`. + ["%40acme/web", "acme/web"], + ["/@acme/web.git/", "acme/web"], + ["acme/web.private", "acme/web.private"], + ["acme", null], + ["acme/web/extra", null], + ["acme/..", null], + ])("reads %s as %s", (path, repository) => { + expect(tanStackSourceRepositoryPath(path)).toBe(repository); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts index 22923264629bf..dfa6d4e9031a0 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts @@ -1,4 +1,4 @@ -import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts"; +import { TANSTACK_SOURCE_HOST, withoutOwnerMark } from "../shared/definition.ts"; export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const; export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number]; @@ -10,14 +10,14 @@ export function tanStackSourceHost(host: string): TanStackSourceHost | null { const SEGMENT = /^[A-Za-z0-9_.-]+$/u; -/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */ +/** `owner/name` from the API spelling or either web spelling of the owner, `.git` dropped. */ export function tanStackSourceRepositoryPath(path: string): string | null { - const [owner, name, ...rest] = path - .trim() - .replace(/^\/+|\/+$/gu, "") - .replace(/\.git$/u, "") - .replace(/^@/u, "") - .split("/"); + const [owner, name, ...rest] = withoutOwnerMark( + path + .trim() + .replace(/^\/+|\/+$/gu, "") + .replace(/\.git$/u, ""), + ).split("/"); return rest.length === 0 && owner !== undefined && name !== undefined && diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts index 4d698fb881dfb..24c93e6aac83d 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts @@ -146,6 +146,7 @@ describe("toActivity", () => { ["4", "review-comment", null], ]); expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`); + expect(Json.pullUrl(HOST, "%40TanStack/ai", 9)).toBe(`https://${HOST}/@TanStack/ai/pull/9`); expect(activity.reviewThreads).toMatchObject([ { id: "4", path: "a.ts", line: 2, side: "left", isResolved: true }, ]); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts index acf3c4158f95c..51537627ca3e7 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts @@ -16,6 +16,8 @@ import type { import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; +import { withoutOwnerMark } from "../shared/definition.ts"; + /** Source sends times as epoch milliseconds. */ const EpochMillis = Schema.Finite; const Login = Schema.String; @@ -29,6 +31,7 @@ export const SourcePull = Schema.Struct({ labels: Schema.optional(Schema.Array(Schema.String)), head: Schema.String, createdAt: EpochMillis, + visibility: Schema.optional(Schema.String), }); export type SourcePull = typeof SourcePull.Type; @@ -135,7 +138,8 @@ const TimelineEntry = Schema.Struct({ type TimelineEntry = typeof TimelineEntry.Type; export const SourceTimeline = Schema.Struct({ - timeline: Schema.Array(TimelineEntry), + // Events such as `head_updated` sit between the comments and carry no id. + timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])), next: Schema.NullOr(Schema.String), }); @@ -239,10 +243,20 @@ export const SourceUser = Schema.Struct({ username: Schema.String }); export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis)); export const pullUrl = (host: string, repository: string, number: number) => - `https://${host}/@${repository}/pull/${number}`; + `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`; -/** A GitHub-synced pull request from a fork names its head only by its pull ref. */ -export const headBranchName = (head: string) => head.replace(/^refs\/heads\//u, ""); +/** + * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private + * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede. + */ +export const headBranchName = (head: string) => + head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, ""); + +/** Absent when Source names no visibility, so a reader tells unknown from public. */ +const visibilityOf = (pull: Pick) => + pull.visibility === "private" || pull.visibility === "public" + ? { visibility: pull.visibility } + : {}; export function toActor(login: string | null, host: string): PullRequestActor | null { if (login === null || login.trim() === "") return null; @@ -280,6 +294,7 @@ export function toChangeRequest( baseBranch: pull.base ?? "", state: pull.state, isDraft: pull.draft, + ...visibilityOf(pull), mergeability: "unknown", additions: 0, deletions: 0, @@ -380,7 +395,9 @@ export function toActivity(input: { }): ProviderChangeRequestActivity { const { host } = input; const page = pullUrl(host, input.repository, input.number); - const entries = input.timeline.timeline.filter(visible); + const entries = input.timeline.timeline.filter( + (entry): entry is TimelineEntry => "id" in entry && visible(entry), + ); const comments: Array = entries.map((entry: TimelineEntry) => ({ id: String(entry.id), kind: diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts index e3ce5c867fa5c..6e09a89fa2cda 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.test.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts @@ -31,7 +31,23 @@ describe("TanStack Source definition", () => { number: 7, }), ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); + // A stored link or an older client may name the repository as the web spells it. + for (const repository of ["@TanStack/router", "%40TanStack/router"]) + expect( + definition.changeRequestUrl({ host: "source.tanstack.com", repository, number: 7 }), + repository, + ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); expect(definition.checkoutCommandArgument("src pr checkout 7")).toBe("7"); expect(definition.checkoutCommandArgument("gh pr checkout 7")).toBeNull(); }); + + it.each(["tanstack/router", "@tanstack/router", "%40tanstack/router"])( + "keys %s as the API's owner/name", + (repository) => { + expect(definition.canonicalRepositoryKey?.(`source.tanstack.com/${repository}`)).toBe( + "source.tanstack.com/tanstack/router", + ); + expect(definition.canonicalRepositoryKey?.(`github.com/${repository}`)).toBeNull(); + }, + ); }); diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts index 1aee00c968dc6..032adc5a45cdd 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.ts @@ -37,6 +37,20 @@ function parseChangeRequestUrl(url: URL) { : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` }; } +/** + * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this + * definition percent-encodes that as `%40owner/name`. + */ +export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, ""); + +/** Links stored with the web's spelling compare equal to the project's own key. */ +function canonicalRepositoryKey(key: string): string | null { + const slash = key.indexOf("/"); + return slash > 0 && isTanStackSourceHost(key.slice(0, slash)) + ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}` + : null; +} + /** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */ function repositoryKeyFromRemote(key: string): string | null { // Remote parsing spells the `@` percent-encoded. @@ -80,13 +94,13 @@ export const definition = defineSourceControl({ ? null : webUrl ? changeRequestUrlBelow(webUrl, `pull/${number}`) - : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`, + : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`, parseChangeRequestUrl, commitUrl: (input) => buildCommitUrl( input.webUrl ? input - : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` }, + : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` }, "commit", ), parseIssueUrl: (url) => @@ -122,6 +136,7 @@ export const definition = defineSourceControl({ checkoutChangeRequestHost: () => null, changeRequestHeadRef: (number) => `refs/pull/${number}/head`, repositoryKeyFromRemote, + canonicalRepositoryKey, recognizeRemote: ({ hostname }) => isTanStackSourceHost(hostname) ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` } diff --git a/patches/@legendapp__list@3.7.3.patch b/patches/@legendapp__list@3.7.3.patch new file mode 100644 index 0000000000000..2afc400b04435 --- /dev/null +++ b/patches/@legendapp__list@3.7.3.patch @@ -0,0 +1,28 @@ +diff --git a/react-native.js b/react-native.js +index 440b0ad..fd5d18d 100644 +--- a/react-native.js ++++ b/react-native.js +@@ -1344,7 +1344,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { + return; + } + if (contentSize > 0 && queuedInitialLayout) { +- const isContentLess = contentSize < scrollLength; ++ // T3 patch: a top inset (e.g. a translucent header) shrinks the room content has to fit in. ++ const isContentLess = contentSize + getContentInsetTop(ctx) < scrollLength; + set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); + set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); + set$( +diff --git a/react-native.mjs b/react-native.mjs +index b95e1f8..e2b013a 100644 +--- a/react-native.mjs ++++ b/react-native.mjs +@@ -1323,7 +1323,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { + return; + } + if (contentSize > 0 && queuedInitialLayout) { +- const isContentLess = contentSize < scrollLength; ++ // T3 patch: a top inset (e.g. a translucent header) shrinks the room content has to fit in. ++ const isContentLess = contentSize + getContentInsetTop(ctx) < scrollLength; + set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); + set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); + set$( diff --git a/patches/effect@4.1.5.patch b/patches/effect@4.1.5.patch new file mode 100644 index 0000000000000..6d1bf0a6a9fa8 --- /dev/null +++ b/patches/effect@4.1.5.patch @@ -0,0 +1,2479 @@ +diff --git a/dist/ai/McpSchema.d.ts b/dist/ai/McpSchema.d.ts +index 8f86c27..aed42ae 100644 +--- a/dist/ai/McpSchema.d.ts ++++ b/dist/ai/McpSchema.d.ts +@@ -941,6 +941,52 @@ export declare const HEADER_MISMATCH_ERROR_CODE: -32020; + * @since 4.0.6 + */ + export declare const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE: -32022; ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const NOT_FOUND_ERROR_CODE: -32023; ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const FORBIDDEN_ERROR_CODE: -32024; ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const RESOURCE_EXHAUSTED_ERROR_CODE: -32025; ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const UNSUPPORTED_ERROR_CODE: -32026; ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export declare const CALLBACK_ENDPOINT_ERROR_CODE: -32027; + declare const ParseError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"NotFound">; ++ readonly code: Schema.tag<-32023>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class NotFound extends NotFound_base { ++} ++declare const Forbidden_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Forbidden">; ++ readonly code: Schema.tag<-32024>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Forbidden extends Forbidden_base { ++} ++declare const ResourceExhausted_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"ResourceExhausted">; ++ readonly code: Schema.tag<-32025>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class ResourceExhausted extends ResourceExhausted_base { ++} ++declare const Unsupported_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"Unsupported">; ++ readonly code: Schema.tag<-32026>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class Unsupported extends Unsupported_base { ++} ++declare const CallbackEndpointError_base: Schema.Class>, Schema.optionalKey, never, never>; ++ readonly _tag: Schema.tag<"CallbackEndpointError">; ++ readonly code: Schema.tag<-32027>; ++}>, import("../Cause.ts").YieldableError>; ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export declare class CallbackEndpointError extends CallbackEndpointError_base { ++} + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1880,6 +2001,66 @@ declare const Skill_base: Schema.Class; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type; ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventDescriptor: Schema.Struct<{ ++ readonly name: Schema.String; ++ readonly description: Schema.decodeTo>, Schema.optionalKey, never, never>; ++ readonly delivery: Schema.$Array>; ++ readonly inputSchema: Schema.$Record; ++ readonly payloadSchema: Schema.$Record; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type; ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const EventOccurrence: Schema.Struct<{ ++ readonly eventId: Schema.String; ++ readonly name: Schema.String; ++ readonly timestamp: Schema.String; ++ readonly data: Schema.$Record; ++ readonly cursor: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++ readonly _meta: Schema.decodeTo>>, Schema.optionalKey>, never, never>; ++}>; ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type; + declare const PromptArgument_base: Schema.Opaque Effect.Effect Layer.Layer; ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence
    { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. Webhook delivery is not supported, so ++ * `events/subscribe` answers `Unsupported`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const registerEvent: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Effect.Effect>; ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export declare const event: = Schema.Struct<{}>, Payload extends Schema.Codec = Schema.Codec, R = never>(options: EventOptions) => Layer.Layer>; + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/McpServer.js b/dist/ai/McpServer.js +index 4bf6bca..0973460 100644 +--- a/dist/ai/McpServer.js ++++ b/dist/ai/McpServer.js +@@ -413,6 +413,9 @@ const notFound = (method, target) => { + return new McpCore.SkillNotFound({ + uri: target + }); ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target); + } + }; + const isHidden = error => error instanceof Hidden; +@@ -2637,6 +2640,96 @@ export const registerSkill = /*#__PURE__*/Effect.fnUntraced(function* (options) + * @since 4.1.1 + */ + export const skill = options => Layer.effectDiscard(registerSkill(options)); ++// ============================================================================= ++// Events ++// ============================================================================= ++const DEFAULT_NEXT_POLL_MS = 30_000; ++/** ++* Registers an event type under the MCP Events extension (SEP-3415). ++* ++* **Details** ++* ++* The server declares `io.modelcontextprotocol/events` on revision ++* `2026-07-28` once any event type is registered, and answers `events/list`, ++* `events/poll` and `events/stream`. A push stream runs `stream` for its ++* lifetime inside the request's middleware, sends heartbeats carrying the ++* last cursor, and ends when the client goes away. Services read by `poll` ++* and `stream` are request-level, as for tools. ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const registerEvent = Effect.fnUntraced(function* (options) { ++ const { name, poll, stream } = options; ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)); ++ } ++ const registry = yield* McpServer; ++ const { core, globalMiddleware } = internalState.get(registry); ++ const services = yield* Effect.context(); ++ const annotations = options.annotations ?? Context.empty(); ++ const { invoke, visible } = makeInvoke(services, globalMiddleware); ++ const parameters = options.parameters ?? Schema.Struct({}); ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)); ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)); ++ const argumentsOf = (args) => decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))); ++ const encodeEvent = (event) => encodePayload(event.data).pipe(Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), Effect.map((data) => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` }))); ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [...(poll === undefined ? [] : ["poll"]), ...(stream === undefined ? [] : ["push"])], ++ inputSchema: toolJsonSchema(parameters, false), ++ payloadSchema: toolJsonSchema(options.payload, false), ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ poll: poll === undefined ? undefined : (request, invocation) => invoke(Effect.gen(function* () { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }); ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ }; ++ }), invocation, { method: "events/poll", target: name, payload: request }), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => invoke(Effect.scoped(Effect.gen(function* () { ++ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }); ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context(); ++ const items = subscription.items.pipe(Stream.mapEffect((item) => item._tag === "Event" ++ ? encodeEvent(item).pipe(Effect.map((event) => ({ ...event, _tag: "Event", cursor: item.cursor })), Effect.catch((error) => Effect.succeed({ _tag: "Error", error }))) ++ : Effect.succeed(item)), Stream.provideContext(context)); ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }); ++ })), invocation, { method: "events/stream", target: name, payload: request }) ++ }); ++}); ++/** ++* Creates a layer that registers an event type under the MCP Events ++* extension (SEP-3415). ++* ++* @see {@link registerEvent} for the Effect-level event registration API ++* ++* @stability unstable ++* @category events ++* @since 4.1.4 ++*/ ++export const event = (options) => Layer.effectDiscard(registerEvent(options)); + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/dist/ai/internal/mcpCore.js b/dist/ai/internal/mcpCore.js +index 4c416a8..50d2d34 100644 +--- a/dist/ai/internal/mcpCore.js ++++ b/dist/ai/internal/mcpCore.js +@@ -75,6 +75,15 @@ export const ClientNotification = /*#__PURE__*/Data.taggedEnum(); + * @internal + */ + export const ServerNotification = /*#__PURE__*/Data.taggedEnum(); ++/** ++ * @internal ++ */ ++export const eventNotFound = name => new McpSchema.NotFound({ ++ message: `Event '${name}' not found`, ++ data: { ++ kind: "event" ++ } ++}); + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a, b) => { + const rootA = a.slice(0, -"/SKILL.md".length); +@@ -90,6 +99,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + const resourceTemplateRegistrations = []; + const promptRegistrations = new Map(); + const skillRegistrations = new Map(); ++ const eventRegistrations = new Map(); + const skillFiles = new Set(); + const completionRegistrations = new Map(); + const filterList = (registrations, invocation) => Effect.map(Effect.filter(Arr.filter(registrations, entry => entry.isVisible(invocation.protocol)), entry => entry.visible === undefined ? Effect.succeed(true) : entry.visible(invocation)), entries => entries.map(entry => entry.descriptor)); +@@ -234,11 +244,22 @@ export const make = /*#__PURE__*/Effect.sync(() => { + return Array.from(children.values()).sort((a, b) => a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : 0); + }) + }; ++ const events = { ++ register: registration => Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration); ++ }), ++ list: invocation => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => Effect.suspend(() => { ++ const registration = eventRegistrations.get(name); ++ return registration !== undefined && registration.isVisible(invocation.protocol) ? Effect.succeed(registration) : Effect.fail(eventNotFound(name)); ++ }) ++ }; + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })); + return { + tools, +@@ -246,6 +267,7 @@ export const make = /*#__PURE__*/Effect.sync(() => { + prompts, + completions, + skills, ++ events, + registrationPresence + }; + }); +diff --git a/dist/ai/internal/mcpEvents.d.ts b/dist/ai/internal/mcpEvents.d.ts +new file mode 100644 +index 0000000..cb0ff5c +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.d.ts +@@ -0,0 +1 @@ ++export {}; +diff --git a/dist/ai/internal/mcpEvents.js b/dist/ai/internal/mcpEvents.js +new file mode 100644 +index 0000000..d875046 +--- /dev/null ++++ b/dist/ai/internal/mcpEvents.js +@@ -0,0 +1,265 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.js"; ++import * as Clock from "../../Clock.js"; ++import * as Duration from "../../Duration.js"; ++import * as Effect from "../../Effect.js"; ++import * as Option from "../../Option.js"; ++import * as Queue from "../../Queue.js"; ++import * as Result from "../../Result.js"; ++import * as Rpc from "../../rpc/Rpc.js"; ++import * as RpcGroup from "../../rpc/RpcGroup.js"; ++import * as Schema from "../../Schema.js"; ++import * as Stream from "../../Stream.js"; ++import * as PublicMcpSchema from "../McpSchema.js"; ++import * as McpProtocol from "./mcpProtocol.js"; ++import * as Stateless from "./mcpSchema/v2026_07_28.js"; ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events"; ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = (extensions, servesEvents) => servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions; ++const methodNotFound = (method) => new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++}); ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core, method) => Effect.flatMap(core.registrationPresence, (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method))); ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value) => new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++}); ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++const optional = Stateless.optional; ++const Cursor = Schema.NullOr(Schema.String); ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest(Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) { ++} ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++}; ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++}), [Stateless.UnknownObject]); ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) { ++} ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest(Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) { ++} ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) { ++} ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make(EventsActiveNotification, EventsEventNotification, EventsHeartbeatNotification, EventsErrorNotification, EventsTerminatedNotification) { ++} ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++const DEFAULT_HEARTBEAT_MS = 30_000; ++const MIN_HEARTBEAT_MS = 1_000; ++const MAX_HEARTBEAT_MS = 300_000; ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16; ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested) => Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)); ++const isJson = Schema.is(Schema.Json); ++/** ++ * @internal ++ */ ++export const wireError = (failure) => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}); ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function* (options) { ++ const { heartbeatMs, name, subscription } = options; ++ let cursor = subscription.cursor; ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0; ++ const send = (tag, payload) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at; ++ })); ++ const active = (truncated) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }); ++ yield* active(subscription.truncated); ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }); ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)); ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result); ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }); ++ } ++ return; ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }); ++ continue; ++ } ++ const item = next.success.value; ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor; ++ const { _meta, _tag, ...occurrence } = item; ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }); ++ break; ++ } ++ case "Position": { ++ cursor = item.cursor; ++ break; ++ } ++ case "Gap": { ++ cursor = item.cursor; ++ yield* active(true); ++ break; ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }); ++ break; ++ } ++ } ++ } ++}, Effect.scoped); +diff --git a/dist/ai/internal/mcpProtocol/v2026_07_28.js b/dist/ai/internal/mcpProtocol/v2026_07_28.js +index af1ceed..467dd8a 100644 +--- a/dist/ai/internal/mcpProtocol/v2026_07_28.js ++++ b/dist/ai/internal/mcpProtocol/v2026_07_28.js +@@ -17,6 +17,7 @@ import * as Schema from "../../../Schema.js"; + import * as Scope from "../../../Scope.js"; + import * as PublicMcpSchema from "../../McpSchema.js"; + import * as McpCore from "../mcpCore.js"; ++import * as McpEvents from "../mcpEvents.js"; + import * as McpProtocol from "../mcpProtocol.js"; + import * as McpSchema from "../mcpSchema/v2026_07_28.js"; + import * as McpSkills from "../mcpSkills.js"; +@@ -242,7 +243,7 @@ const unsupported = operation => new PublicMcpSchema.McpReverseOperationUnsuppor + /** + * @internal + */ +-export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs); ++export const handlerRpcs = /*#__PURE__*/McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs, McpEvents.StatelessRpcs); + /** + * @internal + */ +@@ -260,6 +261,8 @@ export const makeHandlers = (core, _lifecycle, context) => { + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult); + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult); + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult); ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult); ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult); + const sendNotification = context.sendNotification; + const supportsSubscriptions = sendNotification !== undefined; + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -277,7 +280,7 @@ export const makeHandlers = (core, _lifecycle, context) => { + completions: {}, + logging: {} + }; +- const declared = McpSkills.declareExtension(extensions, presence.skills); ++ const declared = McpEvents.declareExtension(McpSkills.declareExtension(extensions, presence.skills), presence.events); + if (declared !== undefined) capabilities.extensions = declared; + if (presence.tools) capabilities.tools = { + listChanged: supportsSubscriptions +@@ -297,6 +300,20 @@ export const makeHandlers = (core, _lifecycle, context) => { + serverInfo: context.serverInfo + }; + }); ++ const requireEvents = (method) => McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))); ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function* (registration, args) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest); ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers); ++ } ++ }); ++ // Webhook delivery is not implemented, so subscribing refuses every event type. ++ const refuseWebhook = Effect.fnUntraced(function* (method, name) { ++ yield* requireEvents(method); ++ yield* core.events.get(name, yield* getInvocation); ++ return yield* McpEvents.unsupportedDelivery("webhook"); ++ }); + const requireSkills = method => McpSkills.requireSkills(core, method).pipe(Effect.catch(error => failWithHttpStatus(404, error))); + const getInvocation = PublicMcpSchema.McpRequestContext.useSync(McpProtocol.invocationFromRequestContext); + const getInputInvocation = Effect.fnUntraced(function* (request) { +@@ -592,6 +609,77 @@ export const makeHandlers = (core, _lifecycle, context) => { + }, context.serverInfo); + return yield* decodeReadResourceDirectoryResult(result); + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/list"); ++ yield* McpProtocol.rejectCursor(request.cursor); ++ const events = yield* core.events.list(yield* getInvocation); ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push"); ++ return delivery.length === 0 ? [] : [{ ...event, delivery }]; ++ }); ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo); ++ return yield* decodeListEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function* (request) { ++ yield* requireEvents("events/poll"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation); ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ })), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo); ++ return yield* decodePollEventsResult(result); ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function* (request, { client, requestId }) { ++ yield* requireEvents("events/stream"); ++ const invocation = yield* getInvocation; ++ const registration = yield* core.events.get(request.name, invocation); ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push"); ++ } ++ yield* validateEventHeaders(registration, request.arguments); ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId }; ++ const send = (tag, payload) => sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }); ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs); ++ yield* Effect.raceFirst(registration.stream({ arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, invocation, (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send })), context.awaitClientEnd ?? Effect.never); ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo); ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }); ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function* (request) { ++ return yield* refuseWebhook("events/subscribe", request.name); ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function* (request) { ++ return yield* refuseWebhook("events/unsubscribe", request.name); ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function* (_request) { + return yield* Effect.void; + }) +@@ -613,10 +701,10 @@ const runtime = { + export const protocol = /*#__PURE__*/McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: /*#__PURE__*/McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: /*#__PURE__*/McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/dist/ai/internal/mcpRuntime.js b/dist/ai/internal/mcpRuntime.js +index 88238ff..274e513 100644 +--- a/dist/ai/internal/mcpRuntime.js ++++ b/dist/ai/internal/mcpRuntime.js +@@ -39,6 +39,10 @@ const routingNameKey = method => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name"; + case "resources/read": + return "uri"; +@@ -340,7 +344,8 @@ export const make = /*#__PURE__*/Effect.fnUntraced(function* (protocols) { + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && (input.method === "subscriptions/listen" || input.method === "events/stream") + }; + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, +diff --git a/src/ai/McpSchema.ts b/src/ai/McpSchema.ts +index ba6c830..1e58fb9 100644 +--- a/src/ai/McpSchema.ts ++++ b/src/ai/McpSchema.ts +@@ -740,6 +740,57 @@ export const HEADER_MISMATCH_ERROR_CODE = -32020 as const + */ + export const UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE = -32022 as const + ++/** ++ * Represents the MCP error code for a referenced entity that does not exist, ++ * such as an unknown event name. `data.kind` may say which. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const NOT_FOUND_ERROR_CODE = -32023 as const ++ ++/** ++ * Represents the MCP error code for a principal that is not permitted, or ++ * whose access was revoked. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const FORBIDDEN_ERROR_CODE = -32024 as const ++ ++/** ++ * Represents the MCP error code for a server-imposed limit or quota. ++ * `data.limit` names it. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const RESOURCE_EXHAUSTED_ERROR_CODE = -32025 as const ++ ++/** ++ * Represents the MCP error code for a well-formed request that asks for a ++ * capability or option not supported here. `data` identifies it, for example ++ * `{ feature: "deliveryMode", value: "push" }`. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const UNSUPPORTED_ERROR_CODE = -32026 as const ++ ++/** ++ * Represents the MCP error code for a client-supplied callback endpoint that ++ * failed verification or could not be reached. ++ * ++ * @stability unstable ++ * @category constants ++ * @since 4.1.4 ++ */ ++export const CALLBACK_ENDPOINT_ERROR_CODE = -32027 as const ++ + /** + * Represents an MCP/JSON-RPC error for invalid JSON that could not be parsed. + * +@@ -852,6 +903,74 @@ export class InternalError extends Schema.Error("effect/ai/McpSch + static readonly notImplemented = new InternalError({ message: "Not implemented" }) + } + ++/** ++ * Represents an MCP error for a referenced entity that does not exist. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class NotFound extends Schema.Error("effect/ai/McpSchema/NotFound")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("NotFound"), ++ code: Schema.tag(NOT_FOUND_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a principal that is not permitted. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Forbidden extends Schema.Error("effect/ai/McpSchema/Forbidden")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Forbidden"), ++ code: Schema.tag(FORBIDDEN_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a server-imposed limit or quota. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class ResourceExhausted extends Schema.Error("effect/ai/McpSchema/ResourceExhausted")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("ResourceExhausted"), ++ code: Schema.tag(RESOURCE_EXHAUSTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a capability or option not supported here. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class Unsupported extends Schema.Error("effect/ai/McpSchema/Unsupported")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("Unsupported"), ++ code: Schema.tag(UNSUPPORTED_ERROR_CODE) ++}) {} ++ ++/** ++ * Represents an MCP error for a callback endpoint that failed verification or ++ * could not be reached. ++ * ++ * @stability unstable ++ * @category errors ++ * @since 4.1.4 ++ */ ++export class CallbackEndpointError ++ extends Schema.Error("effect/ai/McpSchema/CallbackEndpointError")({ ++ ...McpErrorBase.fields, ++ _tag: Schema.tag("CallbackEndpointError"), ++ code: Schema.tag(CALLBACK_ENDPOINT_ERROR_CODE) ++ }) ++{} ++ + /** + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. +@@ -1501,6 +1620,76 @@ export class Skill extends Schema.Class( + _meta: optional(UnknownObject) + }) {} + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * How a client receives an event type's occurrences under the MCP Events ++ * extension (SEP-3415): by `events/poll`, an `events/stream` push stream, or ++ * a webhook registered with `events/subscribe`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDelivery = Schema.Literals(["poll", "push", "webhook"]) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDelivery = typeof EventDelivery.Type ++ ++/** ++ * An event type listed by `events/list`: its subscription arguments, its ++ * payload, and the delivery modes it supports. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventDescriptor = Schema.Struct({ ++ name: Schema.String, ++ description: optional(Schema.String), ++ delivery: Schema.Array(EventDelivery), ++ inputSchema: UnknownObject, ++ payloadSchema: UnknownObject, ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventDescriptor = typeof EventDescriptor.Type ++ ++/** ++ * One delivered event. `cursor` is the subscription's position after it, on ++ * push and webhook delivery; poll carries the cursor on the result. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const EventOccurrence = Schema.Struct({ ++ eventId: Schema.String, ++ name: Schema.String, ++ timestamp: Schema.String, ++ data: UnknownObject, ++ cursor: optional(Schema.NullOr(Schema.String)), ++ _meta: optional(UnknownObject) ++}) ++ ++/** ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventOccurrence = typeof EventOccurrence.Type ++ + // ============================================================================= + // Prompts + // ============================================================================= +diff --git a/src/ai/McpServer.ts b/src/ai/McpServer.ts +index 4c2e191..3bf4321 100644 +--- a/src/ai/McpServer.ts ++++ b/src/ai/McpServer.ts +@@ -344,6 +344,9 @@ export type MiddlewareMethod = + | "skills/list" + | "skills/get" + | "resources/directory/read" ++ | "events/list" ++ | "events/poll" ++ | "events/stream" + + /** + * Request metadata passed to MCP middleware. +@@ -819,7 +822,14 @@ const internalError = new InternalError({ message: "Internal error" }) + const rejectWith = (error: McpErrorBase) => + Effect.fail(new McpCore.RequestRejected({ code: error.code, message: error.message, data: error.data, error })) + +-type CallMethod = "tools/call" | "resources/read" | "prompts/get" | "completion/complete" | "skills/get" ++type CallMethod = ++ | "tools/call" ++ | "resources/read" ++ | "prompts/get" ++ | "completion/complete" ++ | "skills/get" ++ | "events/poll" ++ | "events/stream" + + type ListMethod = Exclude + +@@ -829,6 +839,8 @@ interface NotFoundErrors { + readonly "prompts/get": McpCore.PromptNotFound + readonly "completion/complete": InvalidParams + readonly "skills/get": McpCore.SkillNotFound ++ readonly "events/poll": McpSchema.NotFound ++ readonly "events/stream": McpSchema.NotFound + } + + const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod] => { +@@ -843,6 +855,9 @@ const notFound = (method: CallMethod, target: string): NotFoundErrors[CallMethod + return new InvalidParams({ message: "Unknown completion reference or argument" }) + case "skills/get": + return new McpCore.SkillNotFound({ uri: target }) ++ case "events/poll": ++ case "events/stream": ++ return McpCore.eventNotFound(target) + } + } + +@@ -4134,6 +4149,276 @@ export const registerSkill: (options: SkillOptions) => Effect.Effect => + Layer.effectDiscard(registerSkill(options)) + ++// ============================================================================= ++// Events ++// ============================================================================= ++ ++/** ++ * A failure an event handler reports to the client: a JSON-RPC error on a ++ * poll or when a push stream opens, and `notifications/events/terminated` ++ * once it is open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventError = ++ | InvalidParams ++ | InternalError ++ | McpSchema.NotFound ++ | McpSchema.Forbidden ++ | McpSchema.ResourceExhausted ++ | McpSchema.Unsupported ++ ++/** ++ * Where a poll starts. `cursor` is `null` to start from now, which replays ++ * nothing. With a cursor, replay starts at whichever is later: the cursor, or ++ * `maxAgeMs` before now. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * Where a push stream starts, read as for {@link EventPollRequest}. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventStreamRequest { ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * One occurrence, with its payload as the event's `payload` schema types it. ++ * `eventId` stays the same however often the occurrence is delivered. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOccurrence { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: A ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * A poll's answer. `truncated` says delivery started later than the cursor, ++ * and `hasMore` that `maxEvents` cut the batch short. `nextPollMs` defaults ++ * to 30 seconds. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventPollResult { ++ readonly events: ReadonlyArray> ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly hasMore?: boolean | undefined ++ readonly nextPollMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries: an occurrence and the cursor after it; a ++ * position checked without a match, which the next heartbeat reports; a gap, ++ * sent as a fresh `notifications/events/active` with `truncated`; or an error ++ * that leaves the stream open. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EventOccurrence) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventError } ++ ++/** ++ * An accepted push subscription: where it starts, and its items. A failure ++ * of `items` ends it. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated?: boolean | undefined ++ readonly items: Stream.Stream, EventError, R> ++} ++ ++/** ++ * Options for {@link registerEvent} and {@link event}. ++ * ++ * **Details** ++ * ++ * `parameters` types the subscription arguments, an empty object by default, ++ * and `payload` the occurrences' `data`; both are advertised as JSON Schema ++ * by `events/list`. `poll` offers poll delivery and `stream` push delivery, ++ * and at least one is required. Webhook delivery is not supported, so ++ * `events/subscribe` answers `Unsupported`. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export interface EventOptions, Payload extends Schema.Codec, R> { ++ readonly name: string ++ readonly description?: string | undefined ++ readonly parameters?: Params | undefined ++ readonly payload: Payload ++ readonly _meta?: Readonly> | undefined ++ readonly annotations?: Context.Context | undefined ++ readonly poll?: ++ | (( ++ args: Params["Type"], ++ request: EventPollRequest ++ ) => Effect.Effect, EventError, R>) ++ | undefined ++ readonly stream?: ++ | (( ++ args: Params["Type"], ++ request: EventStreamRequest ++ ) => Effect.Effect, EventError, R | Scope.Scope>) ++ | undefined ++} ++ ++const DEFAULT_NEXT_POLL_MS = 30_000 ++ ++/** ++ * Registers an event type under the MCP Events extension (SEP-3415). ++ * ++ * **Details** ++ * ++ * The server declares `io.modelcontextprotocol/events` on revision ++ * `2026-07-28` once any event type is registered, and answers `events/list`, ++ * `events/poll` and `events/stream`. A push stream runs `stream` for its ++ * lifetime inside the request's middleware, sends heartbeats carrying the ++ * last cursor, and ends when the client goes away. Services read by `poll` ++ * and `stream` are request-level, as for tools. ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const registerEvent: < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions) => Effect.Effect> = ++ Effect.fnUntraced(function*(options: EventOptions, Schema.Codec, any>) { ++ const { name, poll, stream } = options ++ if (poll === undefined && stream === undefined) { ++ return yield* Effect.die(new Cause.IllegalArgumentError(`Event ${name}: give it poll, stream or both`)) ++ } ++ const registry = yield* McpServer ++ const { core, globalMiddleware } = internalState.get(registry)! ++ const services = yield* Effect.context() ++ const annotations = options.annotations ?? Context.empty() ++ const { invoke, visible } = makeInvoke(services, globalMiddleware) ++ const parameters = options.parameters ?? Schema.Struct({}) ++ const decodeArguments = Schema.decodeUnknownEffect(Schema.toCodecJson(parameters)) ++ const encodePayload = Schema.encodeUnknownEffect(Schema.toCodecJson(options.payload)) ++ const argumentsOf = (args: unknown) => ++ decodeArguments(args).pipe(Effect.mapError((error) => new InvalidParams({ message: error.message }))) ++ const encodeEvent = (event: EventOccurrence) => ++ encodePayload(event.data).pipe( ++ Effect.flatMap((data) => Predicate.isReadonlyObject(data) ? Effect.succeed(data) : Effect.fail(data)), ++ Effect.map((data): McpCore.EncodedEvent => ({ ++ eventId: event.eventId, ++ timestamp: event.timestamp, ++ data, ++ ...(event._meta === undefined ? {} : { _meta: event._meta }) ++ })), ++ Effect.mapError(() => new InternalError({ message: `Event '${name}' payload failed to encode` })) ++ ) ++ yield* core.events.register({ ++ descriptor: { ++ name, ++ ...(options.description === undefined ? {} : { description: options.description }), ++ delivery: [...(poll === undefined ? [] : ["poll" as const]), ...(stream === undefined ? [] : ["push" as const])], ++ inputSchema: toolJsonSchema(parameters, false) as Record, ++ payloadSchema: toolJsonSchema(options.payload, false) as Record, ++ ...(options._meta === undefined ? {} : { _meta: options._meta }) ++ }, ++ isVisible: isEnabled(annotations), ++ visible: visible("events/list", name), ++ poll: poll === undefined ? undefined : (request, invocation) => ++ invoke( ++ Effect.gen(function*() { ++ const result = yield* poll(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }) ++ return { ++ events: yield* Effect.forEach(result.events, encodeEvent), ++ cursor: result.cursor, ++ truncated: result.truncated ?? false, ++ hasMore: result.hasMore ?? false, ++ nextPollMs: result.nextPollMs ?? DEFAULT_NEXT_POLL_MS ++ } ++ }), ++ invocation, ++ { method: "events/poll", target: name, payload: request } ++ ), ++ stream: stream === undefined ? undefined : (request, invocation, deliver) => ++ invoke( ++ Effect.scoped(Effect.gen(function*() { ++ const subscription = yield* stream(yield* argumentsOf(request.arguments), { ++ cursor: request.cursor, ++ maxAgeMs: request.maxAgeMs ++ }) ++ // The items run on the delivery fiber, so they keep this request's services. ++ const context = yield* Effect.context() ++ const items = subscription.items.pipe( ++ Stream.mapEffect((item): Effect.Effect => ++ item._tag === "Event" ++ ? encodeEvent(item).pipe( ++ Effect.map((event) => ({ ...event, _tag: "Event" as const, cursor: item.cursor })), ++ Effect.catch((error) => Effect.succeed({ _tag: "Error" as const, error })) ++ ) ++ : Effect.succeed(item) ++ ), ++ Stream.provideContext(context) ++ ) ++ yield* deliver({ cursor: subscription.cursor, truncated: subscription.truncated ?? false, items }) ++ })), ++ invocation, ++ { method: "events/stream", target: name, payload: request } ++ ) ++ }) ++ }) as any ++ ++/** ++ * Creates a layer that registers an event type under the MCP Events ++ * extension (SEP-3415). ++ * ++ * @see {@link registerEvent} for the Effect-level event registration API ++ * ++ * @stability unstable ++ * @category events ++ * @since 4.1.4 ++ */ ++export const event = < ++ Params extends Schema.Codec = Schema.Struct<{}>, ++ Payload extends Schema.Codec = Schema.Codec, ++ R = never ++>(options: EventOptions): Layer.Layer> => ++ Layer.effectDiscard(registerEvent(options)) ++ + /** + * Registers an MCP prompt from an Effect program. + * +diff --git a/src/ai/internal/mcpCore.ts b/src/ai/internal/mcpCore.ts +index 643982d..597701f 100644 +--- a/src/ai/internal/mcpCore.ts ++++ b/src/ai/internal/mcpCore.ts +@@ -8,6 +8,7 @@ import * as Data from "../../Data.ts" + import * as Effect from "../../Effect.ts" + import type * as McpProtocol from "../McpProtocol.ts" + import * as McpSchema from "../McpSchema.ts" ++import type * as Stream from "../../Stream.ts" + + /** + * @internal +@@ -330,6 +331,118 @@ export interface SkillRegistration { + readonly directory: (uri: string) => ReadonlyArray | undefined + } + ++/** ++ * A failure an event handler reports to the client as a JSON-RPC error, such ++ * as `McpSchema.Forbidden` or `McpSchema.InvalidParams`. ++ * ++ * @internal ++ */ ++export interface EventFailure { ++ readonly code: number ++ readonly message: string ++ readonly data?: unknown ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollRequest { ++ readonly arguments: Readonly> ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++ readonly maxEvents?: number | undefined ++} ++ ++/** ++ * An occurrence with its payload already encoded for the wire. ++ * ++ * @internal ++ */ ++export interface EncodedEvent { ++ readonly eventId: string ++ readonly timestamp: string ++ readonly data: Readonly> ++ readonly _meta?: Readonly> | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface EventPollOutcome { ++ readonly events: ReadonlyArray ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly hasMore: boolean ++ readonly nextPollMs: number ++} ++ ++/** ++ * @internal ++ */ ++export interface EventStreamRequest { ++ readonly arguments: Readonly> ++ readonly cursor: string | null ++ readonly maxAgeMs?: number | undefined ++} ++ ++/** ++ * What a push stream carries after `notifications/events/active`: occurrences, ++ * a position checked without a match (carried by the next heartbeat), a gap ++ * (a fresh `active` with `truncated`), or a recoverable error. ++ * ++ * @internal ++ */ ++export type EventStreamItem = ++ | ({ readonly _tag: "Event"; readonly cursor: string | null } & EncodedEvent) ++ | { readonly _tag: "Position"; readonly cursor: string | null } ++ | { readonly _tag: "Gap"; readonly cursor: string | null } ++ | { readonly _tag: "Error"; readonly error: EventFailure } ++ ++/** ++ * A push subscription the handler accepted. A failure of `items` ends it with ++ * `notifications/events/terminated`. ++ * ++ * @internal ++ */ ++export interface EventSubscription { ++ readonly cursor: string | null ++ readonly truncated: boolean ++ readonly items: Stream.Stream ++} ++ ++/** ++ * @internal ++ */ ++export interface EventRegistration { ++ readonly descriptor: McpSchema.EventDescriptor ++ readonly isVisible: (profile: NegotiatedProtocolProfile) => boolean ++ readonly visible?: Visible | undefined ++ readonly poll?: ++ | (( ++ request: EventPollRequest, ++ invocation: McpInvocation ++ ) => Effect.Effect) ++ | undefined ++ // Runs for the subscription's lifetime: `deliver` takes over once the ++ // handler accepts it, so a failure before that is the request's error. ++ readonly stream?: ++ | (( ++ request: EventStreamRequest, ++ invocation: McpInvocation, ++ deliver: (subscription: EventSubscription) => Effect.Effect ++ ) => Effect.Effect) ++ | undefined ++} ++ ++/** ++ * @internal ++ */ ++export interface Events { ++ readonly register: (registration: EventRegistration) => Effect.Effect ++ readonly list: (invocation: McpInvocation) => Effect.Effect, RequestRejected> ++ readonly get: (name: string, invocation: McpInvocation) => Effect.Effect ++} ++ + /** + * @internal + */ +@@ -507,11 +620,13 @@ export interface McpCore { + readonly prompts: Prompts + readonly completions: Completions + readonly skills: Skills ++ readonly events: Events + readonly registrationPresence: Effect.Effect<{ + readonly tools: boolean + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +@@ -523,6 +638,12 @@ export interface McpCore { + */ + export type Visible = (invocation: McpInvocation) => Effect.Effect + ++/** ++ * @internal ++ */ ++export const eventNotFound = (name: string): McpSchema.NotFound => ++ new McpSchema.NotFound({ message: `Event '${name}' not found`, data: { kind: "event" } }) ++ + // Whether one skill directory contains the other, or both are the same. + const skillsOverlap = (a: string, b: string): boolean => { + const rootA = a.slice(0, -"/SKILL.md".length) +@@ -539,6 +660,7 @@ export const make: Effect.Effect = Effect.sync(() => { + const resourceTemplateRegistrations: Array = [] + const promptRegistrations = new Map() + const skillRegistrations = new Map() ++ const eventRegistrations = new Map() + const skillFiles = new Set() + const completionRegistrations = new Map< + string, +@@ -717,12 +839,28 @@ export const make: Effect.Effect = Effect.sync(() => { + }) + } + ++ const events: Events = { ++ register: (registration) => ++ Effect.sync(() => { ++ eventRegistrations.set(registration.descriptor.name, registration) ++ }), ++ list: (invocation) => filterList(eventRegistrations.values(), invocation), ++ get: (name, invocation) => ++ Effect.suspend(() => { ++ const registration = eventRegistrations.get(name) ++ return registration !== undefined && registration.isVisible(invocation.protocol) ++ ? Effect.succeed(registration) ++ : Effect.fail(eventNotFound(name)) ++ }) ++ } ++ + const registrationPresence = Effect.sync(() => ({ + tools: registrations.size > 0, + resources: resourceRegistrations.length > 0 || resourceTemplateRegistrations.length > 0, + prompts: promptRegistrations.size > 0, +- skills: skillRegistrations.size > 0 ++ skills: skillRegistrations.size > 0, ++ events: eventRegistrations.size > 0 + })) + +- return { tools, resources, prompts, completions, skills, registrationPresence } ++ return { tools, resources, prompts, completions, skills, events, registrationPresence } + }) +diff --git a/src/ai/internal/mcpEvents.ts b/src/ai/internal/mcpEvents.ts +new file mode 100644 +index 0000000..54b2ca8 +--- /dev/null ++++ b/src/ai/internal/mcpEvents.ts +@@ -0,0 +1,315 @@ ++/** ++ * The Events extension (SEP-3415): wire schemas on revision 2026-07-28 and ++ * the delivery loop behind a push stream. ++ */ ++import * as Cause from "../../Cause.ts" ++import * as Clock from "../../Clock.ts" ++import * as Duration from "../../Duration.ts" ++import * as Effect from "../../Effect.ts" ++import * as Option from "../../Option.ts" ++import * as Queue from "../../Queue.ts" ++import * as Result from "../../Result.ts" ++import * as Rpc from "../../rpc/Rpc.ts" ++import * as RpcGroup from "../../rpc/RpcGroup.ts" ++import * as Schema from "../../Schema.ts" ++import * as Stream from "../../Stream.ts" ++import * as PublicMcpSchema from "../McpSchema.ts" ++import type * as McpCore from "./mcpCore.ts" ++import * as McpProtocol from "./mcpProtocol.ts" ++import * as Stateless from "./mcpSchema/v2026_07_28.ts" ++ ++/** ++ * @internal ++ */ ++export const EXTENSION_ID = "io.modelcontextprotocol/events" ++ ++/** ++ * Adds the extension declaration while any event type is registered. The ++ * server sends no `notifications/events/list_changed`, so its settings object ++ * is empty. ++ * ++ * @internal ++ */ ++export const declareExtension = ( ++ extensions: Readonly> | undefined, ++ servesEvents: boolean ++): Readonly> | undefined => ++ servesEvents ? { ...extensions, [EXTENSION_ID]: {} } : extensions ++ ++const methodNotFound = (method: string) => ++ new McpProtocol.ProtocolError({ ++ code: PublicMcpSchema.METHOD_NOT_FOUND_ERROR_CODE, ++ message: `Method not found: ${method}` ++ }) ++ ++/** ++ * Fails with `Method not found` while no event type is registered, as a ++ * server that does not declare the extension. ++ * ++ * @internal ++ */ ++export const requireEvents = (core: McpCore.McpCore, method: string) => ++ Effect.flatMap( ++ core.registrationPresence, ++ (presence) => presence.events ? Effect.void : Effect.fail(methodNotFound(method)) ++ ) ++ ++/** ++ * @internal ++ */ ++export const unsupportedDelivery = (value: PublicMcpSchema.EventDelivery) => ++ new PublicMcpSchema.Unsupported({ ++ message: `Delivery mode '${value}' is not supported for this event`, ++ data: { feature: "deliveryMode", value } ++ }) ++ ++// ============================================================================= ++// Wire schemas ++// ============================================================================= ++ ++const optional = Stateless.optional ++const Cursor = Schema.NullOr(Schema.String) ++const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)) ++ ++/** ++ * @internal ++ */ ++export const ListEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ...Stateless.PaginatedResult, events: Schema.Array(PublicMcpSchema.EventDescriptor) }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class ListEvents extends Rpc.make("events/list", { ++ success: ListEventsResult, ++ error: Stateless.McpError, ++ payload: Stateless.PaginatedRequestParams ++}) {} ++ ++const SubscriptionParams = { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ cursor: optional(Cursor), ++ maxAgeMs: optional(NonNegativeInt) ++} ++ ++/** ++ * @internal ++ */ ++export const PollEventsResult = Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ events: Schema.Array(PublicMcpSchema.EventOccurrence), ++ cursor: Cursor, ++ truncated: Schema.Boolean, ++ hasMore: Schema.Boolean, ++ nextPollMs: NonNegativeInt ++ }), ++ [Stateless.UnknownObject] ++) ++ ++/** ++ * @internal ++ */ ++export class PollEvents extends Rpc.make("events/poll", { ++ success: PollEventsResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, maxEvents: optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class StreamEvents extends Rpc.make("events/stream", { ++ success: Stateless.SubscriptionsListenResult, ++ error: Stateless.McpError, ++ payload: { ...SubscriptionParams, heartbeatMs: optional(NonNegativeInt) } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class SubscribeEvents extends Rpc.make("events/subscribe", { ++ success: Schema.StructWithRest( ++ Schema.Struct({ ++ ...Stateless.ResultMeta, ++ id: Schema.String, ++ refreshBefore: Schema.NullOr(Schema.String), ++ cursor: Cursor, ++ truncated: Schema.Boolean ++ }), ++ [Stateless.UnknownObject] ++ ), ++ error: Stateless.McpError, ++ payload: { ++ ...SubscriptionParams, ++ delivery: Stateless.UnknownObject, ++ ttlMs: optional(Schema.NullOr(NonNegativeInt)) ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class UnsubscribeEvents extends Rpc.make("events/unsubscribe", { ++ success: Schema.StructWithRest(Schema.Struct(Stateless.ResultMeta), [Stateless.UnknownObject]), ++ error: Stateless.McpError, ++ payload: { ++ ...Stateless.RequestParams.fields, ++ name: Schema.String, ++ arguments: optional(Stateless.UnknownObject), ++ delivery: Stateless.UnknownObject ++ } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsActiveNotification extends Rpc.make("notifications/events/active", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor, truncated: Schema.Boolean, heartbeatMs: NonNegativeInt } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsEventNotification extends Rpc.make("notifications/events/event", { ++ payload: { ...PublicMcpSchema.EventOccurrence.fields, ...Stateless.NotificationParams.fields } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsHeartbeatNotification extends Rpc.make("notifications/events/heartbeat", { ++ payload: { ...Stateless.NotificationParams.fields, cursor: Cursor } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsErrorNotification extends Rpc.make("notifications/events/error", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * @internal ++ */ ++export class EventsTerminatedNotification extends Rpc.make("notifications/events/terminated", { ++ payload: { ...Stateless.NotificationParams.fields, error: Stateless.McpError } ++}) {} ++ ++/** ++ * The extension's requests on revision 2026-07-28. ++ * ++ * @internal ++ */ ++export class StatelessRpcs ++ extends RpcGroup.make(ListEvents, PollEvents, StreamEvents, SubscribeEvents, UnsubscribeEvents) ++{} ++ ++/** ++ * The notifications a push stream carries. ++ * ++ * @internal ++ */ ++export class ServerNotificationRpcs extends RpcGroup.make( ++ EventsActiveNotification, ++ EventsEventNotification, ++ EventsHeartbeatNotification, ++ EventsErrorNotification, ++ EventsTerminatedNotification ++) {} ++ ++// ============================================================================= ++// Push delivery ++// ============================================================================= ++ ++const DEFAULT_HEARTBEAT_MS = 30_000 ++const MIN_HEARTBEAT_MS = 1_000 ++const MAX_HEARTBEAT_MS = 300_000 ++// Occurrences the handler may run ahead of a slow client before it waits. ++const PENDING_ITEMS = 16 ++ ++/** ++ * The heartbeat interval granted for a suggested one. ++ * ++ * @internal ++ */ ++export const grantHeartbeat = (suggested: number | undefined): number => ++ Math.min(MAX_HEARTBEAT_MS, Math.max(MIN_HEARTBEAT_MS, suggested ?? DEFAULT_HEARTBEAT_MS)) ++ ++const isJson = Schema.is(Schema.Json) ++ ++/** ++ * @internal ++ */ ++export const wireError = (failure: McpCore.EventFailure): Stateless.McpError => ({ ++ code: failure.code, ++ message: failure.message, ++ ...(failure.data !== undefined && isJson(failure.data) ? { data: failure.data } : {}) ++}) ++ ++/** ++ * Sends `notifications/events/active`, then each occurrence, and a heartbeat ++ * with the position checked so far whenever `heartbeatMs` passes without ++ * another message. A failure of the subscription's items ends it with ++ * `notifications/events/terminated`. `send` adds the subscription id. ++ * ++ * @internal ++ */ ++export const deliver = Effect.fnUntraced(function*(options: { ++ readonly name: string ++ readonly subscription: McpCore.EventSubscription ++ readonly heartbeatMs: number ++ readonly send: (tag: string, payload: Readonly>) => Effect.Effect ++}) { ++ const { heartbeatMs, name, subscription } = options ++ let cursor = subscription.cursor ++ // Measured from the last message sent: a Position changes the cursor but sends nothing. ++ let sentAt = 0 ++ const send = (tag: string, payload: Readonly>) => ++ options.send(tag, payload).pipe(Effect.andThen(Clock.currentTimeMillis), Effect.map((at) => { ++ sentAt = at ++ })) ++ const active = (truncated: boolean) => send(EventsActiveNotification._tag, { cursor, truncated, heartbeatMs }) ++ yield* active(subscription.truncated) ++ const items = yield* Stream.toQueue(subscription.items, { capacity: PENDING_ITEMS }) ++ while (true) { ++ const wait = Math.max(0, sentAt + heartbeatMs - (yield* Clock.currentTimeMillis)) ++ const next = yield* Queue.take(items).pipe(Effect.timeoutOption(Duration.millis(wait)), Effect.result) ++ if (Result.isFailure(next)) { ++ if (!Cause.isDone(next.failure)) { ++ yield* send(EventsTerminatedNotification._tag, { error: wireError(next.failure) }) ++ } ++ return ++ } ++ if (Option.isNone(next.success)) { ++ yield* send(EventsHeartbeatNotification._tag, { cursor }) ++ continue ++ } ++ const item = next.success.value ++ switch (item._tag) { ++ case "Event": { ++ cursor = item.cursor ++ const { _meta, _tag, ...occurrence } = item ++ yield* send(EventsEventNotification._tag, { ...occurrence, name, ...(_meta === undefined ? {} : { _meta }) }) ++ break ++ } ++ case "Position": { ++ cursor = item.cursor ++ break ++ } ++ case "Gap": { ++ cursor = item.cursor ++ yield* active(true) ++ break ++ } ++ case "Error": { ++ yield* send(EventsErrorNotification._tag, { error: wireError(item.error) }) ++ break ++ } ++ } ++ } ++}, Effect.scoped) +diff --git a/src/ai/internal/mcpProtocol.ts b/src/ai/internal/mcpProtocol.ts +index 5393651..f40915b 100644 +--- a/src/ai/internal/mcpProtocol.ts ++++ b/src/ai/internal/mcpProtocol.ts +@@ -484,6 +484,7 @@ export interface HandlerInstallationContext { + readonly resources: boolean + readonly prompts: boolean + readonly skills: boolean ++ readonly events: boolean + }> + } + +diff --git a/src/ai/internal/mcpProtocol/v2026_07_28.ts b/src/ai/internal/mcpProtocol/v2026_07_28.ts +index a701ec8..9b9a6fd 100644 +--- a/src/ai/internal/mcpProtocol/v2026_07_28.ts ++++ b/src/ai/internal/mcpProtocol/v2026_07_28.ts +@@ -22,6 +22,7 @@ import type * as Types from "../../../Types.ts" + import type * as PublicMcpProtocol from "../../McpProtocol.ts" + import * as PublicMcpSchema from "../../McpSchema.ts" + import * as McpCore from "../mcpCore.ts" ++import * as McpEvents from "../mcpEvents.ts" + import * as McpProtocol from "../mcpProtocol.ts" + import * as McpSchema from "../mcpSchema/v2026_07_28.ts" + import * as McpSkills from "../mcpSkills.ts" +@@ -344,7 +345,11 @@ const unsupported = ( + /** + * @internal + */ +-export const handlerRpcs = McpSchema.ClientRequestRpcs.merge(McpSchema.ClientNotificationRpcs, McpSkills.StatelessRpcs) ++export const handlerRpcs = McpSchema.ClientRequestRpcs.merge( ++ McpSchema.ClientNotificationRpcs, ++ McpSkills.StatelessRpcs, ++ McpEvents.StatelessRpcs ++) + + /** + * @internal +@@ -370,6 +375,8 @@ export const makeHandlers = ( + const decodeListSkillsResult = Schema.decodeUnknownEffect(McpSkills.ListSkillsResult) + const decodeGetSkillResult = Schema.decodeUnknownEffect(McpSkills.GetSkillResult) + const decodeReadResourceDirectoryResult = Schema.decodeUnknownEffect(McpSkills.ReadResourceDirectoryResult) ++ const decodeListEventsResult = Schema.decodeUnknownEffect(McpEvents.ListEventsResult) ++ const decodePollEventsResult = Schema.decodeUnknownEffect(McpEvents.PollEventsResult) + const sendNotification = context.sendNotification + const supportsSubscriptions = sendNotification !== undefined + // Older adapters accept arbitrary JSON; this binding requires extension settings objects. +@@ -384,7 +391,10 @@ export const makeHandlers = ( + } + const getDiscovery = Effect.map(context.registrationPresence, (presence) => { + const capabilities: Types.Mutable = { completions: {}, logging: {} } +- const declared = McpSkills.declareExtension(extensions, presence.skills) ++ const declared = McpEvents.declareExtension( ++ McpSkills.declareExtension(extensions, presence.skills), ++ presence.events ++ ) + if (declared !== undefined) capabilities.extensions = declared + if (presence.tools) capabilities.tools = { listChanged: supportsSubscriptions } + if (presence.resources) { +@@ -393,6 +403,24 @@ export const makeHandlers = ( + if (presence.prompts) capabilities.prompts = { listChanged: supportsSubscriptions } + return { supportedVersions: context.supportedVersions, capabilities, serverInfo: context.serverInfo } + }) ++ const requireEvents = (method: string) => ++ McpEvents.requireEvents(core, method).pipe(Effect.catch((error) => failWithHttpStatus(404, error))) ++ // The event type's `x-mcp-header` arguments must match their headers, as a tool's do. ++ const validateEventHeaders = Effect.fnUntraced(function*( ++ registration: McpCore.EventRegistration, ++ args: unknown ++ ) { ++ const httpRequest = yield* Effect.serviceOption(HttpServerRequest.HttpServerRequest) ++ if (Option.isSome(httpRequest)) { ++ yield* validateParameterHeaders(registration.descriptor.inputSchema, args, httpRequest.value.headers) ++ } ++ }) ++ // Webhook delivery is not implemented, so subscribing refuses every event type. ++ const refuseWebhook = Effect.fnUntraced(function*(method: string, name: string) { ++ yield* requireEvents(method) ++ yield* core.events.get(name, yield* getInvocation) ++ return yield* McpEvents.unsupportedDelivery("webhook") ++ }) + const requireSkills = (method: string) => + McpSkills.requireSkills(core, method).pipe( + Effect.catch((error) => failWithHttpStatus(404, error)) +@@ -728,6 +756,92 @@ export const makeHandlers = ( + const result = yield* projectCompleteResult({ ...cacheHint("skills"), resources }, context.serverInfo) + return yield* decodeReadResourceDirectoryResult(result) + }, Effect.mapError(projectError)), ++ "events/list": Effect.fnUntraced(function*(request: typeof McpEvents.ListEvents.payloadSchema.Type) { ++ yield* requireEvents("events/list") ++ yield* McpProtocol.rejectCursor(request.cursor) ++ const events = yield* core.events.list(yield* getInvocation) ++ // Without a notification channel nothing can be pushed. ++ const offered = supportsSubscriptions ? events : events.flatMap((event) => { ++ const delivery = event.delivery.filter((mode) => mode !== "push") ++ return delivery.length === 0 ? [] : [{ ...event, delivery }] ++ }) ++ const result = yield* projectCompleteResult({ events: offered }, context.serverInfo) ++ return yield* decodeListEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/poll": Effect.fnUntraced(function*(request: typeof McpEvents.PollEvents.payloadSchema.Type) { ++ yield* requireEvents("events/poll") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.poll === undefined) { ++ return yield* McpEvents.unsupportedDelivery("poll") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const outcome = yield* registration.poll({ ++ arguments: request.arguments ?? {}, ++ cursor: request.cursor ?? null, ++ maxAgeMs: request.maxAgeMs, ++ maxEvents: request.maxEvents ++ }, invocation) ++ const result = yield* projectCompleteResult({ ++ events: outcome.events.map((event) => ++ omitUndefined({ ++ eventId: event.eventId, ++ name: request.name, ++ timestamp: event.timestamp, ++ data: event.data, ++ _meta: event._meta ++ }) ++ ), ++ cursor: outcome.cursor, ++ truncated: outcome.truncated, ++ hasMore: outcome.hasMore, ++ nextPollMs: outcome.nextPollMs ++ }, context.serverInfo) ++ return yield* decodePollEventsResult(result) ++ }, Effect.mapError(projectError)), ++ "events/stream": Effect.fnUntraced(function*( ++ request: typeof McpEvents.StreamEvents.payloadSchema.Type, ++ { client, requestId }: { readonly client: Rpc.ServerClient; readonly requestId: RpcMessage.RequestId } ++ ) { ++ yield* requireEvents("events/stream") ++ const invocation = yield* getInvocation ++ const registration = yield* core.events.get(request.name, invocation) ++ if (registration.stream === undefined || sendNotification === undefined) { ++ return yield* McpEvents.unsupportedDelivery("push") ++ } ++ yield* validateEventHeaders(registration, request.arguments) ++ const subscriptionMetadata = { "io.modelcontextprotocol/subscriptionId": requestId } ++ const send = (tag: string, payload: Readonly>) => ++ sendNotification(McpSchema.protocolVersion, client.id, { ++ tag, ++ payload: { ++ ...payload, ++ _meta: { ...(Predicate.isReadonlyObject(payload._meta) ? payload._meta : {}), ...subscriptionMetadata } ++ } ++ }) ++ const heartbeatMs = McpEvents.grantHeartbeat(request.heartbeatMs) ++ yield* Effect.raceFirst( ++ registration.stream( ++ { arguments: request.arguments ?? {}, cursor: request.cursor ?? null, maxAgeMs: request.maxAgeMs }, ++ invocation, ++ (subscription) => McpEvents.deliver({ name: request.name, subscription, heartbeatMs, send }) ++ ), ++ context.awaitClientEnd ?? Effect.never ++ ) ++ const encodedServerInfo = yield* encodeImplementation(context.serverInfo) ++ return McpSchema.SubscriptionsListenResult.make({ ++ _meta: { ...subscriptionMetadata, "io.modelcontextprotocol/serverInfo": encodedServerInfo }, ++ resultType: "complete" ++ }) ++ }, Effect.mapError(projectError)), ++ "events/subscribe": Effect.fnUntraced(function*(request: typeof McpEvents.SubscribeEvents.payloadSchema.Type) { ++ return yield* refuseWebhook("events/subscribe", request.name) ++ }, Effect.mapError(projectError)), ++ "events/unsubscribe": Effect.fnUntraced(function*( ++ request: typeof McpEvents.UnsubscribeEvents.payloadSchema.Type ++ ) { ++ return yield* refuseWebhook("events/unsubscribe", request.name) ++ }, Effect.mapError(projectError)), + "notifications/cancelled": Effect.fnUntraced(function*( + _request: typeof McpSchema.CancelledNotification.payloadSchema.Type + ) { +@@ -751,10 +865,10 @@ const runtime = { + export const protocol = McpProtocol.make({ + protocolVersion: McpSchema.protocolVersion, + runtime, +- clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs), ++ clientRpcs: McpSchema.ClientRpcs.merge(McpSkills.StatelessRpcs, McpEvents.StatelessRpcs), + clientNotificationRpcs: McpSchema.ClientNotificationRpcs, + serverRequestRpcs: McpSchema.ServerRequestRpcs, +- serverNotificationRpcs: McpSchema.ServerNotificationRpcs, ++ serverNotificationRpcs: McpSchema.ServerNotificationRpcs.merge(McpEvents.ServerNotificationRpcs), + handlerRpcs, + makeHandlers, + toReverseClient: () => ({ +diff --git a/src/ai/internal/mcpRuntime.ts b/src/ai/internal/mcpRuntime.ts +index 9d4c96e..eb0590c 100644 +--- a/src/ai/internal/mcpRuntime.ts ++++ b/src/ai/internal/mcpRuntime.ts +@@ -53,6 +53,10 @@ const routingNameKey = (method: string): "name" | "uri" | undefined => { + switch (method) { + case "tools/call": + case "prompts/get": ++ case "events/poll": ++ case "events/stream": ++ case "events/subscribe": ++ case "events/unsubscribe": + return "name" + case "resources/read": + return "uri" +@@ -479,7 +483,9 @@ export const make = Effect.fnUntraced(function*( + return { + _tag: "Accepted", + acknowledge: !isRequest || !hasId, +- isSubscription: Predicate.hasProperty(input, "method") && input.method === "subscriptions/listen" ++ // A push subscription stays open until cancelled, so it is never a plain response. ++ isSubscription: Predicate.hasProperty(input, "method") && ++ (input.method === "subscriptions/listen" || input.method === "events/stream") + } + }, + effectLogLevel: (clientId, headers, fallback) => stateful?.effectLogLevel(clientId, headers, fallback) ?? fallback, diff --git a/scripts/check-changed.ts b/scripts/check-changed.ts index 2c7923ba7502b..20991331a5ee3 100644 --- a/scripts/check-changed.ts +++ b/scripts/check-changed.ts @@ -437,6 +437,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { file === "bunfig.toml" || file.startsWith("patches/") || file.startsWith("apps/mobile/deps/") || + file.startsWith("apps/web/deps/") || path.basename(file) === "package.json", ); @@ -482,7 +483,7 @@ const checkChanged = Effect.fn("checkChanged")(function* (input: { if (yield* fs.exists(inRoot(manifest))) yield* copy(manifest); } } - for (const extra of ["apps/mobile/deps", "patches", "bunfig.toml"]) { + for (const extra of ["apps/mobile/deps", "apps/web/deps", "patches", "bunfig.toml"]) { if (yield* fs.exists(inRoot(extra))) yield* copy(extra); } const result = yield* vp(["install", "--lockfile-only", "--ignore-scripts"], temp); diff --git a/scripts/release-smoke.ts b/scripts/release-smoke.ts index 4c0c6bb8b9048..e93180a82a707 100644 --- a/scripts/release-smoke.ts +++ b/scripts/release-smoke.ts @@ -70,11 +70,12 @@ function copyWorkspaceManifestFixture(targetRoot: string): void { NodeFS.cpSync(sourcePath, destinationPath); } - const mobileDependencies = NodePath.resolve(repoRoot, "apps/mobile/deps"); - if (NodeFS.existsSync(mobileDependencies)) { - NodeFS.cpSync(mobileDependencies, NodePath.resolve(targetRoot, "apps/mobile/deps"), { - recursive: true, - }); + // Fork tarballs that file: dependencies install from. + for (const forks of ["apps/mobile/deps", "apps/web/deps"]) { + const source = NodePath.resolve(repoRoot, forks); + if (NodeFS.existsSync(source)) { + NodeFS.cpSync(source, NodePath.resolve(targetRoot, forks), { recursive: true }); + } } const patchesDirectory = NodePath.resolve(repoRoot, "patches"); diff --git a/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts b/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts index b6afb9358cd2b..66c69347e4aa4 100644 --- a/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts +++ b/scripts/scenarios/add-project-tab-reaches-submit.e2e.ts @@ -9,7 +9,8 @@ test( await t3.project("demo"); await t3.open(); - await screen.getByRole("button", "Add project").tap(); + await screen.getByRole("combobox", "Projects").tap(); + await screen.getByRole("option", "Add project").tap(); await screen.getByText("Git URL").tap(); await screen.getByRole("combobox").fill("https://github.com/pingdotgg/t3code.git"); const submit = screen.getByRole("button", "Continue (Enter)"); diff --git a/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts new file mode 100644 index 0000000000000..6cfbafc6c49b2 --- /dev/null +++ b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const FILE = "handoff.txt"; + +test( + "A bare citation leaves the file unresolved when other projects contain several matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("planning"); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: [`See :codex-file-citation{path="${FILE}" line_range_start="1"}`], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-handoff-citation"); + } + }, +); diff --git a/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts new file mode 100644 index 0000000000000..22458e6223fbb --- /dev/null +++ b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts @@ -0,0 +1,34 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A bare citation leaves the file unresolved when the thread project has ambiguous matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: ['See :codex-file-citation{path="handoff.txt" line_range_start="1"}'], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-local-handoff-citation"); + } + }, +); diff --git a/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts new file mode 100644 index 0000000000000..739497a827757 --- /dev/null +++ b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts @@ -0,0 +1,113 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fixture holds Git's HTTP request open. +import * as NodeHttp from "node:http"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { ProjectId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Stream from "effect/Stream"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +test( + "Dismissing clone progress leaves the later failure notification visible", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Other work", messages: ["Start"] }); + const gitRequest = Promise.withResolvers(); + const remote = NodeHttp.createServer((_request, response) => { + gitRequest.resolve(response); + }); + + try { + await new Promise((resolve) => remote.listen(0, "127.0.0.1", resolve)); + const address = remote.address(); + if (!address || typeof address === "string") throw new Error("No Git fixture port"); + const projectId = ProjectId.make( + await runPromise( + SecureRandom.SecureRandom.pipe( + Effect.flatMap((random) => random.uuidV4()), + Effect.provide(NodeCrypto.layer), + ), + ), + ); + const name = "pending-clone"; + const origin = app.baseUrl ?? ""; + await t3.open(thread); + await screen.getByText("Start", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + const createdAt = DateTime.formatIso(yield* DateTime.now); + yield* client["projectClone.start"]({ + projectId, + title: name, + createdAt, + remoteUrl: `http://127.0.0.1:${address.port}/${name}.git`, + destinationPath: `${project}/../${name}`, + }); + }).pipe(Effect.scoped), + ); + const response = await gitRequest.promise; + + const toastTitle = (title: string) => + browser.locator(`[data-slot="toast-title"]:text-is("${title}")`); + const dismiss = async (title: string) => { + await browser + .locator( + `[data-position]:has(> div > [data-slot="toast-close"]):has([data-slot="toast-title"]:text-is("${title}"))`, + ) + .getByRole("button", "Dismiss notification", { exact: true }) + .tap(); + await toastTitle(title).waitFor({ state: "detached" }); + }; + const progress = toastTitle(`Cloning ${name}`); + const failure = toastTitle(`Failed to clone ${name}`); + + await progress.waitFor(); + await dismiss(`Cloning ${name}`); + + response.writeHead(404).end(); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + yield* client.subscribeProjectClones({}).pipe( + Stream.filter((clones) => + clones.some((clone) => clone.projectId === projectId && clone.phase === "failed"), + ), + Stream.runHead, + ); + }).pipe(Effect.scoped, Effect.timeout("10 seconds")), + ); + + try { + await expect(failure).toBeVisible(); + } finally { + await app.screenshot("after-background-clone-fails"); + } + + await dismiss(`Failed to clone ${name}`); + + const retryRequest = Promise.withResolvers(); + remote.once("request", (_request, response) => retryRequest.resolve(response)); + const retry = await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + return yield* client["projectClone.retry"]({ projectId }); + }).pipe(Effect.scoped), + ); + await expect(retry.applied).toBe(true); + const retryResponse = await retryRequest.promise; + await expect(progress).toBeVisible(); + retryResponse.writeHead(404).end(); + await expect(failure).toBeVisible(); + } finally { + remote.close(); + remote.closeAllConnections(); + } + }, +); diff --git a/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts new file mode 100644 index 0000000000000..dbd90361cfe45 --- /dev/null +++ b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts @@ -0,0 +1,139 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodeCredential = Schema.decodeUnknownSync(Schema.Struct({ credential: Schema.String })); + +test( + "A closed linked-thread tab does not take over the conversation when pairing finishes", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("primary"); + const parent = await t3.thread({ + project, + title: "Current work", + messages: ["Keep this conversation open"], + }); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + const second = makeState(SECOND_HOME); + const issued = await runPromise(second.cli(["auth", "session", "issue", "--token-only"])); + // @effect-diagnostics-next-line globalFetch:off -- Seeds the real peer link from the scenario's Node fixture. + const pairing = await fetch(`${host}/api/auth/pairing-token`, { + method: "POST", + headers: { + authorization: `Bearer ${issued.stdout.trim()}`, + "content-type": "application/json", + }, + body: JSON.stringify({ purpose: "peer-link", access: "full-access" }), + }); + if (!pairing.ok) throw new Error(`Could not mint a peer-link code: ${pairing.status}`); + const { credential } = decodeCredential(await pairing.json()); + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "full-access", + }); + }).pipe(Effect.scoped), + ); + + const linkedProject = await second.state.project("linked"); + const linkedTitle = "Remote design notes"; + const linkedPrompt = "Read the remote design notes"; + const remoteThread = await second.state.thread({ + project: linkedProject, + title: linkedTitle, + messages: [linkedPrompt], + }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + await browser.setViewport({ width: 1440, height: 900 }); + + // Restore the same saved tab that opening the delegated thread in the panel would leave. + await browser.addInitScript( + ({ via, linked, parentId, childId, title }) => { + if (location.pathname !== `/${via}/${parentId}`) return; + const id = `linked-thread:${encodeURIComponent(via)}:${encodeURIComponent(linked)}:${encodeURIComponent(childId)}`; + localStorage.setItem( + "t3code:right-panel-state:v2", + JSON.stringify({ + version: 16, + state: { + byThreadKey: { + [`${via}:${parentId}`]: { + isOpen: true, + activeSurfaceId: id, + surfaces: [ + { + kind: "linked-thread", + id, + viaEnvironmentId: via, + environmentId: linked, + threadId: childId, + label: "Scenario", + title, + }, + ], + }, + }, + threadPanelVisibilityByThreadKey: {}, + }, + }), + ); + }, + { + via, + linked, + parentId: parent.threadId, + childId: remoteThread.threadId, + title: linkedTitle, + }, + ); + + const tokenUrl = `${host}/oauth/token`; + const requested = Promise.withResolvers(); + const release = Promise.withResolvers(); + await browser.route(tokenUrl, async (route) => { + if (route.request.method !== "POST") return route.fallback(); + requested.resolve(); + await release.promise; + await route.continue(); + }); + try { + await t3.open(parent); + await screen.getByText(linkedPrompt, { exact: true }).waitFor(); + const originalUrl = await browser.url(); + await screen.getByRole("button", "Connect to interact", { exact: true }).tap(); + await requested.promise; + await screen.getByRole("button", `Close ${linkedTitle}`, { exact: true }).tap(); + + release.resolve(); + await screen + .getByText("This device is paired with it and can use its threads.", { exact: true }) + .waitFor(); + + await app.screenshot("after-pairing-finishes"); + await expect(browser).toHaveURL(originalUrl); + } finally { + release.resolve(); + await browser.unroute(tokenUrl); + } + } finally { + await server.stop(); + } + }, +); diff --git a/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts b/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts new file mode 100644 index 0000000000000..42c5c57b1ea4c --- /dev/null +++ b/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts @@ -0,0 +1,88 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +const linkEnvironments = Effect.fn("scenario.linkEnvironments")(function* ( + primaryOrigin: string, + secondOrigin: string, + fallback: string, +) { + const primary = yield* rpcClient(T3_HOME, primaryOrigin); + const second = yield* rpcClient(SECOND_HOME, secondOrigin); + for (const client of [primary, second]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: secondOrigin, + alternateUrls: [fallback], + pairingCode: credential, + access: "full-access", + }); +}, Effect.scoped); + +test( + "Connect to interact opens the editable thread before a silent fallback times out", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const primary = app.baseUrl ?? ""; + const secondServer = startSecondServer(primary); + try { + const { host } = await secondServer.ready; + const alternate = new URL(host); + alternate.hostname = "127.0.0.2"; + await runPromise(linkEnvironments(primary, host, alternate.origin)); + + const second = makeState(SECOND_HOME).state; + const project = await second.project("linked"); + const thread = await second.thread({ + project, + title: "Linked handoff", + messages: ["first"], + }); + const via = await runPromise(environmentId(primary)); + const target = await runPromise(environmentId(host)); + + await browser.addInitScript((fallback) => { + const fetchActual = globalThis.fetch; + globalThis.fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input), location.href); + if (url.origin !== fallback || url.pathname !== "/.well-known/t3/environment") { + // @effect-diagnostics-next-line globalFetch:off - This interception runs inside the browser. + return fetchActual(input, init); + } + // The browser's network silently drops this route. The preferred address is still real. + return new Promise((_, reject) => { + const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined); + signal?.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); + }; + }, alternate.origin); + + await t3.open(`/linked/${via}/${target}/${thread.threadId}`); + await screen.getByRole("heading", "Linked handoff").waitFor(); + await screen.getByRole("button", "Connect to interact").tap(); + + try { + await expect + .poll(() => browser.evaluate(() => location.pathname), { timeout: 4_000 }) + .toBe(`/${target}/${encodeURIComponent(thread.threadId)}`); + } finally { + await app.screenshot("linked-thread-after-connect"); + } + } finally { + await secondServer.stop(); + } + }, +); diff --git a/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts new file mode 100644 index 0000000000000..fd24c39b74dea --- /dev/null +++ b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts @@ -0,0 +1,105 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +test( + "Try again immediately reads a linked thread once it is reachable", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli([ + "auth", + "pairing", + "create", + "--json", + ]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "approval-required", + }); + }).pipe(Effect.scoped), + ); + + const remote = makeState(SECOND_HOME).state; + const project = await remote.project("linked"); + const prompt = "Read the linked design notes"; + const thread = await remote.thread({ project, title: "Design notes", messages: [prompt] }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + + // Drop only the first subscription, as if the linked machine were briefly unreachable. + // Every later request goes to the real server and reads the seeded thread. + await browser.addInitScript(() => { + let failed = false; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (failed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = Array.isArray(parsed) ? parsed : [parsed]; + const request = messages.find( + (message) => message?._tag === "Request" && message.tag === "peerLinks.subscribeThread", + ); + if (!request) return send.call(this, data); + failed = true; + const others = messages.filter((message) => message !== request); + if (others.length > 0) send.call(this, JSON.stringify(others)); + // @effect-diagnostics-next-line globalTimers:off - This callback is injected into the browser. + setTimeout(() => { + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId: request.id, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "PeerLinkThreadReadError", + reason: "unreachable", + label: "Scenario", + message: "The linked machine is temporarily unreachable.", + }, + }, + ], + }, + }), + }), + ); + }, 0); + }; + }); + + await t3.open(`/linked/${via}/${linked}/${thread.threadId}`); + await screen.getByRole("button", "Try again", { exact: true }).tap(); + await app.screenshot("after-trying-again"); + // The automatic retry waits 15 seconds. This checks the user's explicit retry. + await expect(screen.getByText(prompt, { exact: true })).toBeVisible({ timeout: 4_000 }); + } finally { + await server.stop(); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts new file mode 100644 index 0000000000000..c944cf1ec9d42 --- /dev/null +++ b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts @@ -0,0 +1,80 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const savedResults = Array.from({ length: 17 }, (_, index) => `Saved result ${index + 1}`); +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: [ + { output_type: "stream", name: "stdout", text: Array(12).fill("Processing").join("\n") }, + ...savedResults.map((result) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `${result}` }, + })), + ], + }, + ], +}; +const lastOutput = '[data-notebook-output="0-17"]'; + +test( + "All saved notebook outputs render when they fit in a tall preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // The stream puts the final result below the fold until the user scrolls. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 1070; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator('[data-notebook-output="0-15"] iframe').waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = viewport.scrollHeight; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + const bounds = viewport.getBoundingClientRect(); + return Array.from(viewport.querySelectorAll("[data-notebook-output]"), (output) => { + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return "Output is offscreen"; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }); + }, lastOutput), + ) + .toEqual(savedResults); + } finally { + await app.screenshot("last-saved-output-in-tall-preview"); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts new file mode 100644 index 0000000000000..2897ecc0df7eb --- /dev/null +++ b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts @@ -0,0 +1,77 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: Array.from({ length: 17 }, (_, index) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `Saved result ${index + 1}` }, + })), + }, + ], +}; +const fifteenthOutputFrame = '[data-notebook-output="0-14"] iframe'; +const lastOutput = '[data-notebook-output="0-16"]'; + +test( + "A visible saved notebook output renders when earlier outputs have scrolled above it", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // Leave room for the final output and fewer than sixteen preceding outputs. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 940; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator(fifteenthOutputFrame).waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = 170; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const output = document.querySelector(selector); + const viewport = output?.closest(".scrollbar-gutter-both"); + if (!output || !viewport) return null; + const bounds = viewport.getBoundingClientRect(); + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return null; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }, lastOutput), + ) + .toBe("Saved result 17"); + } finally { + await app.screenshot("last-saved-output"); + } + }, +); diff --git a/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts new file mode 100644 index 0000000000000..8ee5453bbba20 --- /dev/null +++ b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A queued message shows its @-file mention by name, not as a raw link", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "src/foo.ts": "export {};\n" }); + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @foo"); + await screen.getByRole("option", "foo.ts", { exact: false }).tap(); + await expect(composer).toContainText("foo.ts"); + + // The showcase recording streams for several seconds, long enough to queue behind its turn. + await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Show me again"])); + await screen.getByText("Working for", { exact: false }).waitFor(); + // Enter steers by default; the alternate send queues. + await browser.keyboard.press("ControlOrMeta+Enter"); + + const queued = screen.getByRole("listitem", "Queued message 1 of 1, not sent"); + await queued.waitFor(); + // Read the row once: the queued message sends, and its row goes, when the turn ends. + const text = await queued.textContent(); + await app.screenshot("queued-row"); + expect(text).toContain("Review foo.ts"); + }, +); diff --git a/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts new file mode 100644 index 0000000000000..49186eaa4429a --- /dev/null +++ b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts @@ -0,0 +1,64 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +declare global { + interface Window { + releaseOldThemeRead: () => void; + } +} + +test( + "An earlier theme file cannot become the draft after its replacement is rejected", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + + await browser.evaluate(() => { + const target = document.querySelector('input[type="file"]')?.parentElement; + if (!target) throw new Error("No theme file drop target"); + + const gate = Promise.withResolvers(); + const theme = JSON.stringify({ + version: 1, + name: "Earlier theme", + appearance: "dark", + colors: { accent: "#734ee4" }, + }); + const first = new File([theme], "earlier.json", { type: "application/json" }); + const text = File.prototype.text; + File.prototype.text = function () { + if (this.name === first.name) return gate.promise.then(() => theme); + return text.call(this); + }; + window.releaseOldThemeRead = gate.resolve; + + const drop = (file: File) => { + const files = new DataTransfer(); + files.items.add(file); + target.dispatchEvent( + new DragEvent("drop", { dataTransfer: files, bubbles: true, cancelable: true }), + ); + }; + drop(first); + drop(new File([" ".repeat(300_000)], "replacement.json", { type: "application/json" })); + return null; + }); + + await dialog.getByText(/That file is/).waitFor(); + await browser.evaluate(async () => { + window.releaseOldThemeRead(); + // Let the earlier file response and its React update reach the dialog. + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + return null; + }); + await app.screenshot("dialog-after-earlier-theme-read-finishes"); + await expect(dialog.getByRole("button", "Add theme", { exact: true })).toBeDisabled(); + }, +); diff --git a/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts new file mode 100644 index 0000000000000..1f93e154b89e2 --- /dev/null +++ b/scripts/scenarios/stopped-worktree-turn-sends-in-checkout.e2e.ts @@ -0,0 +1,51 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A worktree thread stopped mid-turn and moved to the project checkout runs its next message", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("demo"); + // The question recording waits for an answer, so the turn is running in its new worktree. + const started = await runPromise( + makeState(T3_HOME).cli( + [ + "thread", + "start", + project, + "Ask me something", + "--worktree", + "main", + "--provider", + "devReplay", + "--model", + "question", + "--wait", + "--json", + ], + [2], + ), + ); + await t3.open(JSON.parse(started.stdout) as { threadId: string }); + + const stop = screen.getByRole("button", "Stop generation"); + await stop.waitFor({ timeout: 60_000 }); + await stop.tap(); + await stop.waitFor({ state: "hidden" }); + + await browser.locator('[data-slot="combobox-trigger"][aria-label^="Branch:"]:visible').click(); + await screen.getByRole("option", /^main\b/).tap(); + // The server has moved the thread to the project checkout before the send. + await browser + .locator('[aria-label^="Run context:"][aria-label$="Local checkout"]') + .waitFor({ timeout: 60_000 }); + + await screen.getByRole("textbox").fill("Once more"); + await screen.getByRole("textbox").press("Enter"); + await screen.getByText("Once more").first().waitFor(); + await expect(stop).toBeVisible({ timeout: 60_000 }); + await app.screenshot("running-in-checkout"); + }, +); diff --git a/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts new file mode 100644 index 0000000000000..acd9096465978 --- /dev/null +++ b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts @@ -0,0 +1,75 @@ +import { ProjectSnapshot, ProviderInstanceId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const PROMPT_LOG_LIMIT = 64 * 1024; +const FRAME_OPEN = "".length; + +const deliverStraddlingEmoji = Effect.fn("scenario.deliverStraddlingEmoji")( + function* (origin: string) { + const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); + const { projects } = yield* HttpClient.execute( + HttpClientRequest.get(`${origin}/api/projects`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)), + ); + const client = yield* rpcClient(T3_HOME, origin); + const { task } = yield* client["scheduledTasks.upsert"]({ + title: "Webhook log", + prompt: "{{body.text}}", + enabled: true, + schedule: { type: "webhook" }, + projectId: projects.find((project) => project.title === "webhook-log")!.id, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + // The emoji's high surrogate is the last code unit the delivery log keeps. + const text = `${"a".repeat(PROMPT_LOG_LIMIT - 1 - FRAME_OPEN)}😀 tail`; + yield* HttpClient.execute( + HttpClientRequest.post(`${origin}${task.webhook!.path}`).pipe( + HttpClientRequest.bodyJsonUnsafe({ text }), + ), + ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + }, + Effect.scoped, + Effect.provide(FetchHttpClient.layer), +); + +test( + "A long webhook prompt in the delivery log does not end in a broken character", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("webhook-log"); + await runPromise(deliverStraddlingEmoji(app.baseUrl ?? "")); + + await t3.open("/settings/scheduled-tasks"); + await screen.getByRole("button", "Actions for Webhook log").tap(); + await screen.getByRole("menuitem", "Deliveries").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByRole("button", /POST/).tap(); + const prompt = dialog.getByText(/^ { + const block = [...document.querySelectorAll("pre")].find((pre) => + pre.textContent?.startsWith(" +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import JSZip from "jszip"; + +import { test, WEB } from "./t3.ts"; + +const SHEETS = ["Overview", "Actuals", "Forecast"]; +const RELATIONSHIPS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + +async function workbook() { + const archive = new JSZip(); + const sheets = SHEETS.map( + (name, index) => ``, + ).join(""); + archive.file( + "xl/workbook.xml", + `${sheets}`, + ); + const relationships = SHEETS.map( + (_, index) => + ``, + ).join(""); + archive.file("xl/_rels/workbook.xml.rels", `${relationships}`); + for (const [index] of SHEETS.entries()) + archive.file( + `xl/worksheets/sheet${index + 1}.xml`, + `${index + 1}`, + ); + return archive.generateAsync({ type: "uint8array" }); +} + +test( + "Two rapid right arrows advance two tabs in an Excel preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "budget.xlsx": await workbook() }); + const archive = await JSZip.loadAsync(await workbook()); + const manifest = (await archive.file("xl/workbook.xml")!.async("string")).replace( + ' { + const first = document.querySelector( + '[role="tablist"] [role="tab"][aria-selected="true"]', + )!; + first.focus(); + for (let press = 0; press < 2; press++) + document.activeElement?.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), + ); + return null; + }); + await screen.getByRole("grid", /Actuals|Forecast/).waitFor(); + await app.screenshot("after-two-right-arrows"); + await expect + .poll(() => + browser.evaluate( + () => + document + .querySelector('[role="tablist"]') + ?.parentElement?.querySelector('[role="grid"]') + ?.getAttribute("aria-label") ?? null, + ), + ) + .toBe("Forecast"); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("wraparound.xlsx"); + await screen.getByRole("option", "wraparound.xlsx", { exact: false }).tap(); + await browser + .locator('[data-active-tab="true"]') + .getByText("wraparound.xlsx", { exact: true }) + .waitFor(); + const overview = screen.getByRole("tab", "Overview"); + await overview.waitFor(); + + const { ok: showSucceeded, selectedAtSecondPress } = await browser.evaluate(async () => { + const first = document.querySelector( + '[role="tablist"] [role="tab"][aria-selected="true"]', + )!; + const pressRight = () => + document.activeElement?.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), + ); + const postMessage = Worker.prototype.postMessage; + return await new Promise<{ ok: boolean; selectedAtSecondPress: string | null }>((resolve) => { + Worker.prototype.postMessage = function ( + this: Worker, + message: { method?: string; id?: number }, + options?: Transferable[] | StructuredSerializeOptions, + ) { + if (message.method === "show") { + Worker.prototype.postMessage = postMessage; + const onReply = (event: MessageEvent<{ id: number; ok: boolean }>) => { + if (event.data.id !== message.id) return; + this.removeEventListener("message", onReply); + if (event.data.ok !== true) { + resolve({ ok: false, selectedAtSecondPress: null }); + return; + } + // The worker client has queued the first layout, and React has yet to commit it. + queueMicrotask(() => { + const selected = first.getAttribute("aria-selected"); + pressRight(); + resolve({ ok: true, selectedAtSecondPress: selected }); + }); + }; + this.addEventListener("message", onReply); + } + Reflect.apply(postMessage, this, [message, options]); + }; + first.focus(); + pressRight(); + }); + }); + expect(showSucceeded).toBe(true); + expect(selectedAtSecondPress).toBe("true"); + await expect(overview).toBeFocused(); + await app.screenshot("after-wrapping-to-overview"); + await expect(overview).toHaveAttribute("aria-selected", "true"); + await expect(screen.getByRole("grid", "Overview")).toBeVisible(); + }, +);